ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/maps/perl/CFDB.pm
Revision: 1.1
Committed: Wed Aug 9 11:54:02 2006 UTC (17 years, 9 months ago) by elmex
Branch: MAIN
Log Message:
the ipo and board are now converted to JSON and the board works now too.

File Contents

# User Rev Content
1 elmex 1.1 package CFDB;
2     use Carp;
3     use POSIX qw/strftime/;
4    
5     sub write_file {
6     my ($file, $cont) = @_;
7    
8     open my $f, ">", "$file.tmp"
9     or die "Couldn't open file for writing $file.tmp: $!";
10     print $f $cont
11     or die "Couldn't write to file $file.tmp: $!";;
12     close $f
13     or die "Couldn't close written file $file.tmp: $!";
14    
15     rename "$file.tmp", $file;
16     }
17    
18     sub read_file {
19     my ($file) = @_;
20     open my $f, "<", "$file"
21     or die "Couldn't open file $file: $!";
22     return join '', <$f>;
23     }
24    
25     sub new {
26     my ($class, %arg) = @_;
27    
28     my $self = bless {
29     %arg,
30     }, $class;
31    
32     $self->{last_check} = (-M $self->{db_file}) + 1;
33     unless (-e $self->{db_file}) {
34     write_file ($self->{db_file}, cf::to_json ({}));
35     }
36     $self->check_maildb ();
37    
38     $self;
39     }
40    
41     sub check_maildb {
42     my ($self) = @_;
43    
44     if ($self->{last_check} > (-M $self->{db_file})) {
45     $self->{last_check} = -M $self->{db_file};
46    
47     my $maildb = eval { my $m = cf::from_json read_file $self->{db_file}; return $m };
48     if ($@) {
49     warn "ERROR when reading mail database $self->{db_file}: $@\n";
50     $self->{db_file} = $self->{db_file} . ".after_failure";
51     } else {
52     $self->{maildb} = $maildb;
53     }
54     }
55     }
56    
57     # This is not thread or multiprocess safe!
58     # XXX: A second process will (of course) terribly damage the maildatabase
59     # but i assume there wont be any second process.
60     sub sync_maildb {
61     my ($self) = @_;
62    
63     write_file ($self->{db_file}, cf::to_json ($self->{maildb}));
64     $self->{last_check} = -M $self->{db_file};
65     }
66    
67     sub get {
68     my ($self, $key) = @_;
69     $self->check_maildb;
70     $self->{maildb}->{$key};
71     }
72    
73     sub clear {
74     my ($self, $key) = @_;
75     $self->check_maildb;
76     delete $self->{maildb}->{$key};
77     $self->sync_maildb;
78     }
79    
80     sub set {
81     my ($self, $key, $value) = @_;
82     $self->check_maildb;
83     $self->{maildb}->{$key} = $value;
84     $self->sync_maildb;
85     }
86     1