aboutsummaryrefslogtreecommitdiff
path: root/bin/mailsync
blob: 2667c600f2b9e1f483606f14898dfb3067e8a7ef (plain)
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
#! /usr/bin/python
# Copyright (C) 2014-2015 Sergey Poznyakoff
#  
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function
import os
import sys
import errno
import getopt
import mailbox
import re
import MySQLdb
from time import strftime, strptime
from subprocess import Popen,PIPE,call

dbg = 0
dry_run = 0
reset_state = 0

EX_OK = 0
EX_FAILURE = 1
EX_USAGE = 64
EX_CONFIG = 78

kwtab = {
    'core': {
        'rootdir': False,
        'etcdir' : True,
        'listfile': False,
        'indexrootdir': True,
        'mboxrootdir': True,
        'htmlrootdir': True,
        'base_url': True,
    },
    'mysql': {
        'host': False,
        'user': False,
        'passwd': False,
        'db': False,
        'port': False,
        'unix_socket': False,
        'connect_timeout': False,
        'init_command': False,
        'read_default_file': False,
        'read_default_group': False,
        'use_unicode': False,
        'charset': False,
        'sql_mode': False,
        #ssl: FIXME
    }
}    

conf = { }

os.environ["PATH"] = os.path.dirname(sys.argv[0]) + ':' + os.environ["PATH"] 

status = EX_OK

def debug(lev, text):
    if (dbg >= lev):
        print("debug: %s" % text, file=sys.stderr)

def absdir(dir):
    if dir.startswith('/'):
        return dir
    elif 'rootdir' in conf['core']:
        return conf['core']['rootdir'] + '/' + dir
    else:
        print("core.rootdir not set in config", file=sys.stderr)
        exit(EX_CONFIG)
        
def get_state(listid):
    file = absdir(conf['core']['htmlrootdir'] + "/" + listid + "/.state")
    try:
        with open(file, 'r') as f:
            r = int(f.readline().rstrip())
    except:
        r = 0
    return r

def save_state(listid,n):
    file = absdir(conf['core']['htmlrootdir'] + "/" + listid + "/.state")
    try:
        with open(file, 'w') as f:
            f.write(str(n) + "\n")
    except IOError:
        print("cannot write %s: %s" % (file,sys.exc_info()), file=sys.stderr)
        status = EX_FAILURE

def save_timestamp(listid,ts):
    file = absdir(conf['core']['htmlrootdir'] + "/" + listid + "/.timestamp")
    try:
        with open(file, 'w') as f:
            f.write(strftime('%s', ts) + "\n")
    except IOError:
        print("cannot write %s: %s" % (file,sys.exc_info()), file=sys.stderr)
        status = EX_FAILURE


def mboxtohtml(listid):
    name = absdir(conf['core']['mboxrootdir'] + "/" + listid + ".mbox/" + listid + ".mbox")
    try:
        inbox = mailbox.mbox(name)
    except IOError as e:
        if e.errno == errno.ENOENT:
            print("%s: archive does not exist" % (name))
            return False
        raise
            
    if reset_state:
        n = 0
    else:
        n = get_state(listid)
    t = 0
    for message in inbox.values()[n:]:
        frm = message.get_from()
        s = frm.split(' ', 1)
        t = strptime(s[1], '%a %b %d %H:%M:%S %Y')
        period = strftime('%Y-%m', t)
        periodh = strftime('%B, %Y', t)
        dirname = absdir(conf['core']['htmlrootdir'] + "/" + listid + "/" + period)
        if not os.path.exists(dirname):
            os.makedirs(dirname, 02775)

        cmd = [ 'mhonarc',
                '-add',
                '-rcfile', absdir(conf['core']['etcdir'] + '/main.mrc'),
                '-outdir', dirname,
                '-definevar', 'gray_period=' + period,
                "-definevar", 'gray_period_pretty="' + periodh + '"',
                '-definevar', 'gray_base_url="' + conf['core']['base_url'] + '"',
                '-definevar', 'gray_listname=' + listid ];
        debug(1, "running %s" % str(cmd))
        if not dry_run:
            p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
            (out,err) = p.communicate(str(message));
            if p.returncode < 0:
                print("command \"%s\" exited on signal %s" %
                      (str(cmd), -p.returncode), file=sys.stderr)
                status = EX_FAILURE
            elif p.returncode:
                print("command \"%s\" exited with code %s" %
                      (str(cmd), p.returncode), file=sys.stderr)
                status = EX_FAILURE
            if err:
                print("\"%s\": %s" % (str(cmd), err), file=sys.stderr)
                status = EX_FAILURE
                        
    if t > 0:
        n = len(inbox)
        debug(1, "%s: %d messages, timestamp %d" % (name,n,t))
        save_state(listid, n)
	save_timestamp(listid, t)
        return True 
    debug(1, "%s: not modified" % (name))
    return False
        
