-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1502 lines (1342 loc) · 37.7 KB
/
main.go
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"
"bytes"
"crypto/md5"
"encoding/xml"
"flag"
"fmt"
"github.com/hydrogen18/stalecucumber"
"github.com/kolo/xmlrpc"
"io/ioutil"
"linedb"
"mime"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
func log(format string, a ...interface{}) {
fmt.Fprintln(os.Stderr, fmt.Sprintf(format, a...))
}
func logerr(err error, format string, a ...interface{}) {
var s = fmt.Sprintf(format, a...)
if s == "" {
if err == nil {
panic("format cannot be empty when err is nil")
}
s = err.Error()
err = nil
}
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %s - %s\n", s, err.Error())
} else {
fmt.Fprintf(os.Stderr, "ERROR: %s\n", s)
}
}
func fuseErr(err, err2 error) error {
if err == nil {
return err2
}
if err2 == nil {
return err
}
return fmt.Errorf("%s; %s", err.Error(), err2.Error())
}
type Report struct {
message string
err error
combined []*Report
}
func ReportMsg(format string, a ...interface{}) *Report {
return &Report{
fmt.Sprintf(format, a...),
nil,
nil,
}
}
func WrapErr(err error, format string, a ...interface{}) *Report {
if err == nil {
panic("err cannot be nil")
}
return &Report{
fmt.Sprintf(format, a...),
err,
nil,
}
}
func CombineReports(r1, r2 *Report) *Report {
if r1 == nil {
return r2
}
if r2 == nil {
return r1
}
return &Report{
"",
nil,
[]*Report{r1, r2},
}
}
func (r *Report) AsText() string {
if r.combined != nil {
s := ""
for _, r2 := range r.combined {
s += r2.AsText()
}
return s
}
if r.err != nil {
return fmt.Sprintf("ERROR: %s - %s\n", r.message, r.err.Error())
}
return fmt.Sprintf("ERROR: %s\n", r.message)
}
func writeFileTempRename(filePath string, data []byte) error {
tmp := filePath + ".tmp"
if err := ioutil.WriteFile(tmp, data, 0666); err != nil {
return err
}
if err := os.Rename(tmp, filePath); err != nil {
return err
}
return nil
}
const defaultConfigFile = "ljdump.config"
// Use dot so it never coinside with LJ journal name
const accountDataDirName = "account.data"
const accountDataDBFileName = "account.linedb"
const serverUrlCompabilitySuffix = "/interface/xmlrpc"
const defaultLJServer = "https://livejournal.com"
type Config struct {
server string
username string
journals []string
password string
dumpDir string
accountDataDir string
}
type commandOptionStringArray []string
func (a *commandOptionStringArray) String() string {
return strings.Join(*a, " ")
}
func (a *commandOptionStringArray) Set(value string) error {
*a = append(*a, value)
return nil
}
func loadConfig() (*Config, *Report) {
configFile := defaultConfigFile
var commandOptions struct {
showUsage bool
server string
username string
journals commandOptionStringArray
passwordFile string
}
parseCommandLine := func() *Report {
programName := filepath.Base(os.Args[0])
flags := flag.NewFlagSet(programName, flag.ContinueOnError)
flags.SetOutput(os.Stderr)
// Avoid printing full usage on command line errors
flags.Usage = func() { }
// Extract `` from the long option usage to construct short usage
findUsageTypeRe := regexp.MustCompile("`[^`]+`")
shorthand := func(longOption, usage string) string {
return fmt.Sprintf("shorthand for -%s %s", longOption, findUsageTypeRe.FindString(usage))
}
addBoolOpt := func(ptr *bool, shortOption rune, longOption, usage string) {
flags.BoolVar(ptr, longOption, false, usage)
flags.BoolVar(ptr, string(shortOption), false, shorthand(longOption, usage))
}
addStrOpt := func(ptr *string, shortOption rune, longOption, defaultValue, usage string) {
flags.StringVar(ptr, longOption, defaultValue, usage)
flags.StringVar(ptr, string(shortOption), defaultValue, shorthand(longOption, usage))
}
addValueOpt := func(ptr flag.Value, shortOption rune, longOption, usage string) {
flags.Var(ptr, longOption, usage)
flags.Var(ptr, string(shortOption), shorthand(longOption, usage))
}
addBoolOpt(&commandOptions.showUsage, 'h', "help", "print usage on stdout and exit")
addStrOpt(&commandOptions.server, 's', "server", defaultLJServer, "LJ `server`")
addStrOpt(&commandOptions.username, 'u', "username", "", "LJ `username`")
addStrOpt(
&commandOptions.passwordFile, 'p', "password-file", "",
"`path` to file with LJ user password, use '-' to read from stdin (password will be echoed)",
)
addValueOpt(&commandOptions.journals, 'j', "journal", "add `journal` to the list of journals to archive. If none are given, use LJ username")
if err := flags.Parse(os.Args[1:]); err != nil {
log("Try '%s --help' for more information", programName)
os.Exit(1)
} else if commandOptions.showUsage {
flags.SetOutput(os.Stdout)
fmt.Printf("Usage: %s [OPTION]...\n\nOption summary:\n", programName)
flags.PrintDefaults()
os.Exit(0)
}
if flags.NArg() != 0 {
return ReportMsg("Unexpected command line argument %s", flags.Arg(0))
}
return nil
}
if r := parseCommandLine(); r != nil {
return nil, r
}
configBytes, err := ioutil.ReadFile(configFile)
if err != nil {
if !os.IsNotExist(err) {
return nil, WrapErr(err, "failed to read %s", configFile)
}
}
var storedConfig struct {
XMLName xml.Name `xml:"ljdump"`
Server string `xml:"server"`
Username string `xml:"username"`
Journals []string `xml:"journal"`
Password string `xml:"password"`
PasswordFile string `xml:"passwordFile"`
}
if len(configBytes) != 0 {
if err = xml.Unmarshal(configBytes, &storedConfig); err != nil {
return nil, WrapErr(err, "failed to parse %s as ljdump config XML", configFile)
}
if storedConfig.Password != "" && storedConfig.PasswordFile != "" {
return nil, ReportMsg(
"Only one of <password>, <passwordFile> can be specified in %s",
configFile,
)
}
}
var config = new(Config)
config.server = commandOptions.server
if config.server == "" {
config.server = storedConfig.Server
}
if config.server != "" {
if strings.HasSuffix(config.server, serverUrlCompabilitySuffix) {
config.server = storedConfig.Server[0 : len(config.server)-len(serverUrlCompabilitySuffix)]
}
} else {
config.server = defaultLJServer
}
config.username = commandOptions.username
if config.username == "" {
config.username = storedConfig.Username
}
if config.username == "" {
return nil, ReportMsg("username must be specified either on command line or in %s", configFile)
}
if len(commandOptions.journals) != 0 {
config.journals = commandOptions.journals
} else {
config.journals = storedConfig.Journals
}
if len(config.journals) == 0 {
config.journals = []string{config.username}
} else {
for i, journal := range config.journals {
if journal == "" {
return nil, ReportMsg("journal %d is empty string", i+1)
}
}
}
// password-file option on the command line take precedence over
// both password and passwordFile in the config.
passwordFile := commandOptions.passwordFile
if passwordFile == "" {
config.password = storedConfig.Password
}
if config.password == "" {
if passwordFile == "" {
passwordFile = os.Getenv("LJDUMP_PASSWORD_FILE")
if passwordFile == "" {
passwordFile = storedConfig.PasswordFile
if passwordFile != "" && !filepath.IsAbs(passwordFile) {
passwordFile = filepath.Join(filepath.Dir(configFile), passwordFile)
}
}
}
if passwordFile == "" {
return nil, ReportMsg(
"the password was not specified in the config file %s and no password file path was given on command line, in LJDUMP_PASSWORD_FILE environment variable or the config file",
configFile,
)
}
if passwordFile == "-" {
fmt.Print("Enter lj user password (it will be echoed): ")
}
passwordBytes, err := readFileFirstLine(passwordFile)
if err != nil {
return nil, WrapErr(err, "failed to read password from %s", passwordFile)
}
if len(passwordBytes) == 0 {
return nil, WrapErr(err, "first line with password in %s was empty", passwordFile)
}
config.password = string(passwordBytes)
}
config.dumpDir = "."
config.accountDataDir = filepath.Join(config.dumpDir, accountDataDirName)
return config, nil
}
// When filePath is -, read stdin
func readFileFirstLine(filePath string) ([]byte, error) {
var f *os.File
var err error
if filePath == "-" {
f = os.Stdin
} else {
f, err = os.Open(filePath)
if err != nil {
return nil, err
}
}
var scanner = bufio.NewScanner(f)
var lineBytes []byte
if scanner.Scan() {
lineBytes = scanner.Bytes()
}
err = scanner.Err()
if f != os.Stdin {
err = fuseErr(err, f.Close())
}
return lineBytes, err
}
type journalContext struct {
config *Config
session *ljSession
name string
dir string
db journalDB
shouldWriteDB bool
origDbLastSync string
newEntries int
newComments int
}
const journalDBFileName = "journal.linedb"
func newJournalContext(session *ljSession, journalName string) *journalContext {
dir := filepath.Join(session.config.dumpDir, journalName)
jcx := &journalContext{
config: session.config,
session: session,
name: journalName,
dir: dir,
}
return jcx
}
type CommentId int64
type UserId int64
type commentMeta struct {
posterId UserId
state string
}
type accountData struct {
fileCounter int
pictureDefaultUrl string
pictureUrlFileMap map[string]string
pictureKeywordUrlMap map[string]string
}
type journalDB struct {
lastSync string
userMap map[UserId]string
commentMap map[CommentId]commentMeta
}
type sortIds []int64
func (a sortIds) Len() int { return len(a) }
func (a sortIds) Less(i, j int) bool { return a[i] < a[j] }
func (a sortIds) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func parseUserId(idstr string) (UserId, error) {
if idstr == "" {
return 0, nil
}
id, err := strconv.ParseInt(idstr, 10, 64)
if err != nil {
err = fmt.Errorf("failed to parse user id string as int64 - %s", err.Error())
}
return UserId(id), err
}
func addSortedMapKeyValue(e *linedb.Encoder, tableName string, m map[string]string) {
keys := make([]string, len(m))
i := 0
for key := range m {
keys[i] = key
i++
}
sort.Strings(keys)
e.Table(tableName)
for _, key := range keys {
e.AddString(key).AddString(m[key]).EndRow()
}
e.EndTable()
}
func writeAccountData(accountData *accountData, config *Config) *Report {
e := linedb.NewByteEncoder()
e.Scalar("fileCounter").AddInt(accountData.fileCounter)
e.Scalar("pictureDefaultUrl").AddString(accountData.pictureDefaultUrl)
e.EmptyLine()
e.Comment("map from url to filename")
addSortedMapKeyValue(e, "pictureUrlFileMap", accountData.pictureUrlFileMap)
e.EmptyLine()
e.Comment("map from picture-keyword to picture-url")
addSortedMapKeyValue(e, "pictureKeywordUrlMap", accountData.pictureKeywordUrlMap)
dbpath := filepath.Join(config.accountDataDir, accountDataDBFileName)
if err := writeFileTempRename(dbpath, e.GetBytes()); err != nil {
return WrapErr(err, "failed to write account data db file %s", dbpath)
}
return nil
}
func readAccountData(config *Config) (*accountData, *Report) {
accountData := &accountData{}
// Initialize maps so entries can be added
accountData.pictureUrlFileMap = make(map[string]string)
accountData.pictureKeywordUrlMap = make(map[string]string)
dbpath := filepath.Join(config.accountDataDir, accountDataDBFileName)
dbdata, err := ioutil.ReadFile(dbpath)
if err != nil {
if !os.IsNotExist(err) {
return nil, WrapErr(err, "")
}
return accountData, nil
}
d := linedb.NewByteDecoder(dbdata)
for d.NextItem() {
switch d.ItemKind {
case linedb.ScalarItem:
switch d.ItemName {
case "fileCounter":
accountData.fileCounter = d.GetInt()
case "pictureDefaultUrl":
accountData.pictureDefaultUrl = d.GetString()
}
case linedb.TableItem:
for d.NextRow() {
switch d.ItemName {
case "pictureUrlFileMap":
accountData.pictureUrlFileMap[d.GetString()] = d.GetString()
case "pictureKeywordUrlMap":
accountData.pictureKeywordUrlMap[d.GetString()] = d.GetString()
}
}
}
}
if err := d.GetError(); err != nil {
return nil, WrapErr(err, "error while parsing account data file %s as linedb", dbpath)
}
return accountData, nil
}
func writeJournalDB(jcx *journalContext) *Report {
e := linedb.NewByteEncoder()
e.Scalar("lastSync").AddString(jcx.db.lastSync)
e.EmptyLine()
e.Comment("map from user-id to user-name")
userIds := make(sortIds, 0, len(jcx.db.userMap))
for userId := range jcx.db.userMap {
userIds = append(userIds, int64(userId))
}
sort.Sort(userIds)
e.Table("users")
for _, userId := range userIds {
e.AddInt64(userId).AddString(jcx.db.userMap[UserId(userId)]).EndRow()
}
e.EndTable()
e.EmptyLine()
e.Comment("map from comment-id to (poster-id state)")
commentIds := make(sortIds, 0, len(jcx.db.commentMap))
for commentId := range jcx.db.commentMap {
commentIds = append(commentIds, int64(commentId))
}
sort.Sort(commentIds)
e.Table("commentMeta")
for _, commentId := range commentIds {
commentMeta := jcx.db.commentMap[CommentId(commentId)]
e.AddInt64(commentId).AddInt64(int64(commentMeta.posterId)).AddString(commentMeta.state).EndRow()
}
e.EndTable()
var dbpath = filepath.Join(jcx.dir, journalDBFileName)
if err := writeFileTempRename(dbpath, e.GetBytes()); err != nil {
return WrapErr(err, "failed to write journal db file %s", dbpath)
}
return nil
}
func readJournalDB(jcx *journalContext) *Report {
var dbpath = filepath.Join(jcx.dir, journalDBFileName)
dbdata, err := ioutil.ReadFile(dbpath)
if err != nil {
if !os.IsNotExist(err) {
return WrapErr(err, "")
}
}
if len(dbdata) == 0 {
log("Converting Python Journal DB into %s", dbpath)
err = readPythonLastRunFile(jcx)
if err == nil {
err = readPythonCommentMeta(jcx)
if err == nil {
err = readPythonUserMap(jcx)
}
}
if err != nil {
return WrapErr(err, "error while reading old python-generated DB files for journal %s", jcx.name)
}
if r := writeJournalDB(jcx); r != nil {
return r
}
} else {
jcx.db.userMap = make(map[UserId]string)
jcx.db.commentMap = make(map[CommentId]commentMeta)
d := linedb.NewByteDecoder(dbdata)
for d.NextItem() {
switch d.ItemKind {
case linedb.ScalarItem:
switch d.ItemName {
case "lastSync":
jcx.db.lastSync = d.GetString()
}
case linedb.TableItem:
for d.NextRow() {
switch d.ItemName {
case "users":
jcx.db.userMap[UserId(d.GetInt64())] = d.GetString()
case "commentMeta":
jcx.db.commentMap[CommentId(d.GetInt64())] = commentMeta{
posterId: UserId(d.GetInt64()),
state: d.GetString(),
}
}
}
}
}
}
jcx.origDbLastSync = jcx.db.lastSync
return nil
}
func readPythonLastRunFile(jcx *journalContext) error {
jcx.db.lastSync = ""
var p = filepath.Join(jcx.dir, ".last")
var f, err = os.Open(p)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
return err
}
// Read only first line with time sync as maxid is derived from comments meta data
var s = bufio.NewScanner(f)
if s.Scan() {
jcx.db.lastSync = s.Text()
}
return fuseErr(s.Err(), f.Close())
}
func readPythonCommentMeta(jcx *journalContext) error {
var p = filepath.Join(jcx.dir, "comment.meta")
var file, err = os.Open(p)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
return err
}
var pythonData map[interface{}]interface{}
pythonData, err = stalecucumber.Dict(stalecucumber.Unpickle(file))
if err == nil {
jcx.db.commentMap = make(map[CommentId]commentMeta, len(pythonData))
for key, value := range pythonData {
var idnum, keyOk = key.(int64)
if !keyOk {
err = fmt.Errorf("Unexpected key type %T in %s", key, p)
break
}
var structValue, valueOk = value.(map[interface{}]interface{})
if !valueOk {
err = fmt.Errorf("Unexpected value type %T in %s", value, p)
break
}
var posterIdStr, posterIdOk = structValue["posterid"].(string)
if !posterIdOk {
err = fmt.Errorf("Unexpected posterid type %T in %s", structValue["posterid"], p)
break
}
var state, stateOk = structValue["state"].(string)
if !stateOk {
err = fmt.Errorf("Unexpected state type %T in %s", structValue["state"], p)
break
}
var posterId UserId
posterId, err = parseUserId(posterIdStr)
if err != nil {
break
}
var id = CommentId(idnum)
jcx.db.commentMap[id] = commentMeta{posterId, state}
}
}
return fuseErr(err, file.Close())
}
func readPythonUserMap(jcx *journalContext) error {
var p = filepath.Join(jcx.dir, "user.map")
var file, err = os.Open(p)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
return err
}
var pythonData map[string]interface{}
pythonData, err = stalecucumber.DictString(stalecucumber.Unpickle(file))
if err == nil {
jcx.db.userMap = make(map[UserId]string, len(pythonData))
for userIdStr, userValue := range pythonData {
var user, userOk = userValue.(string)
if !userOk {
err = fmt.Errorf("Unexpected user name type %T in %s", userValue, p)
break
}
var userId UserId
userId, err = parseUserId(userIdStr)
if err != nil {
break
}
jcx.db.userMap[userId] = user
}
}
return fuseErr(err, file.Close())
}
func writeLJEventDump(jcx *journalContext, eventType byte, itemId int64, event map[string]interface{}) *Report {
buf := bytes.NewBufferString(xml.Header)
var tmparea []byte
var serializeTagValue func(tag string, v interface{}) *Report
// For now allow valid XML names with only ascii characters
isValidXmlTagName := func(s string) bool {
for j, c := range s {
if ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || c == '_' {
continue
}
if j != 0 {
if ('0' <= c && c <= '9') || c == '-' || c == '.' {
continue
}
}
return false
}
return true
}
// xml.EscapeText escapes way too much
addEscapeXmlValue := func(s []byte) {
for _, b := range s {
replace := ""
switch b {
case '<':
replace = "<"
case '>':
replace = ">"
case '&':
replace = "&"
default:
buf.WriteByte(b)
continue
}
buf.WriteString(replace)
}
}
serializeMap := func(m map[string]interface{}) *Report {
keys := make([]string, len(m))
i := 0
for key := range m {
if !isValidXmlTagName(key) {
return ReportMsg("cannot serialize map key '%s' as XML name", key)
}
keys[i] = key
i++
}
// Ensure key order independent from the runtime presentation of map
sort.Strings(keys)
for _, key := range keys {
value := m[key]
if array, isArray := value.([]interface{}); isArray {
for _, elem := range array {
serializeTagValue(key, elem)
}
} else {
serializeTagValue(key, value)
}
}
return nil
}
serializeTagValue = func(tag string, value interface{}) *Report {
buf.WriteByte('<')
buf.WriteString(tag)
if value == nil {
buf.WriteString("/>\n")
return nil
}
buf.WriteByte('>')
switch v := value.(type) {
case int:
tmparea = strconv.AppendInt(tmparea[0:0], int64(v), 10)
buf.Write(tmparea)
case int64:
tmparea = strconv.AppendInt(tmparea[0:0], v, 10)
buf.Write(tmparea)
case string:
tmparea = append(tmparea[0:0], v...)
addEscapeXmlValue(tmparea)
case map[string]interface{}:
buf.WriteByte('\n')
if r := serializeMap(v); r != nil {
return r
}
default:
return ReportMsg("unsupported %T type in received LJEvent", v)
}
buf.WriteString("</")
buf.WriteString(tag)
buf.WriteString(">\n")
return nil
}
buf.WriteString("<event>\n")
if r := serializeMap(event); r != nil {
return r
}
buf.WriteString("</event>\n")
eventPath := filepath.Join(jcx.dir, fmt.Sprintf("%c-%d", eventType, itemId))
if err := writeFileTempRename(eventPath, buf.Bytes()); err != nil {
return WrapErr(err, "")
}
return nil
}
type ljSession struct {
config *Config
client http.Client
lastRequestTime time.Time
loginCookie string
}
// Get LJ session cookie,
// http://www.livejournal.com/doc/server/ljp.csp.flat.protocol.html
func openLJSession(config *Config) (*ljSession, *Report) {
session := &ljSession{
config: config,
}
session.client.Transport = session
calculateChallengeResponse := func(challenge string) string {
var passhash = fmt.Sprintf("%x", md5.Sum([]byte(config.password)))
return fmt.Sprintf("%x", md5.Sum([]byte(challenge+passhash)))
}
v := url.Values{}
v.Set("mode", "getchallenge")
responseMap, r := callLJFlatInterface(session, v)
if r != nil {
return nil, r
}
challenge := responseMap["challenge"]
if challenge == "" {
return nil, ReportMsg("no challenge is resposne")
}
v = url.Values{}
v.Set("mode", "sessiongenerate")
v.Set("user", config.username)
v.Set("auth_method", "challenge")
v.Set("auth_challenge", challenge)
v.Set("auth_response", calculateChallengeResponse(challenge))
v.Set("ipfixed", "1")
log("Logging in to %s", config.server)
responseMap, r = callLJFlatInterface(session, v)
if r != nil {
return nil, r
}
session.loginCookie = responseMap["ljsession"]
if session.loginCookie == "" {
return nil, ReportMsg("failed to login to %s, perhaps the password was invalid", config.server)
}
return session, nil
}
func callLJFlatInterface(session *ljSession, values url.Values) (map[string]string, *Report) {
posturl := session.config.server + "/interface/flat"
resp, err := session.client.PostForm(posturl, values)
if err != nil {
return nil, WrapErr(err, "")
}
s := bufio.NewScanner(resp.Body)
nameValueMap := make(map[string]string)
name := ""
firstLine := ""
for s.Scan() {
if name == "" {
name = s.Text()
if name == "" {
break
}
if firstLine == "" {
firstLine = name
}
} else {
nameValueMap[name] = s.Text()
name = ""
}
}
err = fuseErr(s.Err(), resp.Body.Close())
if err != nil {
return nil, WrapErr(err, "")
}
status := nameValueMap["success"]
if status != "OK" {
errmsg := nameValueMap["errmsg"]
if errmsg == "" {
return nil, ReportMsg(
"Server Error with flat protocol, try again later. mode=%s status=%s\n\t%s",
values.Get("mode"), status, firstLine,
)
} else {
return nil, ReportMsg(
"Server reported error with flat protocol mode=%s status=%s\n\t%s",
values.Get("mode"), status, errmsg,
)
}
}
return nameValueMap, nil
}
func callLJFlatMathod(
method string, session *ljSession, nameValuePairs ...string,
) (map[string]string, *Report) {
v := url.Values{}
v.Set("mode", method)
v.Set("ver", "1")
v.Set("user", session.config.username)
v.Set("auth_method", "cookie")
for i := 0; i != len(nameValuePairs); i += 2 {
v.Set(nameValuePairs[i], nameValuePairs[i+1])
}
return callLJFlatInterface(session, v)
}
func getLJFlatArray(arrayName string, m map[string]string) ([]string, *Report) {
key := arrayName + "_count"
countStr := m[key]
if countStr == "" {
return nil, ReportMsg("no %s key in LJ flat response", key)
}
count, err := strconv.Atoi(countStr)
if err != nil {
return nil, WrapErr(err, "value '%s' for %s key in LJ flat response is not an integer", countStr, key)
}
if count < 0 {
return nil, ReportMsg("value '%s' for %s key in LJ flat response is negative", countStr, key)
}
a := make([]string, count)
for i := 0; i < count; i++ {
key = fmt.Sprintf("%s_%d", arrayName, i+1)
value, present := m[key]
if !present {
return nil, ReportMsg("no %s key in LJ flat response", key)
}
a[i] = value
}
return a, nil
}
func (session *ljSession) RoundTrip(req *http.Request) (*http.Response, error) {
// Remove the referer that http.Client sets on redirect as lj will
// reports with it.
req.Header.Del("Referer")
// Set login and agent headers. Doing it here also avoids
// https://github.com/golang/go/issues/4800
req.Header.Set("User-Agent", "Bot - https://github.com/ibukanov/ljdumpgo; [email protected]")
if session.loginCookie != "" {
req.Header.Set("Cookie", "ljsession="+session.loginCookie)
req.Header.Set("X-LJ-Auth", "cookie")
}
if false {
s, _ := httputil.DumpRequestOut(req, true)
fmt.Println(string(s))
}
// rate-limit number of requests to avoid blacklisting by IP
const minimalTimeBetweenRequests = 250 * time.Millisecond
newRequestTime := time.Now()
if !session.lastRequestTime.IsZero() {
sinceLastRequest := newRequestTime.Sub(session.lastRequestTime)
if sinceLastRequest < minimalTimeBetweenRequests {
time.Sleep(minimalTimeBetweenRequests - sinceLastRequest)
}
}
session.lastRequestTime = newRequestTime
res, err := http.DefaultTransport.RoundTrip(req)
if false {
s, _ := httputil.DumpResponse(res, true)
fmt.Println(string(s))
}
return res, err
}
// Only Unicode letters, digits, dashes and underscores
var blacklistedPictureFilenameChars = regexp.MustCompile(`[^\p{L}\p{N}_-]`)
func convertPictureKeywordToFilename(keyword string) string {
return blacklistedPictureFilenameChars.ReplaceAllString(keyword, "_")
}
func dumpAccountData(session *ljSession, accountData *accountData) *Report {
log("Fetching user info for: %s", session.config.username)
if err := os.MkdirAll(session.config.accountDataDir, 0777); err != nil {
return WrapErr(err, "failed to create directory for account data %s", session.config.accountDataDir)
}
updated := false
responseMap, r := callLJFlatMathod(
"login", session,
"getpickws", "1",
"getpickwurls", "1",
)
if r != nil {
return r
}
keywordArrayName, urlsArrayName := "pickw", "pickwurl"
keywords, r := getLJFlatArray(keywordArrayName, responseMap)
if r != nil {
return r
}
urls, r := getLJFlatArray(urlsArrayName, responseMap)
if r != nil {
return r
}
if len(keywords) != len(urls) {