-
Notifications
You must be signed in to change notification settings - Fork 3
/
hw.pl
930 lines (770 loc) · 24.5 KB
/
hw.pl
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
#!/usr/bin/perl
#
# hw.pl - Hatena Diary Writer (with Loader).
#
# Copyright (C) 2004,2005,2007 by Hiroshi Yuki.
# http://www.hyuki.com/techinfo/hatena_diary_writer.html
#
# Special thanks to:
# - Ryosuke Nanba http://d.hatena.ne.jp/rna/
# - Hahahaha http://www20.big.or.jp/~rin_ne/
# - Ishinao http://ishinao.net/
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# 'Hatena Diary Loader' originally written by Hahahaha(id:rin_ne)
# http://d.hatena.ne.jp/rin_ne/20040825#p7
#
# Modified by Kengo Koseki (id:koseki2)
# http://d.hatena.ne.jp/koseki2/
#
use strict;
my $VERSION = "1.4.1.3";
use LWP::UserAgent;
use HTTP::Request::Common;
use HTTP::Cookies;
use File::Basename;
use Getopt::Std;
use Digest::MD5 qw(md5_base64);
use File::Temp qw(tempdir tempfile);
my $enable_encode = eval('use Encode; 1');
# Prototypes.
sub login();
sub get_rkm($$$$$$$$$$$);
sub logout();
sub update_diary_entry($$$$$$);
sub delete_diary_entry($);
sub doit_and_retry($$);
sub create_it($$$);
sub delete_it($);
sub post_it($$$$$$);
sub get_timestamp();
sub print_debug(@);
sub print_message(@);
sub read_title_body($);
sub find_image_file($);
sub replace_timestamp($);
sub error_exit(@);
sub load_config();
# Hatena user id (if empty, I will ask you later).
my $username = '';
# Hatena password (if empty, I will ask you later).
my $password = '';
# Hatena group name (for hatena group user only).
my $groupname = '';
# Default file names.
my $touch_file = 'touch.txt';
my $cookie_file = 'cookie.txt';
my $config_file = 'config.txt';
my $target_file = '';
# Load diary date.
my $load_date = '';
# Diff diary date.
my $diff_date = '';
# Filter command.
# e.g. 'iconv -f euc-jp -t utf-8 %s'
# where %s is filename, output is stdout.
my $filter_command = '';
# Proxy setting.
my $http_proxy = '';
# Directory for "YYYY-MM-DD.txt".
my $txt_dir = ".";
# Client and server encodings.
my $client_encoding = '';
my $server_encoding = '';
# Hatena URL.
my $hatena_url = 'http://d.hatena.ne.jp';
my $hatena_sslregister_url = 'https://www.hatena.ne.jp/login';
# Crypt::SSLeay check.
eval {
require Crypt::SSLeay;
};
if ($@) {
print_message("WARNING: Crypt::SSLeay is not found, use non-encrypted HTTP mode.");
$hatena_sslregister_url = 'http://www.hatena.ne.jp/login';
}
# Option for LWP::UserAgent.
my %ua_option = (
agent => "HatenaDiaryWriter/$VERSION", # "Mozilla/5.0",
timeout => 180,
);
# Other variables.
my $delete_title = 'delete';
my $cookie_jar;
my $user_agent;
my $rkm; # session id for posting.
# Handle command-line option.
my %cmd_opt = (
'd' => 0, # "debug" flag.
't' => 0, # "trivial" flag.
'u' => "", # "username" option.
'p' => "", # "password" option.
'a' => "", # "agent" option.
'T' => "", # "timeout" option.
'c' => 0, # "cookie" flag.
'g' => "", # "groupname" option.
'f' => "", # "file" option.
'M' => 0, # "no timestamp" flag.
'n' => "", # "config file" option.
'S' => 1, # "SSL" option. This is always 1. Set 0 to login older hatena server.
'l' => "", # "load" diary.
'D' => "", # "diff" option.
);
$Getopt::Std::STANDARD_HELP_VERSION = 1;
getopts("tdu:p:a:T:cg:f:Mn:l:D:", \%cmd_opt) or error_exit("Unknown option.");
if ($cmd_opt{d}) {
print_debug("Debug flag on.");
print_debug("Cookie flag on.") if $cmd_opt{c};
print_debug("Trivial flag on.") if $cmd_opt{t};
&VERSION_MESSAGE();
}
# Override config file name (before load_config).
$config_file = $cmd_opt{n} if $cmd_opt{n};
# Override global vars with config file.
load_config() if -e($config_file);
# Override global vars with command-line options.
$username = $cmd_opt{u} if $cmd_opt{u};
$password = $cmd_opt{p} if $cmd_opt{p};
$groupname = $cmd_opt{g} if $cmd_opt{g};
$ua_option{agent} = $cmd_opt{a} if $cmd_opt{a};
$ua_option{timeout} = $cmd_opt{T} if $cmd_opt{T};
$target_file = $cmd_opt{f} if $cmd_opt{f};
$load_date = $cmd_opt{l} if $cmd_opt{l};
$diff_date = $cmd_opt{D} if $cmd_opt{D};
# Change $hatena_url to Hatena group URL if ($groupname is defined).
if ($groupname) {
$hatena_url = "http://$groupname.g.hatena.ne.jp";
}
# Start.
if ($cmd_opt{l}) {
&load_main;
} elsif ($cmd_opt{D}) {
&diff_main;
} else {
&main;
}
# no-error exit.
exit(0);
# Load diary main sequence. -l option
sub load_main {
my ($year, $month, $day) = parse_date($load_date);
# Login if necessary.
login() unless ($user_agent);
print_message("Load $year-$month-$day.");
my ($title, $body) = load_diary_entry($year,$month,$day);
save_diary_entry($year,$month,$day,$title,$body);
print_message("Load OK.");
logout if ($user_agent);
}
sub diff_main {
my ($year, $month, $day) = parse_date($diff_date);
# Login if necessary.
login() unless ($user_agent);
print_message("Diff $year-$month-$day.");
my ($title, $body) = load_diary_entry($year,$month,$day);
logout if ($user_agent);
my $src = $title."\n".$body;
my $tmpdir = tempdir(CLEANUP => 1);
my($fh, $tmpfilename) = tempfile('diff_XXXXXX', DIR => $tmpdir);
print $fh $src;
close $fh;
my $filename = text_filename($year,$month,$day);
my $cmd = "diff $tmpfilename $filename";
system $cmd;
}
sub parse_date($) {
my ($date) = @_;
if ($date !~ /\A(\d\d\d\d)-(\d\d)-(\d\d)(?:-.+)?(?:\.txt)?\Z/) {
error_exit("Illegal date format.");
}
return ($1, $2, $3);
}
# Main sequence.
sub main {
my $count = 0;
my @files;
# Setup file list.
if ($cmd_opt{f}) {
# Do not check timestamp.
push(@files, $cmd_opt{f});
print_debug("main: files: option -f: @files");
} else {
while (glob("$txt_dir/*.txt")) {
# Check timestamp.
next if (-e($touch_file) and (-M($_) > -M($touch_file)));
push(@files, $_);
}
print_debug("main: files: current dir ($txt_dir): @files");
}
# Process it.
for (@files) {
# Check file name.
next unless (/\b(\d\d\d\d)-(\d\d)-(\d\d)(?:-.+)?\.txt$/);
# Check if it is a file.
next unless (-f $_);
my ($year, $month, $day) = ($1, $2, $3);
my $date = $year . $month . $day;
# Login if necessary.
login() unless ($user_agent);
# Replace "*t*" unless suppressed.
replace_timestamp($_) unless ($cmd_opt{M});
# Read title and body.
my ($title, $body) = read_title_body($_);
# Find image files.
my $imgfile = find_image_file($_);
if ($title eq $delete_title) {
# Delete entry.
print_message("Delete $year-$month-$day.");
delete_diary_entry($date);
print_message("Delete OK.");
} else {
# Update entry.
print_message("Post $year-$month-$day. " . ($imgfile ? " (image: $imgfile)" : ""));
update_diary_entry($year, $month, $day, $title, $body, $imgfile);
print_message("Post OK.");
}
sleep(1);
$count++;
}
# Logout if necessary.
logout if ($user_agent);
if ($count == 0) {
print_message("No files are posted.");
} else {
unless ($cmd_opt{f}) {
# Touch file.
open(FILE, "> $touch_file") or die "$!:$touch_file\n";
print FILE get_timestamp;
close(FILE);
}
}
}
# Login.
sub login() {
$user_agent = LWP::UserAgent->new(%ua_option);
$user_agent->env_proxy;
if ($http_proxy) {
$user_agent->proxy('http', $http_proxy);
print_debug("login: proxy for http: $http_proxy");
$user_agent->proxy('https', $http_proxy);
print_debug("login: proxy for https: $http_proxy");
}
# Ask username if not set.
unless ($username) {
print "Username: ";
chomp($username = <STDIN>);
}
# If "cookie" flag is on, and cookie file exists, do not login.
if ($cmd_opt{c} and -e($cookie_file)) {
print_debug("login: Loading cookie jar.");
$cookie_jar = HTTP::Cookies->new;
$cookie_jar->load($cookie_file);
$cookie_jar->scan(\&get_rkm);
print_debug("login: \$cookie_jar = " . $cookie_jar->as_string);
print_message("Skip login.");
return;
}
# Ask password if not set.
unless ($password) {
print "Password: ";
chomp($password = <STDIN>);
}
my %form;
$form{name} = $username;
$form{password} = $password;
my $r; # Response.
if ($cmd_opt{S}) {
my $diary_url = "$hatena_url/$username/";
$form{backurl} = $diary_url;
$form{mode} = "enter";
if ($cmd_opt{c}) {
$form{persistent} = "1";
}
print_message("Login to $hatena_sslregister_url as $form{name}.");
$r = $user_agent->simple_request(
HTTP::Request::Common::POST("$hatena_sslregister_url", \%form)
);
print_debug("login: " . $r->status_line);
print_debug("login: \$r = " . $r->content());
} else {
# For older version.
print_message("Login to $hatena_url as $form{name}.");
$r = $user_agent->simple_request(
HTTP::Request::Common::POST("$hatena_url/login", \%form)
);
print_debug("login: " . $r->status_line);
if (not $r->is_redirect) {
error_exit("Login: Unexpected response: ", $r->status_line);
}
}
# Check to exist <meta http-equiv="refresh" content="1;URL=..." />
unless (defined $r->header('refresh')) {
print_debug("failed to login. retry...");
# $username = ''; # needless?
$password = '';
# Retry to login.
goto &login;
}
print_message("Login OK.");
print_debug("login: Making cookie jar.");
$cookie_jar = HTTP::Cookies->new;
$cookie_jar->extract_cookies($r);
$cookie_jar->save($cookie_file);
$cookie_jar->scan(\&get_rkm);
print_debug("login: \$cookie_jar = " . $cookie_jar->as_string);
}
# get session id.
sub get_rkm($$$$$$$$$$$) {
my ($version, $key, $val) = @_;
if ($key eq 'rk') {
$rkm = md5_base64($val);
print_debug("get_rkm: \$rkm = " . $rkm);
}
}
# Logout.
sub logout() {
return unless $user_agent;
# If "cookie" flag is on, and cookie file exists, do not logout.
if ($cmd_opt{c} and -e($cookie_file)) {
print_message("Skip logout.");
return;
}
my %form;
$form{name} = $username;
$form{password} = $password;
print_message("Logout from $hatena_url as $form{name}.");
$user_agent->cookie_jar($cookie_jar);
my $r = $user_agent->get("$hatena_url/logout");
print_debug("logout: " . $r->status_line);
if (not $r->is_redirect and not $r->is_success) {
error_exit("Logout: Unexpected response: ", $r->status_line);
}
unlink($cookie_file);
print_message("Logout OK.");
}
# Update entry.
sub update_diary_entry($$$$$$) {
my ($year, $month, $day, $title, $body, $imgfile) = @_;
if ($cmd_opt{t}) {
# clear existing entry. if the entry does not exist, it has no effect.
doit_and_retry("update_diary_entry: CLEAR.", sub { return post_it($year, $month, $day, "", "", "") });
}
# Make empty entry before posting.
doit_and_retry("update_diary_entry: CREATE.", sub { return create_it($year, $month, $day) });
# Post.
doit_and_retry("update_diary_entry: POST.", sub { return post_it($year, $month, $day, $title, $body, $imgfile) });
}
# Delete entry.
sub delete_diary_entry($) {
my ($date) = @_;
# Delete.
doit_and_retry("delete_diary_entry: DELETE.", sub { return delete_it($date) });
}
# Do the $funcref, and retry if fail.
sub doit_and_retry($$) {
my ($msg, $funcref) = @_;
my $retry = 0;
my $ok = 0;
while ($retry < 2) {
$ok = $funcref->();
if ($ok or not $cmd_opt{c}) {
last;
}
print_debug("try_it: $msg");
unlink($cookie_file);
print_message("Old cookie. Retry login.");
login();
$retry++;
}
if (not $ok) {
error_exit("try_it: Check username/password.");
}
}
# Delete.
sub delete_it($) {
my ($date) = @_;
print_debug("delete_it: $date");
$user_agent->cookie_jar($cookie_jar);
my $r = $user_agent->simple_request(
HTTP::Request::Common::POST("$hatena_url/$username/edit",
# Content_Type => 'form-data',
Content => [
mode => "delete",
date => $date,
rkm => $rkm,
]
)
);
print_debug("delete_it: " . $r->status_line);
if ((not $r->is_redirect()) and (not $r->is_success())) {
error_exit("Delete: Unexpected response: ", $r->status_line);
}
print_debug("delete_it: Location: " . $r->header("Location"));
# Check the result. ERROR if the location ends with the date.
# (Note that delete error != post error)
if ($r->header("Location") =~ m(/$date$)) { # /)){
print_debug("delete_it: returns 0 (ERROR).");
return 0;
} else {
print_debug("delete_it: returns 1 (OK).");
return 1;
}
}
sub create_it($$$) {
my ($year, $month, $day) = @_;
print_debug("create_it: $year-$month-$day.");
$user_agent->cookie_jar($cookie_jar);
my $r = $user_agent->simple_request(
HTTP::Request::Common::POST("$hatena_url/$username/edit",
Content_Type => 'form-data',
Content => [
mode => "enter",
timestamp => get_timestamp,
year => $year,
month => $month,
day => $day,
trivial => $cmd_opt{t},
rkm => $rkm,
# Important:
# If (entry does exists) { append empty string (i.e. nop) }
# If (entry does not exist) { create empty entry }
title => "",
body => "",
date => "",
]
)
);
print_debug("create_it: " . $r->status_line);
if ((not $r->is_redirect()) and (not $r->is_success())) {
error_exit("Create: Unexpected response: ", $r->status_line);
}
print_debug("create_it: Location: " . $r->header("Location"));
# Check the result. OK if the location ends with the date.
if ($r->header("Location") =~ m(/$year$month$day$)) { # /)){
print_debug("create_it: returns 1 (OK).");
return 1;
} else {
print_debug("create_it: returns 0 (ERROR).");
return 0;
}
}
sub post_it($$$$$$) {
my ($year, $month, $day, $title, $body, $imgfile) = @_;
print_debug("post_it: $year-$month-$day.");
$user_agent->cookie_jar($cookie_jar);
my $r = $user_agent->simple_request(
HTTP::Request::Common::POST("$hatena_url/$username/edit",
Content_Type => 'form-data',
Content => [
mode => "enter",
timestamp => get_timestamp,
year => $year,
month => $month,
day => $day,
title => $title,
trivial => $cmd_opt{t},
rkm => $rkm,
# Important:
# This entry must already exist.
body => $body,
date => "$year$month$day",
image => [
$imgfile,
]
]
)
);
print_debug("post_it: " . $r->status_line);
if (not $r->is_redirect) {
error_exit("Post: Unexpected response: ", $r->status_line);
}
print_debug("post_it: Location: " . $r->header("Location"));
# Check the result. OK if the location ends with the date.
if ($r->header("Location") =~ m(/$year$month$day$)) { # /)){
print_debug("post_it: returns 1 (OK).");
return 1;
} else {
print_debug("post_it: returns 0 (ERROR).");
return 0;
}
}
# Get "YYYYMMDDhhmmss" for now.
sub get_timestamp() {
my (@week) = qw(Sun Mon Tue Wed Thu Fri Sat);
my ($sec, $min, $hour, $day, $mon, $year, $weekday) = localtime(time);
$year += 1900;
$mon++;
$mon = "0$mon" if $mon < 10;
$day = "0$day" if $day < 10;
$hour = "0$hour" if $hour < 10;
$min = "0$min" if $min < 10;
$sec = "0$sec" if $sec < 10;
$weekday = $week[$weekday];
return "$year$mon$day$hour$min$sec";
}
# Show version message. This is called by getopts.
sub VERSION_MESSAGE {
print <<"EOD";
Hatena Diary Writer(+Loader) Version $VERSION
Copyright (C) 2004,2005,2007,2009 by Hiroshi Yuki / +Loader by Kengo Koseki.
EOD
}
# Debug print.
sub print_debug(@) {
if ($cmd_opt{d}) {
print "DEBUG: ", @_, "\n";
}
}
# Print message.
sub print_message(@) {
print @_, "\n";
}
# Error exit.
sub error_exit(@) {
print "ERROR: ", @_, "\n";
unlink($cookie_file);
exit(1);
}
# Read title and body.
sub read_title_body($) {
my ($file) = @_;
# Execute filter command, if any.
my $input = $file;
if ($filter_command) {
$input = sprintf("$filter_command |", $file);
}
print_debug("read_title_body: input: $input");
if (not open(FILE, $input)) {
error_exit("$!:$input");
}
my $title = <FILE>; # first line.
chomp($title);
my $body = join('', <FILE>); # rest of all.
close(FILE);
# Convert encodings.
if ($enable_encode and ($client_encoding ne $server_encoding)) {
print_debug("Convert from $client_encoding to $server_encoding.");
Encode::from_to($title, $client_encoding, $server_encoding);
Encode::from_to($body, $client_encoding, $server_encoding);
}
return($title, $body);
}
# Find image file.
sub find_image_file($) {
my ($fulltxt) = @_;
my ($base, $path, $type) = fileparse($fulltxt, qr/\.txt/);
for my $ext ('jpg', 'png', 'gif') {
my $imgfile = "$path$base.$ext";
if (-e $imgfile) {
if ($cmd_opt{f}) {
print_debug("find_image_file: -f option, always update: $imgfile");
return $imgfile;
} elsif (-e($touch_file) and (-M($imgfile) > -M($touch_file))) {
print_debug("find_image_file: skip $imgfile (not updated).");
next;
} else {
print_debug("find_image_file: $imgfile");
return $imgfile;
}
}
}
return undef;
}
# Replace "*t*" with timestamp.
sub replace_timestamp($) {
my ($filename) = @_;
# Read.
open(FILE, $filename) or error_exit("$!: $filename");
my $file = join('', <FILE>);
close(FILE);
# Replace.
my $newfile = $file;
$newfile =~ s/^\*t\*/"*" . time() . "*"/gem;
# Write if replaced.
if ($newfile ne $file) {
print_debug("replace_timestamp: $filename");
open(FILE, "> $filename") or error_exit("$!: $filename");
print FILE $newfile;
close(FILE);
}
}
# Show help message. This is called by getopts.
sub HELP_MESSAGE {
print <<"EOD";
Usage: perl $0 [Options]
Options:
--version Show version.
--help Show this message.
-t Trivial. Use this switch for trivial edit (i.e. typo).
-d Debug. Use this switch for verbose log.
-u username Username. Specify username.
-p password Password. Specify password.
-a agent User agent. Default value is HatenaDiaryWriter/$VERSION.
-T seconds Timeout. Default value is 180.
-c Cookie. Skip login/logout if $cookie_file exists.
-g groupname Groupname. Specify groupname.
-f filename File. Send only this file without checking timestamp.
-M Do NOT replace *t* with current time.
-n config_file Config file. Default value is $config_file.
-l YYYY-MM-DD Load diary.
Config file example:
#
# $config_file
#
id:yourid
password:yourpassword
cookie:cookie.txt
# txt_dir:/usr/yourid/diary
# touch:/usr/yourid/diary/hw.touch
# proxy:http://www.example.com:8080/
# g:yourgroup
# client_encoding:Shift_JIS
# server_encoding:UTF-8
## for Unix, if Encode module is not available.
# filter:iconv -f euc-jp -t utf-8 %s
EOD
}
# Load config file.
sub load_config() {
print_debug("Loading config file ($config_file).");
if (not open(CONF, $config_file)) {
error_exit("Can't open $config_file.");
}
while (<CONF>) {
chomp;
if (/^\#/) {
# skip comment.
} elsif (/^$/) {
# skip blank line.
} elsif (/^id:([^:]+)$/) {
$username = $1;
print_debug("load_config: id:$username");
} elsif (/^g:([^:]+)$/) {
$groupname = $1;
print_debug("load_config: g:$groupname");
} elsif (/^password:(.*)$/) {
$password = $1;
print_debug("load_config: password:********");
} elsif (/^cookie:(.*)$/) {
$cookie_file = glob($1);
$cmd_opt{c} = 1; # If cookie file is specified, Assume '-c' is given.
print_debug("load_config: cookie:$cookie_file");
} elsif (/^proxy:(.*)$/) {
$http_proxy = $1;
print_debug("load_config: proxy:$http_proxy");
} elsif (/^client_encoding:(.*)$/) {
$client_encoding = $1;
print_debug("load_config: client_encoding:$client_encoding");
} elsif (/^server_encoding:(.*)$/) {
$server_encoding = $1;
print_debug("load_config: server_encoding:$server_encoding");
} elsif (/^filter:(.*)$/) {
$filter_command = $1;
print_debug("load_config: filter:$filter_command");
} elsif (/^txt_dir:(.*)$/) {
$txt_dir = glob($1);
print_debug("load_config: txt_dir:$txt_dir");
} elsif (/^touch:(.*)$/) {
$touch_file = glob($1);
print_debug("load_config: touch:$touch_file");
} else {
error_exit("Unknown command '$_' in $config_file.");
}
}
close(CONF);
}
# from hateda loader
# Load entry.
sub load_diary_entry($$$) {
my ($year, $month, $day) = @_;
print_debug("load_it: $hatena_url/$username/edit?date=$year$month$day");
$user_agent->cookie_jar($cookie_jar);
my $r = $user_agent->simple_request(
HTTP::Request::Common::GET("$hatena_url/$username/edit?date=$year$month$day"));
print_debug("load_it: " . $r->status_line);
if (not $r->is_success()) {
error_exit("Load: Unexpected response: ", $r->status_line);
}
# Check entry exist.
$r->content =~ /<form .*?action="\.\/edit" .*?>(.*<\/textarea>)/s;
my $form_data = $1;
$form_data =~ /<input type="hidden" name="date" value="(\d\d\d\d\d\d\d\d)">/;
my $resp_date = $1;
if($resp_date ne "$year$month$day") {
error_exit("Load: Not exist entry.");
}
# Get title and body.
my $title = "";
if ($form_data =~ /<input name="title" .*?value="(.*?)"/) {
$title = $1;
}
$form_data =~ /<textarea .*?>(.*?)<\/textarea>/s;
my $body = $1;
# Unescape string.
$title = unescape($title);
$body = unescape($body);
# Convert encodings.
if ($enable_encode and ($client_encoding ne $server_encoding)) {
print_debug("Convert from $client_encoding to $server_encoding.");
Encode::from_to($title, $server_encoding, $client_encoding);
Encode::from_to($body, $server_encoding, $client_encoding);
}
print_debug("load_it: OK");
return ($title, $body);
}
sub text_filename($$$) {
my ($year,$month,$day) = @_;
my $datename = "$year-$month-$day";
while (glob("$txt_dir/*.txt")) {
next unless (/\b(\d\d\d\d-\d\d-\d\d)(?:-.+)?\.txt$/);
next unless (-f $_);
return $_ if $datename eq $1
}
my $filename = "$txt_dir/$datename.txt";
return $filename;
}
sub save_diary_entry($$$$) {
my ($year,$month,$day,$title,$body) = @_;
my $filename = text_filename($year,$month,$day);
# backup($filename);
if (not open(OUT, ">$filename")) {
error_exit("$!:$filename");
}
print OUT $title."\n";
print OUT $body;
close(OUT);
print_debug("save_diary_entry: return 1 (OK)");
return 1;
}
sub backup($) {
my ($filename) = @_;
# Check if file is exist. (Skip)
if(-f "$filename") {
my $bakext = 0;
while(-f "$filename.$bakext") {
$bakext++;
}
if (not rename("$filename", "$filename.$bakext")) {
error_exit("$!:$filename");
}
}
}
sub unescape($) {
my ($str) = @_;
my @escape_string = (
"<<",
">>",
""\"",
" ",
);
for(@escape_string) {
my ($from, $to) = split(/;/);
$str =~ s/$from;/$to/sg;
}
$str =~ s/&#(\d+);/chr($1)/seg;
$str =~ s/&/&/sg;
return $str;
}
__END__