~sslapp/gibareto/screenlet

« back to all changes in this revision

Viewing changes to lib/gb_backup.py

  • Committer: Miguel Ángel Molina
  • Date: 2011-01-01 17:07:01 UTC
  • Revision ID: sslapp@gmail.com-20110101170701-qmamqijbvxm44pky
Initial upload

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# -*- coding: utf-8 -*-
 
3
#
 
4
#  lib.gb_backup.py
 
5
#
 
6
#  Copyright 2010 Miguel Ángel Molina <sslapp@gmail.com>
 
7
#
 
8
#  This program is free software; you can redistribute it and/or modify
 
9
#  it under the terms of the GNU General Public License as published by
 
10
#  the Free Software Foundation; either version 3 of the License, or
 
11
#  (at your option) any later version.
 
12
#
 
13
#   This program is distributed in the hope that it will be useful,
 
14
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
15
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
16
#   GNU General Public License for more details.
 
17
#
 
18
#   You should have received a copy of the GNU General Public License
 
19
#   along with this program; if not, see <http://www.gnu.org/licenses/>
 
20
#
 
21
#   Este programa es software libre: usted puede redistribuirlo y/o modificarlo
 
22
#   bajo los términos de la Licencia Pública General GNU publicada
 
23
#   por la Fundación para el Software Libre, ya sea la versión 3
 
24
#   de la Licencia, o (a su elección) cualquier versión posterior.
 
25
#
 
26
#   Este programa se distribuye con la esperanza de que sea útil, pero
 
27
#   SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita
 
28
#   MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO.
 
29
#   Consulte los detalles de la Licencia Pública General GNU para obtener
 
30
#   una información más detallada.
 
31
#
 
32
#   Debería haber recibido una copia de la Licencia Pública General GNU
 
33
#   junto a este programa.
 
34
#   En caso contrario, consulte <http://www.gnu.org/licenses/>.
 
35
 
 
36
import cPickle
 
37
import os
 
38
import time
 
39
from lib import gb_imap
 
40
 
 
41
IDS_FILE = 'ids.pkl'
 
42
MAILBOX_DIR = 'mailbox/'
 
43
LAST_RUN_DATE_FILE = 'last-run-date.txt'
 
44
IDS = {}
 
45
 
 
46
def backup(user_data, date_from='', date_to='', from_last=True):
 
47
  """Backup e-mails.
 
48
 
 
49
    Params:
 
50
    user_data:  account data
 
51
    date_from:  Start date  (format: ddmmyyyy) (default: 01011980)
 
52
    date_to:    End date    (format: ddmmyyyy) (default: today)
 
53
    from_last:  Boolean     (True: from last run date)
 
54
 
 
55
    Backup e-mails
 
56
  """
 
57
 
 
58
  global IDS
 
59
 
 
60
  extra = '/'
 
61
  if (user_data['backup_path'][-1] == '/'):
 
62
    extra = ''
 
63
  BACKUP_PATH = user_data['backup_path'] + extra + user_data['user_name'].split('@')[0]
 
64
  MAILBOX_PATH = os.path.join(BACKUP_PATH, MAILBOX_DIR)
 
65
  IDS_PATH = os.path.join(BACKUP_PATH, IDS_FILE)
 
66
  LAST_RUN_DATE_PATH = os.path.join(BACKUP_PATH, LAST_RUN_DATE_FILE)
 
