forked from asciimoo/hister
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhister.go
More file actions
2240 lines (2073 loc) · 65.5 KB
/
Copy pathhister.go
File metadata and controls
2240 lines (2073 loc) · 65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"context"
"database/sql"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"maps"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strconv"
"strings"
"time"
_ "time/tzdata"
"github.com/asciimoo/hister/client"
"github.com/asciimoo/hister/config"
"github.com/asciimoo/hister/files"
"github.com/asciimoo/hister/server"
"github.com/asciimoo/hister/server/crawler"
"github.com/asciimoo/hister/server/document"
"github.com/asciimoo/hister/server/extractor"
"github.com/asciimoo/hister/server/indexer"
"github.com/asciimoo/hister/server/model"
"github.com/asciimoo/hister/ui"
"github.com/bodgit/sevenzip"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
const versionBase = "v0.15.0"
var Version = func() string {
if info, ok := debug.ReadBuildInfo(); ok {
for _, s := range info.Settings {
if s.Key == "vcs.revision" && len(s.Value) >= 7 {
return fmt.Sprintf("%s (%s)", versionBase, s.Value[:7])
}
}
}
return versionBase
}()
var (
cliErrorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Bold(true)
cliSuccessStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("10")).Bold(true)
cliInfoStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("12"))
cliWarningStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("11"))
cliBoldStyle = lipgloss.NewStyle().Bold(true)
)
type browserDBCandidates struct {
name string
table_name string
paths_candidates []string
}
type browserDB struct {
name string
table_name string
paths []string
}
var (
cfgFile string
cfg *config.Config
UserAgent = fmt.Sprintf("Mozilla/5.0 (compatible; Hister/%s; +https://hister.org/)", Version)
)
// stringToAnyMap converts map[string]string to map[string]any, used when
// applying --backend-option flag values to crawler config.
func stringToAnyMap(m map[string]string) map[string]any {
result := make(map[string]any, len(m))
for k, v := range m {
result[k] = v
}
return result
}
// parseCookieFlag parses a Set-Cookie header value (e.g. "session=abc; Domain=example.com; Path=/")
// into a CrawlerCookie. Domain is required.
func parseCookieFlag(s string) (config.CrawlerCookie, error) {
c, err := http.ParseSetCookie(s)
if err != nil {
return config.CrawlerCookie{}, fmt.Errorf("cookie %q: %w", s, err)
}
if c.Domain == "" {
return config.CrawlerCookie{}, fmt.Errorf("cookie %q: Domain attribute is required", s)
}
path := c.Path
if path == "" {
path = "/"
}
return config.CrawlerCookie{Name: c.Name, Value: c.Value, Domain: c.Domain, Path: path}, nil
}
// applyCrawlerBackendFlags reads --backend, --backend-option, --header, and --cookie
// flags from cmd and applies them to cfg.Crawler, overriding any config-file values.
func applyCrawlerBackendFlags(cmd *cobra.Command) {
if b, _ := cmd.Flags().GetString("backend"); b != "" {
cfg.Crawler.Backend = b
}
if opts, _ := cmd.Flags().GetStringToString("backend-option"); len(opts) > 0 {
cfg.Crawler.BackendOptions = stringToAnyMap(opts)
}
if headers, _ := cmd.Flags().GetStringToString("header"); len(headers) > 0 {
if cfg.Crawler.Headers == nil {
cfg.Crawler.Headers = make(map[string]string)
}
maps.Copy(cfg.Crawler.Headers, headers)
}
if cookies, _ := cmd.Flags().GetStringArray("cookie"); len(cookies) > 0 {
for _, raw := range cookies {
ck, err := parseCookieFlag(raw)
if err != nil {
exit(1, err.Error())
}
cfg.Crawler.Cookies = append(cfg.Crawler.Cookies, ck)
}
}
}
var rootCmd = &cobra.Command{
Use: "hister",
Short: "Your own search engine",
Long: "Hister - your own search engine",
Version: Version,
//Run: func(_ *cobra.Command, _ []string) {
//},
}
var listenCmd = &cobra.Command{
Use: "listen",
Short: "Start server",
Long: ``,
PreRun: func(_ *cobra.Command, _ []string) {
initIndex()
},
Run: func(cmd *cobra.Command, _ []string) {
if a, err := cmd.Flags().GetString("address"); err == nil && cmd.Flags().Changed("address") {
if err := cfg.UpdateListenAddress(a); err != nil {
exit(1, `Failed to set server address: `+err.Error())
}
}
if cfg.App.AccessToken != "" && strings.HasPrefix(cfg.BaseURL(""), "http://") {
log.Warn().Msg("Using authentication token without https. Token is sent plain-text in network requests.")
}
if len(cfg.Indexer.Directories) > 0 {
indexer.IndexAll(cfg.Indexer.Directories)
go func() {
if err := files.WatchDirectories(context.Background(), cfg.Indexer.Directories, func(path string) {
userID, err := files.FindDirUser(cfg.Indexer.Directories, path)
if err != nil {
log.Error().Err(err).Str("path", path).Msg("Failed to resolve user for file")
return
} else if userID != 0 && !cfg.App.UserHandling {
log.Error().Str("path", path).Msg("user field set but user_handling is not enabled")
return
}
if err := indexer.IndexFile(path, userID); err != nil {
log.Debug().Err(err).Str("path", path).Msg("Failed to index file")
}
}, func(path string) {
if err := indexer.DeleteFile(path); err != nil {
log.Debug().Err(err).Str("path", path).Msg("Failed to delete file from index")
}
}); err != nil {
log.Error().Err(err).Msg("File watcher failed")
}
}()
}
server.Version = Version
server.Listen(cfg)
},
}
var createConfigCmd = &cobra.Command{
Use: "create-config [FILENAME]",
Short: "Create default configuration file",
Args: cobra.MaximumNArgs(1),
Run: func(_ *cobra.Command, args []string) {
dcfg := config.CreateDefaultConfig()
cb, err := yaml.Marshal(dcfg)
if err != nil {
panic(err)
}
if len(args) > 0 {
fname := args[0]
if _, err := os.Stat(fname); err == nil {
exit(1, fmt.Sprintf(`File "%s" already exists`, fname))
}
if err := os.WriteFile(fname, cb, 0o600); err != nil {
exit(1, `Failed to create config file: `+err.Error())
}
fmt.Println(cliSuccessStyle.Render("✓") + " Config file created: " + cliInfoStyle.Render(fname))
} else {
fmt.Print(string(cb))
}
},
}
var listURLsCmd = &cobra.Command{
Use: "list-urls",
Short: "List indexed URLs",
Long: `List all indexed URLs by fetching them from the running server`,
PreRun: func(cmd *cobra.Command, _ []string) {
offline, _ := cmd.Flags().GetBool("offline")
if offline {
initIndex()
}
},
Run: func(cmd *cobra.Command, _ []string) {
offline, _ := cmd.Flags().GetBool("offline")
if offline {
indexer.Iterate(func(doc *document.Document) {
fmt.Println(doc.URL)
})
return
}
c := newClient(client.WithTimeout(0))
pageKey := ""
for {
res, err := c.Search(&indexer.Query{Text: "*", PageKey: pageKey, Sort: "domain"})
if err != nil {
exit(1, "Failed to fetch URLs: "+err.Error())
}
for _, doc := range res.Documents {
fmt.Println(doc.URL)
}
if res.PageKey == "" || len(res.Documents) == 0 {
break
}
pageKey = res.PageKey
}
},
}
var listFilesCmd = &cobra.Command{
Use: "list-files",
Short: "List all watched files for indexing",
Long: `List all files that match the configured directory watch patterns`,
Run: func(_ *cobra.Command, _ []string) {
if len(cfg.Indexer.Directories) == 0 {
exit(1, "No directories configured for watching")
}
for _, dir := range cfg.Indexer.Directories {
expanded := files.ExpandHome(dir.Path)
err := filepath.WalkDir(expanded, func(path string, d fs.DirEntry, err error) error {
if err != nil {
log.Warn().Err(err).Str("path", path).Msg("Error accessing path")
return nil
}
if d.IsDir() {
if path != expanded && files.ShouldSkipDir(d.Name(), dir.Excludes, dir.IncludeHidden) {
return filepath.SkipDir
}
return nil
}
if dir.IsMatching(d.Name()) {
fmt.Println(path)
}
return nil
})
if err != nil {
log.Error().Err(err).Str("directory", expanded).Msg("Failed to walk directory")
}
}
},
}
var browserImportCmd = &cobra.Command{
Use: "import-browser [BROWSER_TYPE] [DB_PATH]",
Short: "Import Chrome, Firefox or auto-detect browsing history",
Long: `
Import browsing history from a supported browser.
Usage:
import-browser - auto-detect all installed browsers
import-browser BROWSER_TYPE - auto-detect database path
import-browser DB_PATH - auto-detect browser type
import-browser BROWSER_TYPE DB_PATH - import a browser type with a specific database path
Supported for browser types for auto-detecting: firefox, chrome, chromium, brave, edge, vivaldi, opera, zen, waterfox, Ladybird
The Firefox URL database is usually located at ~/.mozilla/firefox/*.default/places.sqlite
The Chrome/Chromium URL database is usually located at ~/.config/chromium/Default/History
`,
Args: cobra.RangeArgs(0, 2),
Run: importHistory,
}
// searchDocToMap converts a document to a flat map of all available fields.
func searchDocToMap(d *document.Document) map[string]any {
return map[string]any{
"id": d.ID(),
"url": d.URL,
"title": d.Title,
"domain": d.Domain,
"score": d.Score,
"added": d.Added,
"language": d.Language,
"type": d.Type,
"text": d.Text,
"favicon": d.Favicon,
"user_id": d.UserID,
"html": d.HTML,
}
}
// searchFilterMap returns only the requested keys; returns the full map when fields is empty.
func searchFilterMap(m map[string]any, fields []string) map[string]any {
if len(fields) == 0 {
return m
}
out := make(map[string]any, len(fields))
for _, f := range fields {
out[f] = m[f]
}
return out
}
var searchCmd = &cobra.Command{
Use: "search [search terms]",
Short: "Command line search interface",
Long: "Command line search interface.\nRun it without arguments to use the TUI interface or pass search terms as arguments to get results on the STDOUT.",
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
if err := ui.SearchTUI(cfg); err != nil {
exit(1, err.Error())
}
return
}
qs := strings.Join(args, " ")
format, _ := cmd.Flags().GetString("format")
limit, _ := cmd.Flags().GetInt("limit")
// Parse and validate --fields.
var fields []string
includeHTML := false
if fieldsRaw, _ := cmd.Flags().GetString("fields"); fieldsRaw != "" {
validFields := map[string]bool{
"id": true, "url": true, "title": true, "domain": true, "score": true,
"added": true, "language": true, "type": true, "text": true,
"favicon": true, "user_id": true, "html": true,
}
for f := range strings.SplitSeq(fieldsRaw, ",") {
f = strings.TrimSpace(f)
if f == "" {
continue
}
if !validFields[f] {
exit(1, "Unknown field: "+f+" (valid fields: id, url, title, domain, score, added, language, type, text, favicon, user_id, html)")
}
fields = append(fields, f)
if f == "html" {
includeHTML = true
}
}
}
// CSV column order: use --fields if given, else a sensible default.
csvFields := fields
if format == "csv" && len(csvFields) == 0 {
csvFields = []string{"title", "url", "domain", "score", "added", "language", "text"}
}
// printDoc emits a single document in the requested format.
var csvWriter *csv.Writer
printDoc := func(d *document.Document) {
m := searchFilterMap(searchDocToMap(d), fields)
switch format {
case "json":
b, err := json.Marshal(m)
if err != nil {
exit(1, "Failed to encode JSON: "+err.Error())
}
fmt.Printf("%s,\n", b)
case "csv":
row := make([]string, 0, len(csvFields))
for _, f := range csvFields {
row = append(row, fmt.Sprintf("%v", m[f]))
}
if err := csvWriter.Write(row); err != nil {
exit(1, "Failed to write CSV row: "+err.Error())
}
default:
if len(fields) == 0 {
fmt.Printf("%s\n%s\n\n", d.Title, d.URL)
} else {
parts := make([]string, 0, len(fields))
for _, f := range fields {
parts = append(parts, fmt.Sprintf("%v", m[f]))
}
fmt.Println(strings.Join(parts, "\n"))
if len(fields) > 1 {
fmt.Println()
}
}
}
}
// Format-specific initialisation.
switch format {
case "json":
fmt.Println("[")
case "csv":
csvWriter = csv.NewWriter(os.Stdout)
if err := csvWriter.Write(csvFields); err != nil {
exit(1, "Failed to write CSV header: "+err.Error())
}
}
// Page through all results, streaming output directly.
c := newClient()
var (
pageKey string
total int
done bool
)
for !done {
res, err := c.Search(&indexer.Query{Text: qs, IncludeHTML: includeHTML, PageKey: pageKey})
if err != nil {
exit(1, "Search failed: "+err.Error())
}
for _, d := range res.Documents {
printDoc(d)
total++
if limit > 0 && total >= limit {
done = true
break
}
}
if res.PageKey == "" || len(res.Documents) == 0 {
done = true
}
pageKey = res.PageKey
}
// Format-specific teardown.
switch format {
case "json":
fmt.Println("]")
case "csv":
csvWriter.Flush()
if err := csvWriter.Error(); err != nil {
exit(1, "Failed to write CSV: "+err.Error())
}
}
},
}
var indexCmd = &cobra.Command{
Use: "index URL [URL...]",
Short: "Index URL [URL...]",
Long: "Index one or more URLs",
Args: cobra.MinimumNArgs(0),
PreRun: func(cmd *cobra.Command, args []string) {
recursive, _ := cmd.Flags().GetBool("recursive")
jobID, _ := cmd.Flags().GetString("job-id")
if recursive || jobID != "" {
initDB()
}
},
Run: func(cmd *cobra.Command, args []string) {
global, _ := cmd.Flags().GetBool("global")
targetUserID, _ := cmd.Flags().GetUint("user-id")
userIDChanged := cmd.Flags().Changed("user-id")
if global && userIDChanged {
exit(1, "--global and --user-id are mutually exclusive")
}
var clientOpts []client.Option
if global {
clientOpts = append(clientOpts, client.WithTargetUserID(0))
} else if userIDChanged {
clientOpts = append(clientOpts, client.WithTargetUserID(targetUserID))
}
if allowSensitive, _ := cmd.Flags().GetBool("allow-sensitive"); allowSensitive {
clientOpts = append(clientOpts, client.WithAllowSensitive())
}
force, _ := cmd.Flags().GetBool("force")
recursive, _ := cmd.Flags().GetBool("recursive")
jobID, _ := cmd.Flags().GetString("job-id")
label, _ := cmd.Flags().GetString("label")
noRobots, _ := cmd.Flags().GetBool("no-robots")
cfg.Crawler.UserAgent = UserAgent
applyCrawlerBackendFlags(cmd)
if ua, _ := cmd.Flags().GetString("user-agent"); ua != "" {
UserAgent = ua
cfg.Crawler.UserAgent = ua
}
if cmd.Flags().Changed("delay") {
d, _ := cmd.Flags().GetInt("delay")
cfg.Crawler.Delay = d
}
if cmd.Flags().Changed("timeout") {
t, _ := cmd.Flags().GetInt("timeout")
cfg.Crawler.Timeout = t
}
var robotsCache *crawler.RobotsCache
if !noRobots && !cfg.Crawler.NoRobots {
robotsCache = crawler.NewRobotsCache(cfg.Crawler.UserAgent)
}
if recursive {
// Persistent crawl mode (always).
var (
startURL string
validatorRules *crawler.ValidatorRules
)
// Generate a random job ID when none was given.
if jobID == "" {
var err error
jobID, err = model.GenerateCrawlJobID()
if err != nil {
exit(1, "Failed to generate crawl job ID: "+err.Error())
}
}
existingJob, err := model.GetCrawlJob(jobID)
if err != nil {
exit(1, "Failed to load crawl job: "+err.Error())
}
if existingJob == nil {
// New job: require at least one URL.
if len(args) == 0 {
exit(1, "at least one URL is required to start a new crawl job")
}
startURL = args[0]
maxDepth, _ := cmd.Flags().GetInt("max-depth")
maxLinks, _ := cmd.Flags().GetInt("max-links")
allowedDomains, _ := cmd.Flags().GetStringArray("allowed-domain")
excludeDomains, _ := cmd.Flags().GetStringArray("exclude-domain")
allowedPatterns, _ := cmd.Flags().GetStringArray("allowed-pattern")
excludePatterns, _ := cmd.Flags().GetStringArray("exclude-pattern")
validatorRules = &crawler.ValidatorRules{
MaxDepth: maxDepth,
MaxLinks: maxLinks,
AllowedDomains: allowedDomains,
ExcludeDomains: excludeDomains,
AllowedPatterns: allowedPatterns,
ExcludePatterns: excludePatterns,
}
rulesJSON, err := crawler.MarshalValidatorRules(validatorRules)
if err != nil {
exit(1, "Failed to serialize validator rules: "+err.Error())
}
if err := model.CreateCrawlJob(jobID, startURL, rulesJSON, label); err != nil {
exit(1, "Failed to create crawl job: "+err.Error())
}
fmt.Println("Starting crawl job:", jobID)
} else {
// Resume existing job.
startURL = existingJob.StartURL
validatorRules, err = crawler.UnmarshalValidatorRules(existingJob.ValidatorRules)
if err != nil {
exit(1, "Failed to restore validator rules: "+err.Error())
}
// Use stored label unless --label was explicitly overridden.
if !cmd.Flags().Changed("label") {
label = existingJob.Label
}
fmt.Println("Resuming crawl job:", jobID)
}
validator, err := crawler.NewValidator(validatorRules)
if err != nil {
exit(1, "Invalid crawler rules: "+err.Error())
}
// Pre-seed visited counter from already-processed URLs.
done, err := model.CountCrawlURLsByStatus(jobID, model.CrawlURLDone)
if err != nil {
exit(1, "Failed to count done URLs: "+err.Error())
}
failed, err := model.CountCrawlURLsByStatus(jobID, model.CrawlURLFailed)
if err != nil {
exit(1, "Failed to count failed URLs: "+err.Error())
}
validator.SetVisited(int(done + failed))
cr, err := crawler.NewPersistent(&cfg.Crawler, jobID, robotsCache)
if err != nil {
exit(1, "Failed to initialize persistent crawler: "+err.Error())
}
defer func() {
if err := cr.Close(); err != nil {
log.Warn().Err(err).Msg("crawler close error")
}
}()
if err := crawlAndIndex(startURL, cr, validator, force, label, clientOpts...); err != nil {
exit(1, "Crawl failed: "+err.Error())
}
return
}
// Resume an existing job by ID without --recursive.
if jobID != "" {
existingJob, err := model.GetCrawlJob(jobID)
if err != nil {
exit(1, "Failed to load crawl job: "+err.Error())
}
if existingJob == nil {
exit(1, "Crawl job not found: "+jobID+". Use --recursive to start a new job.")
}
validatorRules, err := crawler.UnmarshalValidatorRules(existingJob.ValidatorRules)
if err != nil {
exit(1, "Failed to restore validator rules: "+err.Error())
}
// Use stored label unless --label was explicitly overridden.
if !cmd.Flags().Changed("label") {
label = existingJob.Label
}
fmt.Println("Resuming crawl job:", jobID)
validator, err := crawler.NewValidator(validatorRules)
if err != nil {
exit(1, "Invalid crawler rules: "+err.Error())
}
done, err := model.CountCrawlURLsByStatus(jobID, model.CrawlURLDone)
if err != nil {
exit(1, "Failed to count done URLs: "+err.Error())
}
failed, err := model.CountCrawlURLsByStatus(jobID, model.CrawlURLFailed)
if err != nil {
exit(1, "Failed to count failed URLs: "+err.Error())
}
validator.SetVisited(int(done + failed))
cr, err := crawler.NewPersistent(&cfg.Crawler, jobID, robotsCache)
if err != nil {
exit(1, "Failed to initialize persistent crawler: "+err.Error())
}
defer func() {
if err := cr.Close(); err != nil {
log.Warn().Err(err).Msg("crawler close error")
}
}()
if err := crawlAndIndex(existingJob.StartURL, cr, validator, force, label, clientOpts...); err != nil {
exit(1, "Crawl failed: "+err.Error())
}
return
}
// Plain index mode (no crawling).
if len(args) == 0 {
exit(1, "at least one URL is required")
}
// Create the crawler once so the bidi backend reuses its
// WebSocket connection and session across all URLs.
cr, err := crawler.New(&cfg.Crawler, robotsCache)
if err != nil {
exit(1, "Failed to create crawler: "+err.Error())
}
defer func() {
if err := cr.Close(); err != nil {
log.Warn().Err(err).Msg("crawler close error")
}
}()
c := newClient(clientOpts...)
for _, u := range args {
if !force {
exists, err := c.DocumentExists(u)
if err != nil {
log.Warn().Err(err).Str("URL", u).Msg("Failed to check if URL is already indexed")
} else if exists {
log.Info().Str("URL", u).Msg("URL already indexed, skipping (use --force to reindex)")
continue
}
}
if err := indexURL(cr, u, label, clientOpts...); err != nil {
log.Warn().Err(err).Str("URL", u).Msg("Failed to index URL")
}
}
},
}
func init() {
indexCmd.Flags().String("label", "", "Label to attach to all indexed documents")
indexCmd.Flags().Bool("force", false, "Reindex URLs even if they are already in the index. Already indexed URLs are skipped otherwise")
indexCmd.Flags().BoolP("recursive", "r", false, "Recursively crawl linked pages")
indexCmd.Flags().Int("max-depth", 0, "Maximum crawl depth (0 = unlimited)")
indexCmd.Flags().Int("max-links", 0, "Maximum number of pages to visit (0 = unlimited)")
indexCmd.Flags().StringArray("allowed-domain", nil, "Domain to allow during crawl (repeatable; empty = all)")
indexCmd.Flags().StringArray("exclude-domain", nil, "Domain to exclude during crawl (repeatable)")
indexCmd.Flags().StringArray("allowed-pattern", nil, "Regexp pattern URLs must match to be followed (repeatable; empty = all)")
indexCmd.Flags().StringArray("exclude-pattern", nil, "Regexp pattern; matching URLs are skipped (repeatable)")
indexCmd.Flags().Bool("global", false, "Make indexed documents available for all users (only for admins in multiuser mode)")
indexCmd.Flags().Uint("user-id", 0, "Index documents under the given user ID (only for admins in multiuser mode)")
indexCmd.Flags().String("job-id", "", "Persistent crawl job ID; use with --recursive to start a new job or alone to resume an existing one")
indexCmd.Flags().String("backend", "", "Crawler backend to use (\"http\", \"chromedp\", or \"bidi\")")
indexCmd.Flags().StringToString("backend-option", nil, "Crawler backend option as key=value (repeatable, e.g. --backend-option exec_path=/usr/bin/chromium)")
indexCmd.Flags().StringToString("header", nil, "Extra HTTP header as KEY=VALUE (repeatable, e.g. --header Accept-Language=en)")
indexCmd.Flags().StringArray("cookie", nil, "HTTP cookie as Set-Cookie value (repeatable, e.g. --cookie \"session=abc; Domain=example.com\")")
indexCmd.Flags().Bool("no-robots", false, "Disable robots.txt compliance during crawling")
indexCmd.Flags().Int("delay", 0, "Delay in seconds between requests (0 = no delay; overrides config)")
indexCmd.Flags().Int("timeout", 0, "Request timeout in seconds (0 = 5s default; overrides config)")
indexCmd.Flags().String("user-agent", "", "User-agent string for requests (overrides config)")
indexCmd.Flags().Bool("allow-sensitive", false, "Skip sensitive content checks allowing sensitive content being indexed.")
}
var deleteCmd = &cobra.Command{
Use: "delete QUERY",
Short: "Remove documents from the index",
Long: `Remove documents from the index using the search query language.
The QUERY syntax is the same as the search queries.
Examples:
hister delete "url:https://example.com/page"
hister delete "url:file:///home/user/file.pdf"
hister delete "domain:example.com"
hister delete "language:en domain:example.com"
Non-admin users are restricted to their own documents by the server.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
c := newClient()
dry, _ := cmd.Flags().GetBool("dry")
verbose, _ := cmd.Flags().GetBool("verbose")
if verbose {
var (
pageKey string
total uint64
)
for {
res, err := c.Search(&indexer.Query{Text: args[0], PageKey: pageKey, Sort: "domain"})
if err != nil {
exit(1, "Failed to search: "+err.Error())
}
if total == 0 {
total = res.Total
}
for _, doc := range res.Documents {
fmt.Println(doc.URL)
}
if res.PageKey == "" || len(res.Documents) == 0 {
break
}
pageKey = res.PageKey
}
if dry {
fmt.Printf("%d document(s) would be deleted\n", total)
} else {
fmt.Printf("Deleting %d document(s)\n", total)
}
return
}
if dry {
res, err := c.Search(&indexer.Query{Text: args[0]})
if err != nil {
exit(1, "Failed to search: "+err.Error())
}
fmt.Printf("%d document(s) would be deleted\n", res.Total)
return
}
if err := c.DeleteDocuments(args[0]); err != nil {
exit(1, "Failed to delete: "+err.Error())
}
},
}
var createUserCmd = &cobra.Command{
Use: "create-user USERNAME",
Short: "Create a new user",
Long: "Create a new user account (requires user_handling to be enabled)",
Args: cobra.ExactArgs(1),
PreRun: func(_ *cobra.Command, _ []string) {
if !cfg.App.UserHandling {
exit(1, "user_handling is not enabled in configuration")
}
initDB()
},
Run: func(cmd *cobra.Command, args []string) {
username := args[0]
password, err := promptPassword("Password: ")
if err != nil {
exit(1, "Failed to read password: "+err.Error())
}
if len(password) < 8 {
exit(1, "password must be at least 8 characters long")
}
confirm, err := promptPassword("Confirm password: ")
if err != nil {
exit(1, "Failed to read password: "+err.Error())
}
if password != confirm {
exit(1, "passwords do not match")
}
isAdmin, _ := cmd.Flags().GetBool("admin")
if _, err := model.CreateUser(username, password, isAdmin); err != nil {
exit(1, "Failed to create user: "+err.Error())
}
fmt.Println(cliSuccessStyle.Render("✓") + " User created: " + cliInfoStyle.Render(username))
},
}
var deleteUserCmd = &cobra.Command{
Use: "delete-user USERNAME",
Short: "Delete a user",
Long: "Delete a user account (requires user_handling to be enabled). Use --purge to also remove all indexed documents belonging to the user.",
Args: cobra.ExactArgs(1),
PreRun: func(_ *cobra.Command, _ []string) {
if !cfg.App.UserHandling {
exit(1, "user_handling is not enabled in configuration")
}
initDB()
},
Run: func(cmd *cobra.Command, args []string) {
username := args[0]
u, err := model.GetUser(username)
if err != nil {
exit(1, "Failed to get user: "+err.Error())
}
c := newClient()
q := fmt.Sprintf("user_id:%d", u.ID)
res, err := c.Search(&indexer.Query{Text: q})
if err != nil {
exit(1, "Failed to check user documents: "+err.Error())
}
if res.Total > 0 {
purge, _ := cmd.Flags().GetBool("purge")
if !purge {
exit(1, fmt.Sprintf("User %q has %d indexed document(s). Use --purge to delete them along with the user.", username, res.Total))
}
if err := c.DeleteDocuments(q); err != nil {
exit(1, "Failed to purge user documents: "+err.Error())
}
fmt.Printf("%s Purged %d document(s) for user %s\n", cliSuccessStyle.Render("✓"), res.Total, cliInfoStyle.Render(username))
}
if err := model.DeleteUser(username); err != nil {
exit(1, "Failed to delete user: "+err.Error())
}
fmt.Println(cliSuccessStyle.Render("✓") + " User deleted: " + cliInfoStyle.Render(username))
},
}
var showUserCmd = &cobra.Command{
Use: "show-user USERNAME",
Short: "Show user information",
Long: "Display information about a user account (requires user_handling to be enabled)",
Args: cobra.ExactArgs(1),
PreRun: func(_ *cobra.Command, _ []string) {
if !cfg.App.UserHandling {
exit(1, "user_handling is not enabled in configuration")
}
initDB()
},
Run: func(cmd *cobra.Command, args []string) {
u, err := model.GetUser(args[0])
if err != nil {
exit(1, "Failed to get user: "+err.Error())
}
admin := "no"
if u.IsAdmin {
admin = "yes"
}
fmt.Println(cliInfoStyle.Render("Username: ") + u.Username)
fmt.Println(cliInfoStyle.Render("ID: ") + fmt.Sprintf("%d", u.ID))
fmt.Println(cliInfoStyle.Render("Admin: ") + admin)
if showToken, _ := cmd.Flags().GetBool("token"); showToken {
fmt.Println(cliInfoStyle.Render("Token: ") + u.Token)
}
fmt.Println(cliInfoStyle.Render("Created at: ") + u.CreatedAt.Format("2006-01-02 15:04:05"))
fmt.Println(cliInfoStyle.Render("Updated at: ") + u.UpdatedAt.Format("2006-01-02 15:04:05"))
},
}
var updateUserCmd = &cobra.Command{
Use: "update-user USERNAME",
Short: "Update a user",
Long: "Update a user account (requires user_handling to be enabled). Use flags to change username, regenerate token, or toggle admin status.",
Args: cobra.ExactArgs(1),
PreRun: func(_ *cobra.Command, _ []string) {
if !cfg.App.UserHandling {
exit(1, "user_handling is not enabled in configuration")
}
initDB()
},
Run: func(cmd *cobra.Command, args []string) {
username := args[0]
changed := false
if newUsername, _ := cmd.Flags().GetString("username"); newUsername != "" {
if err := model.UpdateUsername(username, newUsername); err != nil {
exit(1, "Failed to update username: "+err.Error())
}
fmt.Println(cliSuccessStyle.Render("✓") + " Username changed: " + cliInfoStyle.Render(username) + " → " + cliInfoStyle.Render(newUsername))
username = newUsername
changed = true
}
if regen, _ := cmd.Flags().GetBool("regen-token"); regen {
token, err := model.RegenerateTokenByUsername(username)
if err != nil {
exit(1, "Failed to regenerate token: "+err.Error())
}
fmt.Println(cliSuccessStyle.Render("✓") + " New token for " + cliInfoStyle.Render(username) + ": " + cliInfoStyle.Render(token))
changed = true
}
if toggle, _ := cmd.Flags().GetBool("toggle-admin"); toggle {
isAdmin, err := model.ToggleAdmin(username)
if err != nil {
exit(1, "Failed to toggle admin: "+err.Error())
}
status := "disabled"
if isAdmin {
status = "enabled"
}
fmt.Println(cliSuccessStyle.Render("✓") + " Admin " + status + " for " + cliInfoStyle.Render(username))
changed = true
}
if !changed {
exit(1, "no changes specified - use --username, --regen-token, or --toggle-admin")
}
},
}
var crawlCmd = &cobra.Command{
Use: "crawl",
Short: "Manage persistent crawl jobs",
Long: "Manage persistent crawl jobs",
}
var crawlListCmd = &cobra.Command{
Use: "list",
Short: "List persistent crawl jobs",
Long: "Display all persistent crawl jobs with their status and URL counts",
Args: cobra.NoArgs,
PreRun: func(_ *cobra.Command, _ []string) {
initDB()
},
Run: func(cmd *cobra.Command, args []string) {
jobs, err := model.ListCrawlJobs()
if err != nil {
exit(1, "Failed to list crawl jobs: "+err.Error())
}
if len(jobs) == 0 {
fmt.Println("No crawl jobs found.")
return
}
for _, j := range jobs {
stats, err := model.GetCrawlJobStats(j.ID)
if err != nil {
log.Warn().Err(err).Str("job_id", j.ID).Msg("failed to get job stats")
}
fmt.Printf("%s %-12s %s\n",
cliInfoStyle.Render(j.ID),
j.Status,
j.StartURL,
)
fmt.Printf(" pending: %d done: %d failed: %d skipped: %d created: %s\n",
stats.Pending, stats.Done, stats.Failed, stats.Skipped,
j.CreatedAt.Format("2006-01-02 15:04:05"),
)
}
},
}
var crawlDeleteCmd = &cobra.Command{
Use: "delete JOB_ID",
Short: "Delete a persistent crawl job",
Long: "Delete a crawl job and all its associated URL tracking data",
Args: cobra.ExactArgs(1),
PreRun: func(_ *cobra.Command, _ []string) {
initDB()
},