def savane_lists(file = None):
    if 'listfile' in conf['core']:
        with open(conf['core']['listfile'], 'r') as f:
            for line in f:
                r = line.strip()
                if len(r) != 0 and r[0] != '#':
                    yield(r)
    else:
        db = MySQLdb.connect(**conf['mysql'])
        cur = db.cursor()
        cur.execute("select list_name from mail_group_list where status=5")
        for row in cur.fetchall():
            yield(row[0])
        db.close

def reindex(listid):
    outdir = absdir(conf['core']['indexrootdir'] + "/" + listid)
    if not os.path.exists(outdir):
        os.makedirs(outdir, 02775)
    indir = absdir(conf['core']['htmlrootdir'] + "/" + listid)
    if os.path.exists(indir):
        cmd = 'mknmz -q -O ' + outdir + \
              ' --allow="msg[0-9][0-9]*\.html" ' + indir
        debug(1, "running %s" % str(cmd))
        if not dry_run:
            p = Popen(cmd, shell=True)
            r = p.wait()
            if r != 0:
                print("command '%s' exited with status %s" % (cmd,r), file=sys.stderr)
                status = EX_FAILURE

def mailsync(l):
    if mboxtohtml(l):
        reindex(l)

def read_config(file):
    debug(1, "reading configuration from %s" % file)
    lno = 0
    section = None
    err = 0
    with open(file, 'r') as f:
        for line in f:
            lno += 1
            r = line.strip()
            if r.startswith('[') and r.endswith(']'):
                section = r[1:-1]
                if not section in kwtab:
                    print("%s:%s: unknown section" % (file,lno),
                          file=sys.stderr)
                    err += 1
                conf[section] = {}
            elif len(r) != 0 and r[0] != '#':
                if not section:
                    print("%s:%s: statement out of section" % (file,lno),
                          file=sys.stderr)
                    continue

                (kw,val) = re.split('\s*=\s*', r, 1)
                if not kw in kwtab[section].keys():
                    print("%s:%s: unknown keyword" % (file,lno),
                          file=sys.stderr)
                    err += 1
                conf[section][kw] = val

        if not 'core' in conf:
            print("%s: [core] section missing" % (file), file=sys.stderr)
            err += 1
        for s in kwtab.keys():
            for k in kwtab[s].keys():
                if kwtab[s][k] and not k in conf[s]:
                    print("%s: %s.%s not set" % (file,s,k), file=sys.stderr)
                    err += 1
        if err:
            exit(EX_CONFIG)

def usage(code=0):
    if code:
        file = sys.stderr
    else:
        file = sys.stdout
    print("""usage: %s [OPTIONS] [LISTID...]

OPTIONS are:

        -d, --debug           increase debug verbosity
        -n, --dry-run         do nothing, print what would have been done
        -c, --config=FILE     read configuration from FILE
        -r, --reset           reset list state

        -h, --help            show this help list

""" % sys.argv[0], file=file)
    exit(code)
                
if __name__ == '__main__':
    config = ''
    try:
        opts, args = getopt.getopt(sys.argv[1:], "dhc:nr",
                                   ["debug", "help", "config=", "dry-run",
                                    "reset"])
    except getopt.GetoptError:
        usage(EX_USAGE)

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
        elif o in ("-d", "--debug"):
            dbg += 1
        elif o in ("-c", "--config"):
            config = a
        elif o in ("-n", "--dry-run"):
            dry_run = 1
        elif o in ("-r", "--reset"):
            reset_state = 1

    if dry_run:
        dbg += 1

    if config == '':
        config = os.path.abspath(os.path.dirname(sys.argv[0]) + '/../etc/mailsync.conf')
        
    read_config(config)

    if len(args) > 0:
        for l in args:
            mailsync(l)
    else:
        for l in savane_lists():
            mailsync(l)

    exit(status)



        

    


        


Return to:

Send suggestions and report system problems to the System administrator.