67
  Num2month = {1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun',
 
68
               7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'}
 
69
 
 
70
  NOW = time.strftime("%d%m%Y", time.localtime())
 
71
  NOW = NOW[0:2] + '-' + Num2month[int(NOW[2:4])] + '-' + NOW[4:8]
 
72
 
 
73
  start_date = date_from
 
74
  end_date= date_to
 
75
 
 
76
  # Check if mailbox path exists and create it if not
 
77
  if (not os.path.isdir(MAILBOX_PATH)):
 
78
    try:
 
79
      os.makedirs(MAILBOX_PATH, 0700)
 
80
    except:
 
81
      raise Exception(_("Error: can't make directory: "),MAILBOX_PATH)
 
82
 
 
83
  # Check params
 
84
  if (from_last):
 
85
    if (os.path.isfile(LAST_RUN_DATE_PATH)):
 
86
      try:
 
87
        fd = open(LAST_RUN_DATE_PATH, 'r')
 
88
        # Read the last run date from file
 
89
        start_date = fd.read(11)
 
90
        end_date = ''
 
91
        fd.close()
 
92
      except:
 
93
        raise Exception(_('Error opening or reading file:'), LAST_RUN_DATE_PATH)
 
94
    else:
 
95
      start_date = '01-Jan-1980'
 
96
  else:
 
97
    if (date_from == ''):
 
98
      start_date = '01-Jan-1980'
 
99
    else:
 
100
      try:
 
101
        start_date = date_from[0:2] + '-' + Num2month[int(date_from[2:4])] + '-' + date_from[4:8]
 
102
      except:
 
103
        raise Exception(_('Date from error'))
 
104
 
 
105
    if (date_to == ''):
 
106
      end_date = NOW
 
107
    else:
 
108
      try:
 
109
        end_date = date_to[0:2] + '-' + Num2month[int(date_to[2:4])] + '-' + date_to[4:8]
 
110
      except:
 
111
        raise Exception(_('Date to error'))
 
112
 
 
113
  # Load IDs if file exists
 
114
  if (os.path.isfile(IDS_PATH)):
 
115
    try:
 
116
      fd = open(IDS_PATH, 'rb')
 
117
      IDS = cPickle.load(fd)
 
118
      fd.close()
 
119
    except:
 
120
      raise Exception(_('Error loading file: '), IDS_PATH)
 
121
 
 
122
  # Create the mail server connection and login into the defined account
 
123
  ms = gb_imap.MailServer(user_data['mail_host'], user_data['mail_host_port'], user_data['user_name'], user_data['password'])
 
124
  ms.login()
 
125
  # Get the mailboxes
 
126
  ms.get_mailboxes()
 
127
  # Loop through the mailboxes
 
128
  mbk = ms.mailboxes.keys()
 
129
  mbk.sort()
 
130
  for k in mbk:
 
131
    mb = ms.mailboxes[k]
 
132
    label = mb.name
 
133
    msg_list = mb.get_message_list(start_date, end_date)
 
134
    print _("Mailbox: {0:25s} {1:>5d} messages.").format(label, len(msg_list))
 
135
    for msg in msg_list:
 
136
      id = mb.get_message_id(msg)
 
137
      if (id not in IDS):
 
138
        print "\t"+_("Message")+": {0:s}".format(id)
 
139
        e_mail = mb.get_message(msg, id)
 
140
        IDS[id] = [label]
 
141
        message_path = os.path.join(MAILBOX_PATH,mb.sub_name)
 
142
        # Check if message path exists and create it if not
 
143
        if (not os.path.isdir(message_path)):
 
144
          try:
 
145
            os.makedirs(message_path, 0700)
 
146
          except:
 
147
            raise Exception(_("Error: can't make directory: "),message_path)
 
148
        filename = os.path.join(message_path, id+'.eml')
 
149
        try:
 
150
          fd = open(filename, 'wb')
 
151
          fd.write(e_mail.e_mail.as_string(True))
 
152
          fd.close()
 
153
        except:
 
154
          raise Exception(_('Error writing file: '),filename)
 
155
      else:
 
156
        if (label not in IDS[id]):
 
157
          print "Updating label: {0:s}".format(label)
 
158
          IDS[id].append(label)
 
159
  try:
 
160
    fd = open(IDS_PATH, 'wb')
 
161
    cPickle.dump(IDS, fd, -1)
 
162
    fd.close()
 
163
  except:
 
164
    raise Exception(_('Error writing file: '), IDS_PATH)
 
165
 
 
166
  try:
 
167
    fd = open(LAST_RUN_DATE_PATH, 'wb')
 
168
    fd.write(NOW)
 
169
    fd.close()
 
170
  except:
 
171
    raise Exception(_('Error writing file: '), LAST_RUN_DATE_PATH)
 
172
 
 
173
  ms.logout()
 
174