Merge lp:~cfraire/backup-gmail/devel into lp:backup-gmail

Proposed by C Fraire
Status: Needs review
Proposed branch: lp:~cfraire/backup-gmail/devel
Merge into: lp:backup-gmail
Diff against target: 2569 lines (+1764/-369)
6 files modified
CHANGELOG (+91/-0)
LICENSE.txt (+674/-0)
README (+45/-2)
backup_gmail.py (+591/-282)
gui.py (+153/-85)
imapUTF7.py (+210/-0)
To merge this branch: bzr merge lp:~cfraire/backup-gmail/devel
Reviewer Review Type Date Requested Status
Joseph Wen Pending
Review via email: mp+66526@code.launchpad.net

Description of the change

  * Full and incremental backup are now the same operation, and re-running
 any backup will only write newly-detected messages ('label' is still
 always written fully after each backup). backup-gmail no longer deletes
 any data
  * add KeyringUtil to use keyring library (if available at runtime)
 for secure handling of saved passwords instead of writing plaintext
 to .cfg files. Existing password settings in .cfg files will be used
 but will not be automatically written anymore.
 (See http://pypi.python.org/pypi/keyring for installation help)
  * Use Gmail's XLIST command to map special internationalized folders
  * --mbox_export is now a separate, optional operation, which can be done
 on its own or after a backup
  * backup_gmail.Gmail objects support a graceful cancel() method intended
 to be called from a separate thread (as in gui.py). (Interrupting
 the command-line backup_gmail.py still terminates immediately).
  * gui.py operates directly on backup_gmail.Gmail objects instead of
 running the backup_gmail "do" methods, and it connects the
 QProgressDialog cancel to Gmail.cancel()
  * use explicit en_US date formatting in Gmail.searchByDate, to support
 users with other default locales
  * improved completion messages for restore or save to reflect the count
 of messages handled from the total set
  * progress can use a custom formatter for values, as with backup to
 format values as '%.2f MB'
  * Messages without MESSAGE-ID still get a <email address hidden> id in
 label, but the RFC content is no longer touched
  * Handle invalid dates in messages when filtering by date. Such messages
 will not be matched
  * --strict_exclude indicates that messages are to be skipped by
 MESSAGE-ID in addition to folder
  * add --prompt mode to pass credentials as STDIN instead of the command-line
  * fix: --end_date behavior is date exclusive, so update usage, and
 gui.py now passes date+1
  * fix gui.py bug where include_labels or exclude_labels were not properly
 unset between runs if the mode changed

To post a comment you must log in.
lp:~cfraire/backup-gmail/devel updated
16. By <email address hidden>

- warn to STDERR that keyring module is not active
- For 'fold', do not use strftime on email dates in case time part is
  invalid. Use date[0] and date[1] directly to effect '%Y-%m'
- relax 'AllMail' expectation, since it seems not to pass for
  international Gmail clients. Investigating further....

17. By <email address hidden>

- keep backslashes in "special" folder keys from XLIST
- RestoreGmail also uses XLIST "\Inbox" instead of literal 'INBOX' and
  treats \AllMail as optional (given user error report)
- remove now-unneeded getGmailPrefix method

18. By <email address hidden>

- Since users can hide special folders in IMAP, treat them as optional
  to avoid KeyError

19. By <email address hidden>

- slight fix to Progress objects to avoid outputting when initializing

20. By <email address hidden>

- fix localized date handling for gui.py and command-line arguments of
  backup_gmail.py
- fix to support Unicode in ConfigParser files by converting to and from
  Latin-1 encoding
- KNOWN PROBLEM: with filtering non-ASCII mailbox names because imaplib does
  not currently support the IMAP-modified UTF-7 encoded needed for general
  Unicode support.

21. By <email address hidden>

- backup_gmail uses imapUTF7 for handling special characters in mailbox
- use utf-8 for .cfg files
- for interacting with backup_gmail lib, convert from PySide unicode to
  utf-8 and back

22. By <email address hidden>

- fix: also convert QDateEdit from unicode to and from utf-8 when interacting
  with backup_gmail

23. By <email address hidden>

- fix: restore can assign non-ASCII labels via UTF-7
- restore by default restores to \AllMail; can restore to specified --label
- restore no longer puts anything into \Inbox (unless explicit with --label)
- remove redundant clearing of \Seen
- update README with some info on library dependencies

24. By <email address hidden>

- improve help strings
- fix scope for raising ApplicationError

25. By <email address hidden>

- restore treats 'INBOX' as a special name even for non-English accounts
- improve usage string

26. By <email address hidden>

- fix: also UTF-7 decode special folders

27. By <email address hidden>

- fix: use BODY.PEEK to effect --keep_status instead of manually unsetting
  \Seen. This fixes the behavior and is no longer a slow operation
- method fetchRFC822Info(...) fetches MESSAGE-ID also, so a separate call
  to fetchMessageId(...) is not required

28. By <email address hidden>

- fix: RestoreGmail works around imaplib's Time2InternalDate function to
  avoid sending non-RFC2822 dates to IMAP

29. By <email address hidden>

Adding regex handling

- add --match_regex for label filtering
- add FilterLabels class to handle work of filtering
- SaveMbox and RestoreGmail now use non-strict label exclusion by
  default and will recognize --strict_exclude
- improve help strings
- add time zone caveats to README

30. By <email address hidden>

--include is now case-insensitive

- also improve FilterLabels and re-use code among BackupGmail,
  SaveMbox, and RestoreGmail

31. By <email address hidden>

Update progress only when fetch batches complete

...not after every message is queued or skipped

32. By <email address hidden>

Fix to avoid IndexError during restore operations

Also:
- include Joseph Wen's chosen license, GPLv3
- update README

Unmerged revisions

32. By <email address hidden>

Fix to avoid IndexError during restore operations

Also:
- include Joseph Wen's chosen license, GPLv3
- update README

31. By <email address hidden>

Update progress only when fetch batches complete

...not after every message is queued or skipped

30. By <email address hidden>

--include is now case-insensitive

- also improve FilterLabels and re-use code among BackupGmail,
  SaveMbox, and RestoreGmail

29. By <email address hidden>

Adding regex handling

- add --match_regex for label filtering
- add FilterLabels class to handle work of filtering
- SaveMbox and RestoreGmail now use non-strict label exclusion by
  default and will recognize --strict_exclude
- improve help strings
- add time zone caveats to README

28. By <email address hidden>

- fix: RestoreGmail works around imaplib's Time2InternalDate function to
  avoid sending non-RFC2822 dates to IMAP

27. By <email address hidden>

- fix: use BODY.PEEK to effect --keep_status instead of manually unsetting
  \Seen. This fixes the behavior and is no longer a slow operation
- method fetchRFC822Info(...) fetches MESSAGE-ID also, so a separate call
  to fetchMessageId(...) is not required

26. By <email address hidden>

- fix: also UTF-7 decode special folders

25. By <email address hidden>

- restore treats 'INBOX' as a special name even for non-English accounts
- improve usage string

24. By <email address hidden>

- improve help strings
- fix scope for raising ApplicationError

23. By <email address hidden>

- fix: restore can assign non-ASCII labels via UTF-7
- restore by default restores to \AllMail; can restore to specified --label
- restore no longer puts anything into \Inbox (unless explicit with --label)
- remove redundant clearing of \Seen
- update README with some info on library dependencies

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'CHANGELOG'
2--- CHANGELOG 2011-03-12 05:07:18 +0000
3+++ CHANGELOG 2016-09-30 23:55:37 +0000
4@@ -1,3 +1,94 @@
5+backup-gmail 2016-9-30
6+ * restore fixes: log error and continue if IMAP append does not succeed
7+ with OK. Avoid string index out of range on empty dates.
8+
9+backup-gmail 2012-2-28
10+ * Update progress only when fetch batches complete, not after every
11+ message is queued or skipped
12+
13+backup-gmail 2012-1-22
14+ * backup is now case-insensitive for --include
15+
16+backup-gmail 2012-1-18
17+ * add --match_regex for label filtering
18+ * add FilterLabels class to handle work of filtering
19+ * SaveMbox and RestoreGmail now use non-strict label exclusion by default
20+ and will recognize --strict_exclude
21+ * improve help strings
22+
23+backup-gmail 2012-1-17
24+ * fix: RestoreGmail works around imaplib's Time2InternalDate function to
25+ avoid sending non-RFC2822 dates to IMAP
26+
27+backup-gmail 2012-1-14
28+ * fix: use BODY.PEEK to effect --keep_status instead of manually unsetting
29+ \Seen. This fixes the behavior and is no longer a slow operation
30+ * method fetchRFC822Info(...) fetches MESSAGE-ID also, so a separate call
31+ to fetchMessageId(...) is not required
32+
33+backup-gmail 2012-1-11.1
34+ * fix: also UTF-7 decode special folders
35+
36+backup-gmail 2012-1-11
37+ * restore treats 'INBOX' as a special name even for non-English accounts
38+ * improve help string
39+
40+backup-gmail 2012-1-10.1
41+ * improve help strings and gui labels
42+
43+backup-gmail 2012-1-10
44+ * fix: restore can assign non-ASCII labels via UTF-7
45+ * restore by default restores to \AllMail; can restore to specified --label
46+ * restore no longer puts anything into \Inbox (unless explicit with --label)
47+ * remove redundant clearing of \Seen in backup if --keep_read_status
48+
49+backup-gmail 2011-11-2
50+ * fix localized date handling for gui.py and command-line arguments of
51+ backup_gmail.py
52+ * fix gui.py to interact with backup_gmail strictly in utf-8
53+ * use imapUTF7 package to handle mailbox names with non-ASCII characters;
54+ (thanks to MXM at http://mxm-mad-science.blogspot.com/)
55+
56+backup-gmail 2011-10-16-1
57+ * Since users can hide special folders in IMAP, treat them as
58+ optional to avoid KeyError
59+
60+backup-gmail 0.2
61+ * Full and incremental backup are now the same operation, and re-running
62+ any backup will only write newly-detected messages ('label' is still
63+ always written fully after each backup). backup-gmail no longer deletes
64+ any data
65+ * add KeyringUtil to use keyring library (if available at runtime)
66+ for secure handling of saved passwords instead of writing plaintext
67+ to .cfg files. Existing password settings in .cfg files will be used
68+ but will not be automatically written anymore.
69+ (See http://pypi.python.org/pypi/keyring for installation help)
70+ * Use Gmail's XLIST command to map special internationalized folders
71+ * --mbox_export is now a separate, optional operation, which can be done
72+ on its own or after a backup
73+ * backup_gmail.Gmail objects support a graceful cancel() method intended
74+ to be called from a separate thread (as in gui.py). (Interrupting
75+ the command-line backup_gmail.py still terminates immediately).
76+ * gui.py operates directly on backup_gmail.Gmail objects instead of
77+ running the backup_gmail "do" methods, and it connects the
78+ QProgressDialog cancel to Gmail.cancel()
79+ * use en_US date formatting in Gmail.searchByDate
80+ * improved completion messages for restore or save to reflect the count
81+ of messages handled from the total set
82+ * progress can use a custom formatter for values, as with backup to
83+ format values as '%.2f MB'
84+ * Messages without MESSAGE-ID still get a hash@backup-gmail.com id in
85+ label, but the RFC content is no longer touched
86+ * Handle invalid dates in messages when filtering by date. Such messages
87+ will not be matched
88+ * --strict_exclude indicates that messages are to be skipped by
89+ MESSAGE-ID in addition to folder
90+ * add --prompt mode to pass credentials as STDIN instead of the command-line
91+ * fix: --end_date behavior is date exclusive, so update usage, and
92+ gui.py now passes date+1
93+ * fix gui.py bug where include_labels or exclude_labels were not properly
94+ unset between runs if the mode changed
95+
96 backup-gmail 0.1.1
97 * Implemented restore function
98 * Implemented configure file
99
100=== added file 'LICENSE.txt'
101--- LICENSE.txt 1970-01-01 00:00:00 +0000
102+++ LICENSE.txt 2016-09-30 23:55:37 +0000
103@@ -0,0 +1,674 @@
104+ GNU GENERAL PUBLIC LICENSE
105+ Version 3, 29 June 2007
106+
107+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
108+ Everyone is permitted to copy and distribute verbatim copies
109+ of this license document, but changing it is not allowed.
110+
111+ Preamble
112+
113+ The GNU General Public License is a free, copyleft license for
114+software and other kinds of works.
115+
116+ The licenses for most software and other practical works are designed
117+to take away your freedom to share and change the works. By contrast,
118+the GNU General Public License is intended to guarantee your freedom to
119+share and change all versions of a program--to make sure it remains free
120+software for all its users. We, the Free Software Foundation, use the
121+GNU General Public License for most of our software; it applies also to
122+any other work released this way by its authors. You can apply it to
123+your programs, too.
124+
125+ When we speak of free software, we are referring to freedom, not
126+price. Our General Public Licenses are designed to make sure that you
127+have the freedom to distribute copies of free software (and charge for
128+them if you wish), that you receive source code or can get it if you
129+want it, that you can change the software or use pieces of it in new
130+free programs, and that you know you can do these things.
131+
132+ To protect your rights, we need to prevent others from denying you
133+these rights or asking you to surrender the rights. Therefore, you have
134+certain responsibilities if you distribute copies of the software, or if
135+you modify it: responsibilities to respect the freedom of others.
136+
137+ For example, if you distribute copies of such a program, whether
138+gratis or for a fee, you must pass on to the recipients the same
139+freedoms that you received. You must make sure that they, too, receive
140+or can get the source code. And you must show them these terms so they
141+know their rights.
142+
143+ Developers that use the GNU GPL protect your rights with two steps:
144+(1) assert copyright on the software, and (2) offer you this License
145+giving you legal permission to copy, distribute and/or modify it.
146+
147+ For the developers' and authors' protection, the GPL clearly explains
148+that there is no warranty for this free software. For both users' and
149+authors' sake, the GPL requires that modified versions be marked as
150+changed, so that their problems will not be attributed erroneously to
151+authors of previous versions.
152+
153+ Some devices are designed to deny users access to install or run
154+modified versions of the software inside them, although the manufacturer
155+can do so. This is fundamentally incompatible with the aim of
156+protecting users' freedom to change the software. The systematic
157+pattern of such abuse occurs in the area of products for individuals to
158+use, which is precisely where it is most unacceptable. Therefore, we
159+have designed this version of the GPL to prohibit the practice for those
160+products. If such problems arise substantially in other domains, we
161+stand ready to extend this provision to those domains in future versions
162+of the GPL, as needed to protect the freedom of users.
163+
164+ Finally, every program is threatened constantly by software patents.
165+States should not allow patents to restrict development and use of
166+software on general-purpose computers, but in those that do, we wish to
167+avoid the special danger that patents applied to a free program could
168+make it effectively proprietary. To prevent this, the GPL assures that
169+patents cannot be used to render the program non-free.
170+
171+ The precise terms and conditions for copying, distribution and
172+modification follow.
173+
174+ TERMS AND CONDITIONS
175+
176+ 0. Definitions.
177+
178+ "This License" refers to version 3 of the GNU General Public License.
179+
180+ "Copyright" also means copyright-like laws that apply to other kinds of
181+works, such as semiconductor masks.
182+
183+ "The Program" refers to any copyrightable work licensed under this
184+License. Each licensee is addressed as "you". "Licensees" and
185+"recipients" may be individuals or organizations.
186+
187+ To "modify" a work means to copy from or adapt all or part of the work
188+in a fashion requiring copyright permission, other than the making of an
189+exact copy. The resulting work is called a "modified version" of the
190+earlier work or a work "based on" the earlier work.
191+
192+ A "covered work" means either the unmodified Program or a work based
193+on the Program.
194+
195+ To "propagate" a work means to do anything with it that, without
196+permission, would make you directly or secondarily liable for
197+infringement under applicable copyright law, except executing it on a
198+computer or modifying a private copy. Propagation includes copying,
199+distribution (with or without modification), making available to the
200+public, and in some countries other activities as well.
201+
202+ To "convey" a work means any kind of propagation that enables other
203+parties to make or receive copies. Mere interaction with a user through
204+a computer network, with no transfer of a copy, is not conveying.
205+
206+ An interactive user interface displays "Appropriate Legal Notices"
207+to the extent that it includes a convenient and prominently visible
208+feature that (1) displays an appropriate copyright notice, and (2)
209+tells the user that there is no warranty for the work (except to the
210+extent that warranties are provided), that licensees may convey the
211+work under this License, and how to view a copy of this License. If
212+the interface presents a list of user commands or options, such as a
213+menu, a prominent item in the list meets this criterion.
214+
215+ 1. Source Code.
216+
217+ The "source code" for a work means the preferred form of the work
218+for making modifications to it. "Object code" means any non-source
219+form of a work.
220+
221+ A "Standard Interface" means an interface that either is an official
222+standard defined by a recognized standards body, or, in the case of
223+interfaces specified for a particular programming language, one that
224+is widely used among developers working in that language.
225+
226+ The "System Libraries" of an executable work include anything, other
227+than the work as a whole, that (a) is included in the normal form of
228+packaging a Major Component, but which is not part of that Major
229+Component, and (b) serves only to enable use of the work with that
230+Major Component, or to implement a Standard Interface for which an
231+implementation is available to the public in source code form. A
232+"Major Component", in this context, means a major essential component
233+(kernel, window system, and so on) of the specific operating system
234+(if any) on which the executable work runs, or a compiler used to
235+produce the work, or an object code interpreter used to run it.
236+
237+ The "Corresponding Source" for a work in object code form means all
238+the source code needed to generate, install, and (for an executable
239+work) run the object code and to modify the work, including scripts to
240+control those activities. However, it does not include the work's
241+System Libraries, or general-purpose tools or generally available free
242+programs which are used unmodified in performing those activities but
243+which are not part of the work. For example, Corresponding Source
244+includes interface definition files associated with source files for
245+the work, and the source code for shared libraries and dynamically
246+linked subprograms that the work is specifically designed to require,
247+such as by intimate data communication or control flow between those
248+subprograms and other parts of the work.
249+
250+ The Corresponding Source need not include anything that users
251+can regenerate automatically from other parts of the Corresponding
252+Source.
253+
254+ The Corresponding Source for a work in source code form is that
255+same work.
256+
257+ 2. Basic Permissions.
258+
259+ All rights granted under this License are granted for the term of
260+copyright on the Program, and are irrevocable provided the stated
261+conditions are met. This License explicitly affirms your unlimited
262+permission to run the unmodified Program. The output from running a
263+covered work is covered by this License only if the output, given its
264+content, constitutes a covered work. This License acknowledges your
265+rights of fair use or other equivalent, as provided by copyright law.
266+
267+ You may make, run and propagate covered works that you do not
268+convey, without conditions so long as your license otherwise remains
269+in force. You may convey covered works to others for the sole purpose
270+of having them make modifications exclusively for you, or provide you
271+with facilities for running those works, provided that you comply with
272+the terms of this License in conveying all material for which you do
273+not control copyright. Those thus making or running the covered works
274+for you must do so exclusively on your behalf, under your direction
275+and control, on terms that prohibit them from making any copies of
276+your copyrighted material outside their relationship with you.
277+
278+ Conveying under any other circumstances is permitted solely under
279+the conditions stated below. Sublicensing is not allowed; section 10
280+makes it unnecessary.
281+
282+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
283+
284+ No covered work shall be deemed part of an effective technological
285+measure under any applicable law fulfilling obligations under article
286+11 of the WIPO copyright treaty adopted on 20 December 1996, or
287+similar laws prohibiting or restricting circumvention of such
288+measures.
289+
290+ When you convey a covered work, you waive any legal power to forbid
291+circumvention of technological measures to the extent such circumvention
292+is effected by exercising rights under this License with respect to
293+the covered work, and you disclaim any intention to limit operation or
294+modification of the work as a means of enforcing, against the work's
295+users, your or third parties' legal rights to forbid circumvention of
296+technological measures.
297+
298+ 4. Conveying Verbatim Copies.
299+
300+ You may convey verbatim copies of the Program's source code as you
301+receive it, in any medium, provided that you conspicuously and
302+appropriately publish on each copy an appropriate copyright notice;
303+keep intact all notices stating that this License and any
304+non-permissive terms added in accord with section 7 apply to the code;
305+keep intact all notices of the absence of any warranty; and give all
306+recipients a copy of this License along with the Program.
307+
308+ You may charge any price or no price for each copy that you convey,
309+and you may offer support or warranty protection for a fee.
310+
311+ 5. Conveying Modified Source Versions.
312+
313+ You may convey a work based on the Program, or the modifications to
314+produce it from the Program, in the form of source code under the
315+terms of section 4, provided that you also meet all of these conditions:
316+
317+ a) The work must carry prominent notices stating that you modified
318+ it, and giving a relevant date.
319+
320+ b) The work must carry prominent notices stating that it is
321+ released under this License and any conditions added under section
322+ 7. This requirement modifies the requirement in section 4 to
323+ "keep intact all notices".
324+
325+ c) You must license the entire work, as a whole, under this
326+ License to anyone who comes into possession of a copy. This
327+ License will therefore apply, along with any applicable section 7
328+ additional terms, to the whole of the work, and all its parts,
329+ regardless of how they are packaged. This License gives no
330+ permission to license the work in any other way, but it does not
331+ invalidate such permission if you have separately received it.
332+
333+ d) If the work has interactive user interfaces, each must display
334+ Appropriate Legal Notices; however, if the Program has interactive
335+ interfaces that do not display Appropriate Legal Notices, your
336+ work need not make them do so.
337+
338+ A compilation of a covered work with other separate and independent
339+works, which are not by their nature extensions of the covered work,
340+and which are not combined with it such as to form a larger program,
341+in or on a volume of a storage or distribution medium, is called an
342+"aggregate" if the compilation and its resulting copyright are not
343+used to limit the access or legal rights of the compilation's users
344+beyond what the individual works permit. Inclusion of a covered work
345+in an aggregate does not cause this License to apply to the other
346+parts of the aggregate.
347+
348+ 6. Conveying Non-Source Forms.
349+
350+ You may convey a covered work in object code form under the terms
351+of sections 4 and 5, provided that you also convey the
352+machine-readable Corresponding Source under the terms of this License,
353+in one of these ways:
354+
355+ a) Convey the object code in, or embodied in, a physical product
356+ (including a physical distribution medium), accompanied by the
357+ Corresponding Source fixed on a durable physical medium
358+ customarily used for software interchange.
359+
360+ b) Convey the object code in, or embodied in, a physical product
361+ (including a physical distribution medium), accompanied by a
362+ written offer, valid for at least three years and valid for as
363+ long as you offer spare parts or customer support for that product
364+ model, to give anyone who possesses the object code either (1) a
365+ copy of the Corresponding Source for all the software in the
366+ product that is covered by this License, on a durable physical
367+ medium customarily used for software interchange, for a price no
368+ more than your reasonable cost of physically performing this
369+ conveying of source, or (2) access to copy the
370+ Corresponding Source from a network server at no charge.
371+
372+ c) Convey individual copies of the object code with a copy of the
373+ written offer to provide the Corresponding Source. This
374+ alternative is allowed only occasionally and noncommercially, and
375+ only if you received the object code with such an offer, in accord
376+ with subsection 6b.
377+
378+ d) Convey the object code by offering access from a designated
379+ place (gratis or for a charge), and offer equivalent access to the
380+ Corresponding Source in the same way through the same place at no
381+ further charge. You need not require recipients to copy the
382+ Corresponding Source along with the object code. If the place to
383+ copy the object code is a network server, the Corresponding Source
384+ may be on a different server (operated by you or a third party)
385+ that supports equivalent copying facilities, provided you maintain
386+ clear directions next to the object code saying where to find the
387+ Corresponding Source. Regardless of what server hosts the
388+ Corresponding Source, you remain obligated to ensure that it is
389+ available for as long as needed to satisfy these requirements.
390+
391+ e) Convey the object code using peer-to-peer transmission, provided
392+ you inform other peers where the object code and Corresponding
393+ Source of the work are being offered to the general public at no
394+ charge under subsection 6d.
395+
396+ A separable portion of the object code, whose source code is excluded
397+from the Corresponding Source as a System Library, need not be
398+included in conveying the object code work.
399+
400+ A "User Product" is either (1) a "consumer product", which means any
401+tangible personal property which is normally used for personal, family,
402+or household purposes, or (2) anything designed or sold for incorporation
403+into a dwelling. In determining whether a product is a consumer product,
404+doubtful cases shall be resolved in favor of coverage. For a particular
405+product received by a particular user, "normally used" refers to a
406+typical or common use of that class of product, regardless of the status
407+of the particular user or of the way in which the particular user
408+actually uses, or expects or is expected to use, the product. A product
409+is a consumer product regardless of whether the product has substantial
410+commercial, industrial or non-consumer uses, unless such uses represent
411+the only significant mode of use of the product.
412+
413+ "Installation Information" for a User Product means any methods,
414+procedures, authorization keys, or other information required to install
415+and execute modified versions of a covered work in that User Product from
416+a modified version of its Corresponding Source. The information must
417+suffice to ensure that the continued functioning of the modified object
418+code is in no case prevented or interfered with solely because
419+modification has been made.
420+
421+ If you convey an object code work under this section in, or with, or
422+specifically for use in, a User Product, and the conveying occurs as
423+part of a transaction in which the right of possession and use of the
424+User Product is transferred to the recipient in perpetuity or for a
425+fixed term (regardless of how the transaction is characterized), the
426+Corresponding Source conveyed under this section must be accompanied
427+by the Installation Information. But this requirement does not apply
428+if neither you nor any third party retains the ability to install
429+modified object code on the User Product (for example, the work has
430+been installed in ROM).
431+
432+ The requirement to provide Installation Information does not include a
433+requirement to continue to provide support service, warranty, or updates
434+for a work that has been modified or installed by the recipient, or for
435+the User Product in which it has been modified or installed. Access to a
436+network may be denied when the modification itself materially and
437+adversely affects the operation of the network or violates the rules and
438+protocols for communication across the network.
439+
440+ Corresponding Source conveyed, and Installation Information provided,
441+in accord with this section must be in a format that is publicly
442+documented (and with an implementation available to the public in
443+source code form), and must require no special password or key for
444+unpacking, reading or copying.
445+
446+ 7. Additional Terms.
447+
448+ "Additional permissions" are terms that supplement the terms of this
449+License by making exceptions from one or more of its conditions.
450+Additional permissions that are applicable to the entire Program shall
451+be treated as though they were included in this License, to the extent
452+that they are valid under applicable law. If additional permissions
453+apply only to part of the Program, that part may be used separately
454+under those permissions, but the entire Program remains governed by
455+this License without regard to the additional permissions.
456+
457+ When you convey a copy of a covered work, you may at your option
458+remove any additional permissions from that copy, or from any part of
459+it. (Additional permissions may be written to require their own
460+removal in certain cases when you modify the work.) You may place
461+additional permissions on material, added by you to a covered work,
462+for which you have or can give appropriate copyright permission.
463+
464+ Notwithstanding any other provision of this License, for material you
465+add to a covered work, you may (if authorized by the copyright holders of
466+that material) supplement the terms of this License with terms:
467+
468+ a) Disclaiming warranty or limiting liability differently from the
469+ terms of sections 15 and 16 of this License; or
470+
471+ b) Requiring preservation of specified reasonable legal notices or
472+ author attributions in that material or in the Appropriate Legal
473+ Notices displayed by works containing it; or
474+
475+ c) Prohibiting misrepresentation of the origin of that material, or
476+ requiring that modified versions of such material be marked in
477+ reasonable ways as different from the original version; or
478+
479+ d) Limiting the use for publicity purposes of names of licensors or
480+ authors of the material; or
481+
482+ e) Declining to grant rights under trademark law for use of some
483+ trade names, trademarks, or service marks; or
484+
485+ f) Requiring indemnification of licensors and authors of that
486+ material by anyone who conveys the material (or modified versions of
487+ it) with contractual assumptions of liability to the recipient, for
488+ any liability that these contractual assumptions directly impose on
489+ those licensors and authors.
490+
491+ All other non-permissive additional terms are considered "further
492+restrictions" within the meaning of section 10. If the Program as you
493+received it, or any part of it, contains a notice stating that it is
494+governed by this License along with a term that is a further
495+restriction, you may remove that term. If a license document contains
496+a further restriction but permits relicensing or conveying under this
497+License, you may add to a covered work material governed by the terms
498+of that license document, provided that the further restriction does
499+not survive such relicensing or conveying.
500+
501+ If you add terms to a covered work in accord with this section, you
502+must place, in the relevant source files, a statement of the
503+additional terms that apply to those files, or a notice indicating
504+where to find the applicable terms.
505+
506+ Additional terms, permissive or non-permissive, may be stated in the
507+form of a separately written license, or stated as exceptions;
508+the above requirements apply either way.
509+
510+ 8. Termination.
511+
512+ You may not propagate or modify a covered work except as expressly
513+provided under this License. Any attempt otherwise to propagate or
514+modify it is void, and will automatically terminate your rights under
515+this License (including any patent licenses granted under the third
516+paragraph of section 11).
517+
518+ However, if you cease all violation of this License, then your
519+license from a particular copyright holder is reinstated (a)
520+provisionally, unless and until the copyright holder explicitly and
521+finally terminates your license, and (b) permanently, if the copyright
522+holder fails to notify you of the violation by some reasonable means
523+prior to 60 days after the cessation.
524+
525+ Moreover, your license from a particular copyright holder is
526+reinstated permanently if the copyright holder notifies you of the
527+violation by some reasonable means, this is the first time you have
528+received notice of violation of this License (for any work) from that
529+copyright holder, and you cure the violation prior to 30 days after
530+your receipt of the notice.
531+
532+ Termination of your rights under this section does not terminate the
533+licenses of parties who have received copies or rights from you under
534+this License. If your rights have been terminated and not permanently
535+reinstated, you do not qualify to receive new licenses for the same
536+material under section 10.
537+
538+ 9. Acceptance Not Required for Having Copies.
539+
540+ You are not required to accept this License in order to receive or
541+run a copy of the Program. Ancillary propagation of a covered work
542+occurring solely as a consequence of using peer-to-peer transmission
543+to receive a copy likewise does not require acceptance. However,
544+nothing other than this License grants you permission to propagate or
545+modify any covered work. These actions infringe copyright if you do
546+not accept this License. Therefore, by modifying or propagating a
547+covered work, you indicate your acceptance of this License to do so.
548+
549+ 10. Automatic Licensing of Downstream Recipients.
550+
551+ Each time you convey a covered work, the recipient automatically
552+receives a license from the original licensors, to run, modify and
553+propagate that work, subject to this License. You are not responsible
554+for enforcing compliance by third parties with this License.
555+
556+ An "entity transaction" is a transaction transferring control of an
557+organization, or substantially all assets of one, or subdividing an
558+organization, or merging organizations. If propagation of a covered
559+work results from an entity transaction, each party to that
560+transaction who receives a copy of the work also receives whatever
561+licenses to the work the party's predecessor in interest had or could
562+give under the previous paragraph, plus a right to possession of the
563+Corresponding Source of the work from the predecessor in interest, if
564+the predecessor has it or can get it with reasonable efforts.
565+
566+ You may not impose any further restrictions on the exercise of the
567+rights granted or affirmed under this License. For example, you may
568+not impose a license fee, royalty, or other charge for exercise of
569+rights granted under this License, and you may not initiate litigation
570+(including a cross-claim or counterclaim in a lawsuit) alleging that
571+any patent claim is infringed by making, using, selling, offering for
572+sale, or importing the Program or any portion of it.
573+
574+ 11. Patents.
575+
576+ A "contributor" is a copyright holder who authorizes use under this
577+License of the Program or a work on which the Program is based. The
578+work thus licensed is called the contributor's "contributor version".
579+
580+ A contributor's "essential patent claims" are all patent claims
581+owned or controlled by the contributor, whether already acquired or
582+hereafter acquired, that would be infringed by some manner, permitted
583+by this License, of making, using, or selling its contributor version,
584+but do not include claims that would be infringed only as a
585+consequence of further modification of the contributor version. For
586+purposes of this definition, "control" includes the right to grant
587+patent sublicenses in a manner consistent with the requirements of
588+this License.
589+
590+ Each contributor grants you a non-exclusive, worldwide, royalty-free
591+patent license under the contributor's essential patent claims, to
592+make, use, sell, offer for sale, import and otherwise run, modify and
593+propagate the contents of its contributor version.
594+
595+ In the following three paragraphs, a "patent license" is any express
596+agreement or commitment, however denominated, not to enforce a patent
597+(such as an express permission to practice a patent or covenant not to
598+sue for patent infringement). To "grant" such a patent license to a
599+party means to make such an agreement or commitment not to enforce a
600+patent against the party.
601+
602+ If you convey a covered work, knowingly relying on a patent license,
603+and the Corresponding Source of the work is not available for anyone
604+to copy, free of charge and under the terms of this License, through a
605+publicly available network server or other readily accessible means,
606+then you must either (1) cause the Corresponding Source to be so
607+available, or (2) arrange to deprive yourself of the benefit of the
608+patent license for this particular work, or (3) arrange, in a manner
609+consistent with the requirements of this License, to extend the patent
610+license to downstream recipients. "Knowingly relying" means you have
611+actual knowledge that, but for the patent license, your conveying the
612+covered work in a country, or your recipient's use of the covered work
613+in a country, would infringe one or more identifiable patents in that
614+country that you have reason to believe are valid.
615+
616+ If, pursuant to or in connection with a single transaction or
617+arrangement, you convey, or propagate by procuring conveyance of, a
618+covered work, and grant a patent license to some of the parties
619+receiving the covered work authorizing them to use, propagate, modify
620+or convey a specific copy of the covered work, then the patent license
621+you grant is automatically extended to all recipients of the covered
622+work and works based on it.
623+
624+ A patent license is "discriminatory" if it does not include within
625+the scope of its coverage, prohibits the exercise of, or is
626+conditioned on the non-exercise of one or more of the rights that are
627+specifically granted under this License. You may not convey a covered
628+work if you are a party to an arrangement with a third party that is
629+in the business of distributing software, under which you make payment
630+to the third party based on the extent of your activity of conveying
631+the work, and under which the third party grants, to any of the
632+parties who would receive the covered work from you, a discriminatory
633+patent license (a) in connection with copies of the covered work
634+conveyed by you (or copies made from those copies), or (b) primarily
635+for and in connection with specific products or compilations that
636+contain the covered work, unless you entered into that arrangement,
637+or that patent license was granted, prior to 28 March 2007.
638+
639+ Nothing in this License shall be construed as excluding or limiting
640+any implied license or other defenses to infringement that may
641+otherwise be available to you under applicable patent law.
642+
643+ 12. No Surrender of Others' Freedom.
644+
645+ If conditions are imposed on you (whether by court order, agreement or
646+otherwise) that contradict the conditions of this License, they do not
647+excuse you from the conditions of this License. If you cannot convey a
648+covered work so as to satisfy simultaneously your obligations under this
649+License and any other pertinent obligations, then as a consequence you may
650+not convey it at all. For example, if you agree to terms that obligate you
651+to collect a royalty for further conveying from those to whom you convey
652+the Program, the only way you could satisfy both those terms and this
653+License would be to refrain entirely from conveying the Program.
654+
655+ 13. Use with the GNU Affero General Public License.
656+
657+ Notwithstanding any other provision of this License, you have
658+permission to link or combine any covered work with a work licensed
659+under version 3 of the GNU Affero General Public License into a single
660+combined work, and to convey the resulting work. The terms of this
661+License will continue to apply to the part which is the covered work,
662+but the special requirements of the GNU Affero General Public License,
663+section 13, concerning interaction through a network will apply to the
664+combination as such.
665+
666+ 14. Revised Versions of this License.
667+
668+ The Free Software Foundation may publish revised and/or new versions of
669+the GNU General Public License from time to time. Such new versions will
670+be similar in spirit to the present version, but may differ in detail to
671+address new problems or concerns.
672+
673+ Each version is given a distinguishing version number. If the
674+Program specifies that a certain numbered version of the GNU General
675+Public License "or any later version" applies to it, you have the
676+option of following the terms and conditions either of that numbered
677+version or of any later version published by the Free Software
678+Foundation. If the Program does not specify a version number of the
679+GNU General Public License, you may choose any version ever published
680+by the Free Software Foundation.
681+
682+ If the Program specifies that a proxy can decide which future
683+versions of the GNU General Public License can be used, that proxy's
684+public statement of acceptance of a version permanently authorizes you
685+to choose that version for the Program.
686+
687+ Later license versions may give you additional or different
688+permissions. However, no additional obligations are imposed on any
689+author or copyright holder as a result of your choosing to follow a
690+later version.
691+
692+ 15. Disclaimer of Warranty.
693+
694+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
695+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
696+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
697+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
698+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
699+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
700+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
701+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
702+
703+ 16. Limitation of Liability.
704+
705+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
706+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
707+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
708+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
709+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
710+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
711+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
712+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
713+SUCH DAMAGES.
714+
715+ 17. Interpretation of Sections 15 and 16.
716+
717+ If the disclaimer of warranty and limitation of liability provided
718+above cannot be given local legal effect according to their terms,
719+reviewing courts shall apply local law that most closely approximates
720+an absolute waiver of all civil liability in connection with the
721+Program, unless a warranty or assumption of liability accompanies a
722+copy of the Program in return for a fee.
723+
724+ END OF TERMS AND CONDITIONS
725+
726+ How to Apply These Terms to Your New Programs
727+
728+ If you develop a new program, and you want it to be of the greatest
729+possible use to the public, the best way to achieve this is to make it
730+free software which everyone can redistribute and change under these terms.
731+
732+ To do so, attach the following notices to the program. It is safest
733+to attach them to the start of each source file to most effectively
734+state the exclusion of warranty; and each file should have at least
735+the "copyright" line and a pointer to where the full notice is found.
736+
737+ {one line to give the program's name and a brief idea of what it does.}
738+ Copyright (C) {year} {name of author}
739+
740+ This program is free software: you can redistribute it and/or modify
741+ it under the terms of the GNU General Public License as published by
742+ the Free Software Foundation, either version 3 of the License, or
743+ (at your option) any later version.
744+
745+ This program is distributed in the hope that it will be useful,
746+ but WITHOUT ANY WARRANTY; without even the implied warranty of
747+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
748+ GNU General Public License for more details.
749+
750+ You should have received a copy of the GNU General Public License
751+ along with this program. If not, see <http://www.gnu.org/licenses/>.
752+
753+Also add information on how to contact you by electronic and paper mail.
754+
755+ If the program does terminal interaction, make it output a short
756+notice like this when it starts in an interactive mode:
757+
758+ {project} Copyright (C) {year} {fullname}
759+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
760+ This is free software, and you are welcome to redistribute it
761+ under certain conditions; type `show c' for details.
762+
763+The hypothetical commands `show w' and `show c' should show the appropriate
764+parts of the General Public License. Of course, your program's commands
765+might be different; for a GUI interface, you would use an "about box".
766+
767+ You should also get your employer (if you work as a programmer) or school,
768+if any, to sign a "copyright disclaimer" for the program, if necessary.
769+For more information on this, and how to apply and follow the GNU GPL, see
770+<http://www.gnu.org/licenses/>.
771+
772+ The GNU General Public License does not permit incorporating your program
773+into proprietary programs. If your program is a subroutine library, you
774+may consider it more useful to permit linking proprietary applications with
775+the library. If this is what you want to do, use the GNU Lesser General
776+Public License instead of this License. But first, please read
777+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
778
779=== modified file 'README'
780--- README 2011-03-10 04:27:09 +0000
781+++ README 2016-09-30 23:55:37 +0000
782@@ -1,9 +1,52 @@
783+backup_gmail
784+============
785+
786 Copyright 2011, Joseph Wen
787
788+Copyright 2015, Chris Fraire
789+
790+This application provides both a command line interface and graphical user
791+interface to backup and restore Gmail data via IMAP. It support incremental
792+backup based on message-id and sha1. It also preserves the read/unread state
793+on the Gmail server.
794+
795 For more information visit:
796-https://launchpad.net/backup-gmail
797+https://github.com/idodeclare/backup-gmail
798
799-== Usage ==
800+Usage
801+=====
802 ./backup_gmail.py
803+
804 or
805+
806 ./gui.py
807+
808+Caveats
809+=======
810+
811+Time Zones
812+----------
813+ A backup operation processes --start and --end using Gmail's servers,
814+and time zones are respected; dates will be qualified using the user's
815+configured Gmail time zone.
816+
817+ --mbox_export and --restore, however, do not currently respect time
818+zones for --start and --end, so results can be slightly incorrect near
819+the date range boundaries.
820+
821+
822+Additional Libraries
823+====================
824+
825+The Qt library, used by gui.py, may need to be installed for platforms
826+where it is not available by default (e.g., Mac OS X, Windows, etc.):
827+
828+ http://www.qt.io/download-open-source/
829+
830+PySide for Qt, used by gui.py, is available for various platforms at:
831+
832+ https://wiki.qt.io/Category:LanguageBindings::PySide::Downloads
833+
834+keyring for Python, used for secure storage of passwords, is available at:
835+
836+ http://pypi.python.org/pypi/keyring#downloads
837
838=== modified file 'backup_gmail.py'
839--- backup_gmail.py 2011-04-14 02:17:02 +0000
840+++ backup_gmail.py 2016-09-30 23:55:37 +0000
841@@ -2,6 +2,7 @@
842
843 """
844 Copyright 2011, Joseph Wen
845+Copyright 2016, C Fraire <cfraire@me.com>.
846 """
847
848 #TODO: MailBox
849@@ -10,8 +11,12 @@
850 import traceback
851 import email.message, email.utils
852 import re, sys, hashlib, os, shutil, time, optparse, mailbox, copy
853-from datetime import datetime
854+import locale
855+from datetime import datetime, date
856 import ConfigParser
857+from imapUTF7 import imapUTF7Encode, imapUTF7Decode
858+
859+KC_SERVICE_TEMPLATE = 'backup_gmail (%s)'
860
861 class MailMetaData:
862 @classmethod
863@@ -26,7 +31,6 @@
864 m.labels = set(tmp[4].split(" ^ "))
865 return m
866
867-
868 def __init__(self, id, hash_value = None, folder = None):
869 self.id = id
870 self.seen = False
871@@ -41,6 +45,69 @@
872 def __str__(self):
873 return "%s %s %s %s %s" % (self.id, self.folder, self.hash_value, str(self.seen), " ^ ".join(self.labels))
874
875+class FilterLabels(object):
876+ def __init__(self, include_list = None, exclude_list = None,
877+ strict_exclude = None, match_regex = None):
878+ self.include_list = include_list
879+ self.exclude_list = exclude_list
880+ self.strict_exclude = strict_exclude
881+ self.match_regex = match_regex
882+
883+ def __get_include_list(self):
884+ return self._include_list
885+
886+ def __set_include_list(self, iterable):
887+ self._include_list = None
888+ if iterable is not None:
889+ self._include_list = set(map(lambda y: y.lower(), iterable))
890+
891+ include_list = property(__get_include_list, __set_include_list)
892+
893+ def __get_exclude_list(self):
894+ return self._exclude_list
895+
896+ def __set_exclude_list(self, iterable):
897+ self._exclude_list = None
898+ if iterable is not None:
899+ self._exclude_list = set(map(lambda y: y.lower(), iterable))
900+
901+ exclude_list = property(__get_exclude_list, __set_exclude_list)
902+
903+ def __get_strict_exclude(self):
904+ return (self._strict_exclude == True)
905+
906+ def __set_strict_exclude(self, value):
907+ self._strict_exclude = (value == True)
908+
909+ strict_exclude = property(__get_strict_exclude, __set_strict_exclude)
910+
911+ def __get_match_regex(self):
912+ return self._match_regex.pattern if self._match_regex else None
913+
914+ def __set_match_regex(self, match_regex):
915+ self._match_regex = None
916+ if match_regex is not None:
917+ self._match_regex = re.compile(match_regex, re.I)
918+
919+ match_regex = property(__get_match_regex, __set_match_regex)
920+
921+ def filter(self, iterable):
922+ if self.include_list is None:
923+ result = list(iterable)
924+ else:
925+ result = filter(lambda x: x.lower() in self.include_list, iterable)
926+
927+ if self.exclude_list is not None:
928+ if not self.strict_exclude:
929+ result = filter(lambda x: x.lower() not in self.exclude_list, result)
930+ elif len(filter(lambda x: x.lower() in self.exclude_list, result)) > 0:
931+ result = list()
932+
933+ # use private directly here
934+ if self._match_regex is not None:
935+ result = filter(lambda x: self._match_regex.search(x) is not None, result)
936+ return result
937+
938 def getMID(env):
939 tmp = re.findall('(<[^>]+>)', env)
940 if len(tmp) == 0:
941@@ -87,15 +154,34 @@
942 def __str__(self):
943 return "MailBox [%s] does not exists.\nMailBox List: %s" % (self.str, self.l)
944
945- def __init__(self, username, password):
946- self.gmail_prefix = None
947+ class ApplicationError(Exception):
948+ def __init__(self, str):
949+ self.str = str
950+
951+ def __str__(self):
952+ return repr(self.str)
953+
954+ def __init__(self, options, progress = None):
955+ self.options = options
956+ self.progress = progress
957+ self.mails = {}
958+ self.mboxs = {}
959+ self.labels = set()
960+ self.gmail = None
961+ self.peek = True
962+ self.canceling = False
963+
964+ def cancel(self):
965+ self.canceling = True
966+
967+ def login(self):
968 self.gmail = imaplib.IMAP4_SSL('imap.gmail.com', 993)
969 try:
970- ret, message = self.gmail.login(username, password)
971+ ret, message = self.gmail.login(self.options.username, self.options.password)
972 except Exception as e:
973 raise self.AuthError("username or password incorrect")
974-
975- def resultCountCheck(self, result, number):
976+
977+ def __resultCountCheck(self, result, number):
978 if number.find(':') == -1:
979 return len(result) == 1
980 else:
981@@ -105,68 +191,132 @@
982 @UIDconverter
983 def fetchRFC822(self, uid):
984 data = []
985- while not self.resultCountCheck(data, uid):
986- ret, data = self.gmail.fetch(uid, 'RFC822')
987+ while not self.__resultCountCheck(data, uid):
988+ ret, data = self.gmail.fetch(uid, '(BODY.PEEK[])' if self.peek else 'RFC822')
989 data = filter(lambda x: len(x) == 2, data)
990 data = map(lambda x:(getUID(x[0]), x[1]), data)
991 return data
992
993 @UIDconverter
994- def fetchMessageId(self, uid):
995+ def fetchMessageId(self, uid): # return UID, MESSAGE-ID
996 data = []
997- while not self.resultCountCheck(data, uid):
998- ret, data = self.gmail.fetch(uid, '(BODY[HEADER.FIELDS (MESSAGE-ID)])')
999+ while not self.__resultCountCheck(data, uid):
1000+ ret, data = self.gmail.fetch(uid, '(BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)])' if self.peek \
1001+ else '(BODY[HEADER.FIELDS (MESSAGE-ID)])')
1002 data = filter(lambda x: len(x) == 2, data)
1003 data = map(lambda x:(getUID(x[0]), getMID(x[1])), data)
1004 return data
1005
1006 @UIDconverter
1007- def fetchRFC822Info(self, uid): # return UID, SIZE, SEEN
1008+ def fetchRFC822Info(self, uid): # return UID, SIZE, SEEN, MESSAGE-ID
1009 data = []
1010- while not self.resultCountCheck(data, uid):
1011- ret, data = self.gmail.fetch(uid, '(RFC822.SIZE FLAGS)')
1012- data = map(lambda x : (getUID(x), re.findall('RFC822.SIZE ([0-9]+)', x)[0], re.search("Seen", x) != None), data)
1013+ while not self.__resultCountCheck(data, uid):
1014+ ret, data = self.gmail.fetch(uid,
1015+ '(RFC822.SIZE FLAGS BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)])' if self.peek \
1016+ else '(RFC822.SIZE FLAGS BODY[HEADER.FIELDS (MESSAGE-ID)])')
1017+ data = filter(lambda x: len(x) == 2, data)
1018+ data = map(lambda x : (getUID(x[0]),
1019+ re.findall('RFC822.SIZE ([0-9]+)', x[0])[0],
1020+ re.search("Seen", x[0]) != None,
1021+ getMID(x[1])),
1022+ data)
1023 return data
1024
1025+ # start is inclusive, end is exclusive
1026 def searchByDate(self, start, end = None):
1027 if start == None and end == None:
1028 ret, result = self.gmail.search(None, 'ALL')
1029 return result[0].split()
1030 elif end == None:
1031- ret, result = self.gmail.search(None, '(SINCE "%s")' % (start, ))
1032+ gstart = GmailDate.fromLocal(start)
1033+ ret, result = self.gmail.search(None, '(SINCE "%s")' % (gstart, ))
1034 return result[0].split()
1035 elif start == None:
1036- ret, result = self.gmail.search(None, '(BEFORE "%s")' % (end, ))
1037+ gend = GmailDate.fromLocal(end)
1038+ ret, result = self.gmail.search(None, '(BEFORE "%s")' % (gend, ))
1039 return result[0].split()
1040 else:
1041- ret, result = self.gmail.search(None, '(SINCE "%s") (BEFORE "%s")' % (start, end))
1042+ gstart = GmailDate.fromLocal(start)
1043+ gend = GmailDate.fromLocal(end)
1044+ ret, result = self.gmail.search(None, '(SINCE "%s") (BEFORE "%s")' % (gstart, gend))
1045 return result[0].split()
1046
1047+ def get_FilterLabels(self):
1048+ lfilt = FilterLabels()
1049+ if self.options.include_labels is not None:
1050+ lfilt.include_list = self.options.include_labels.split('^')
1051+ if self.options.exclude_labels is not None:
1052+ lfilt.exclude_list = self.options.exclude_labels.split('^')
1053+ lfilt.strict_exclude = self.options.strict_exclude
1054+ lfilt.match_regex = self.options.match_regex
1055+ return lfilt
1056+
1057+ def fetchSpecialLabels(self):
1058+ ret, result = self.gmail.xatom('XLIST', '', '*')
1059+ xlist = self.gmail.response('XLIST')[1]
1060+ xlabels = {}
1061+ for x in xlist:
1062+ m = re.match(r'\(([^\)]+)\) "/" "([^"]+)"', x)
1063+ if m is None:
1064+ continue
1065+ attrbs = set(m.group(1).split())
1066+ utf7label = m.group(2)
1067+ label = imapUTF7Decode(utf7label).encode('utf-8')
1068+
1069+ for attr in ['\\Inbox', '\\AllMail', '\\Drafts', '\\Sent', '\\Starred', '\\Trash' ]:
1070+ if attr in attrbs:
1071+ xlabels[attr] = label
1072+ return xlabels
1073+
1074 def fetchLabelNames(self):
1075 labels = self.gmail.list()[1]
1076- return map(lambda x:x[0],
1077+ return map(lambda x:imapUTF7Decode(x).encode('utf-8'),
1078+ map(lambda x:x[0],
1079 filter(lambda x : len(x) > 0,
1080- map(lambda x : re.findall('\(\\\\HasNoChildren\) "/" "([^"]+)"', x), labels)))
1081+ map(lambda x : re.findall('\(\\\\HasNoChildren\) "/" "([^"]+)"', x), labels))))
1082+
1083+ def isValidMailBox(self, name):
1084+ ret, mail_count = self.gmail.select(imapUTF7Encode(name.decode('utf-8')))
1085+ return (ret != 'NO')
1086
1087 def selectMailBox(self, name):
1088- ret, mail_count = self.gmail.select(name)
1089+ ret, mail_count = self.gmail.select(imapUTF7Encode(name.decode('utf-8')))
1090 if ret == 'NO':
1091 raise self.SelectMailBoxError(name, self.fetchLabelNames())
1092 return mail_count
1093
1094- def getGmailPrefix(self):
1095- if self.gmail_prefix != None:
1096- return self.gmail_prefix
1097- labels = self.fetchLabelNames()
1098- prefixs = filter(lambda x: x.find('/All Mail') != -1, labels)
1099- if len(prefixs) == 0:
1100- raise self.SelectMailBoxError('<All Mail>', labels)
1101-
1102- p = prefixs[0].split('/')[0]
1103- if len(prefixs) > 1:
1104- print "There are multiple possible prefixs for Gmail mailbox use [%s]" % (p, )
1105- self.gmail_prefix = p
1106- return self.gmail_prefix
1107+ def checkDir(self):
1108+ if not os.path.isdir(self.options.backup_dir):
1109+ raise self.ApplicationError('[%s] is not a directory!\n' % (self.options.backup_dir, ))
1110+
1111+ def readLabelFile(self):
1112+ labelFile = "%s/label" % (self.options.backup_dir, )
1113+ if os.path.exists(labelFile):
1114+ with open(labelFile) as f:
1115+ for line in f:
1116+ m = MailMetaData.fromStr(line.strip())
1117+ self.mails[m.id] = m
1118+ for l in m.labels:
1119+ self.labels.add(l)
1120+
1121+ def isInTimeFrame(self, date_range, dateTuple):
1122+ if dateTuple == None:
1123+ return True
1124+ if date_range == None or (date_range[0] == None and date_range[1] == None):
1125+ return True
1126+ try:
1127+ date = datetime(*dateTuple[:7])
1128+ except:
1129+ return False
1130+ if date_range[0] == None:
1131+ end = datetime.strptime(date_range[1], "%d-%b-%Y")
1132+ return date < end
1133+ if date_range[1] == None:
1134+ start = datetime.strptime(date_range[0], "%d-%b-%Y")
1135+ return start < date
1136+ start = datetime.strptime(date_range[0], "%d-%b-%Y")
1137+ end = datetime.strptime(date_range[1], "%d-%b-%Y")
1138+ return start < date and date < end
1139
1140 def setFlag(self, uid, flag):
1141 self.gmail.store(uid, '+Flags', flag)
1142@@ -175,278 +325,360 @@
1143 self.gmail.store(uid, '-Flags', flag)
1144
1145 class BackupGmail(Gmail):
1146- def __init__(self, username, password, dest, progress = None):
1147- super(BackupGmail, self).__init__(username, password)
1148- self.mboxs = {}
1149- self.mails = {}
1150- self.keep_read_status = False
1151- self.progress = progress
1152- self.dest = dest
1153+ def __init__(self, options, progress = None):
1154+ super(BackupGmail, self).__init__(options, progress)
1155 self.exclude_mids = set()
1156+ self.written = {}
1157
1158 self.fetchBuffer = []
1159 self.fetchStart = '-1'
1160 self.fetchEnd = '-1'
1161 self.fetchSize = 0
1162
1163- def addToMBox(self, label, mail):
1164- if label not in self.mboxs:
1165- self.mboxs[label] = mailbox.mbox('%s/%s.mbox' % (self.dest, label.replace('/', '-'), ), create = True)
1166- self.mboxs[label].add(mail)
1167+ def formatMegabytes(self, v):
1168+ v /= 1000000.0
1169+ return '%.2f MB' % (v,)
1170
1171- def initProgress(self, infos):
1172+ def __initProgress(self, infos):
1173 total = sum(map(lambda x:int(x[1]), infos))
1174- self.progress.setRange(0, total)
1175- self.progress.setValue(0)
1176-
1177- def fetchMailByLabel(self, label, date_range):
1178- self.progress.setText("\rFetching %s [calculate size] \r" % (label, ))
1179+ self.progress.formatter = self.formatMegabytes
1180+ self.progress.setRange(0, total, 0)
1181+
1182+ def __fetchMailByLabel(self, label, date_range):
1183+ self.progress.setText("Fetching %s [calculate size]" % (label, ))
1184+
1185+ isValid = self.isValidMailBox(label)
1186+ if isValid == False:
1187+ self.progress.setText("Label [%s] cannot be selected." % (label, ))
1188+ self.progress.newLine()
1189+ return
1190+
1191 mail_count = self.selectMailBox(label)
1192 if date_range[0] == None and date_range[1] == None:
1193 infos = self.fetchRFC822Info('1:%s' % (mail_count[0], ))
1194- envs = self.fetchMessageId('1:%s' % (mail_count[0], ))
1195 else:
1196 date_range = self.searchByDate(*date_range)
1197 infos = self.fetchRFC822Info(date_range)
1198- envs = self.fetchMessageId(date_range)
1199-
1200- self.progress.setText("\rFetching %s [@value/@max] \r" % (label, ))
1201- self.initProgress(infos)
1202- total = 0
1203-
1204- for i, (env, info) in enumerate(zip(envs, infos)):
1205- uid, mid = env
1206- uid, size, seen = info
1207+
1208+ self.__initProgress(infos)
1209+ self.progress.setText("Fetching %s [@value/@max]" % (label, ))
1210+
1211+ for i, info in enumerate(infos):
1212+ if self.canceling:
1213+ break
1214+ uid, size, seen, mid = info
1215 if mid not in self.mails:
1216 if mid not in self.exclude_mids:
1217- self.fetchMail(uid, seen, label, size)
1218+ self.__fetchMail(uid, seen, label, size)
1219 else:
1220 self.mails[mid].labels.add(label)
1221- self.addToMBox(label, self.mails[mid].getMail(self.dest))
1222- if seen == False and self.keep_read_status:
1223- self.unsetFlag(uid, '\\Seen')
1224- total += int(size)
1225- self.progress.setValue(total)
1226+ self.progress.setValue(self.progress.value + int(size), True)
1227
1228 #Flush all pending request
1229- self.flushFetchMailRequest()
1230-
1231- def processMail(self, rfc, seen, label):
1232+ self.__flushFetchMailRequest()
1233+
1234+ self.progress.setText("Fetched %s [@value/@max]" % (label, ))
1235+ self.progress.newLine()
1236+
1237+ def __processMail(self, rfc, seen, label):
1238 mail = email.message_from_string(rfc)
1239 date = email.utils.parsedate(mail.get('date'))
1240 if date == None or len(date) != 9:
1241 fold = "Date-Unknown"
1242 else:
1243- fold = time.strftime("%Y-%m", date)
1244+ # %Y-%m directly from the tuple, in case time part is invalid
1245+ fold = "%04d-%02d" % (date[0], date[1])
1246+
1247 h = hashlib.sha256(rfc).hexdigest()
1248 mid = mail.get('message-id')
1249 if mid == None:
1250 mid = "<%s@backupgmail.com>" % (h, )
1251- mail.add_header('message-id', mid)
1252- rfc = mail.as_string()
1253- mail = email.message_from_string(rfc)
1254- try:
1255- os.mkdir("%s/%s" % (self.dest, fold))
1256- except OSError as e:
1257- pass
1258- with open("%s/%s/%s" % (self.dest, fold, h), 'w') as f:
1259- f.write(rfc)
1260+
1261+ mdir = "%s/%s" % (self.options.backup_dir, fold)
1262+ if not os.path.isdir(mdir):
1263+ os.mkdir(mdir)
1264+
1265+ mfile = "%s/%s/%s" % (self.options.backup_dir, fold, h)
1266+ if not os.path.exists(mfile):
1267+ with open(mfile, 'w') as f:
1268+ try:
1269+ f.write(rfc)
1270+ except:
1271+ # in case the write fails, delete the file
1272+ f.close()
1273+ os.remove(mfile)
1274+ raise
1275+ self.written[mid] = h
1276
1277 if mid not in self.mails:
1278 self.mails[mid] = MailMetaData(mid, h, fold)
1279 self.mails[mid].seen = seen
1280
1281 self.mails[mid].labels.add(label)
1282- self.addToMBox(label, mail)
1283
1284- def flushFetchMailRequest(self):
1285+ def __flushFetchMailRequest(self):
1286 if self.fetchBuffer == []:
1287 return
1288
1289 rfcs = self.fetchRFC822('%s:%s' % (self.fetchStart, self.fetchEnd))
1290- if self.keep_read_status:
1291- for i, rfc in enumerate(rfcs):
1292- if self.fetchBuffer[i][0] == False:
1293- self.unsetFlag(rfc[0], '\\Seen')
1294 for i, rfc in enumerate(rfcs):
1295- self.processMail(rfc[1], *self.fetchBuffer[i])
1296+ self.__processMail(rfc[1], *self.fetchBuffer[i])
1297
1298+ self.progress.setValue(self.progress.value + self.fetchSize)
1299 self.fetchBuffer = []
1300 self.fetchEnd = '-1'
1301 self.fetchSize = 0
1302
1303- def fetchMail(self, uid, seen, label, size):
1304+ def __fetchMail(self, uid, seen, label, size):
1305 size = int(size)
1306 if len(self.fetchBuffer) > 300 or self.fetchSize > 10000000:
1307- self.flushFetchMailRequest()
1308+ self.__flushFetchMailRequest()
1309 if int(self.fetchEnd) + 1 == int(uid):
1310 self.fetchEnd = uid
1311 self.fetchBuffer += [(seen, label)]
1312 self.fetchSize += size
1313 else:
1314- self.flushFetchMailRequest()
1315+ self.__flushFetchMailRequest()
1316 self.fetchStart = uid
1317 self.fetchEnd = uid
1318 self.fetchBuffer += [(seen, label)]
1319 self.fetchSize += size
1320-
1321- def fetchAllLabel(self, date_range, exclude_labels = []):
1322- #FIXME need support for multi lanugage
1323- #ignore = ['%s/All Mail' % (self.getGmailPrefix(), ),
1324- # '%s/Trash' % (self.getGmailPrefix(), ),
1325- # '%s/Spam' % (self.getGmailPrefix(), )] + exclude_labels
1326- #labels = filter(lambda x : x not in ignore , self.fetchLabelNames())
1327+
1328+ # Fetch default Gmail folders excluding the special \Drafts and \Trash
1329+ def __fetchDefaultLabels(self):
1330 labels = self.fetchLabelNames()
1331-
1332- for l in labels:
1333- self.fetchMailByLabel(l, date_range)
1334-
1335- def fetchAllMail(self, date_range, exclude_labels = []):
1336- if exclude_labels != []:
1337- labels = filter(lambda x : x in exclude_labels, self.fetchLabelNames())
1338- for l in labels:
1339- mail_count = self.selectMailBox(l)
1340- tmp = set(map(lambda x:x[1], self.fetchMessageId("1:%s" % (mail_count[0], ))))
1341- self.exclude_mids.update(tmp)
1342- #FIXME need support for multi lanugage
1343- #self.fetchMailByLabel('%s/All Mail' % (self.getGmailPrefix(), ), date_range)
1344- self.fetchAllLabel(date_range, exclude_labels)
1345+ specials = self.fetchSpecialLabels()
1346+ if '\\AllMail' in specials: # AllMail with no space
1347+ allMail = specials['\\AllMail']
1348+ if allMail not in labels:
1349+ labels.append(allMail)
1350+ ignore = []
1351+ for labelkey in [ '\\Drafts', '\\Trash' ]:
1352+ if labelkey in specials:
1353+ ignore.append(specials[labelkey])
1354+ labels = filter(lambda x : x not in ignore , labels)
1355+ return labels
1356+
1357+ def __fetchByLabels(self):
1358+ self.written = {}
1359+ self.exclude_mids = set()
1360+
1361+ lfilt = self.get_FilterLabels()
1362+ lfilt.strict_exclude = False # strict_exclude is done via exclude_mids below
1363+ exclude_labels = lfilt.exclude_list
1364+
1365+ if self.options.strict_exclude and exclude_labels is not None:
1366+ for l in exclude_labels:
1367+ if self.isValidMailBox(l):
1368+ mail_count = self.selectMailBox(l)
1369+ tmp = set(map(lambda x:x[1], self.fetchMessageId("1:%s" % (mail_count[0], ))))
1370+ self.exclude_mids.update(tmp)
1371+
1372+ date_range = [self.options.start_date, self.options.end_date]
1373+
1374+ default_labels = self.__fetchDefaultLabels()
1375+ backupLabel = lfilt.filter(default_labels)
1376+ for l in backupLabel:
1377+ if self.canceling:
1378+ self.progress.setText("Backup was canceled by user.")
1379+ self.progress.newLine()
1380+ break;
1381+ self.__fetchMailByLabel(l, date_range)
1382+
1383+ self.progress.setText("Backed up %d previously-unseen message(s)." % (len(self.written), ))
1384+ self.progress.newLine()
1385
1386- def outputLable(self):
1387- with open(self.dest + '/label', 'w') as f:
1388+ def __outputLable(self):
1389+ with open(self.options.backup_dir + '/label', 'w') as f:
1390 for k in self.mails:
1391 print >> f, self.mails[k]
1392
1393- def checkDir(self, overwrite):
1394- try:
1395- os.mkdir(self.dest)
1396- except OSError as e:
1397- if e.errno == 17:
1398- if overwrite == False:
1399- s = raw_input("[%s] Already exists overwrite? (use -i for incremental backup) [N/y]" % (e.filename, ))
1400- else:
1401- s = 'Y'
1402- if s == 'Y' or s == 'y' or s == 'yes':
1403- shutil.rmtree(self.dest)
1404- os.mkdir(self.dest)
1405- else:
1406- exit()
1407- else:
1408- raise e
1409-
1410- def doBackup(self, date_range = None, include_labels = None, exclude_labels = None):
1411- try:
1412- self.mboxs = {}
1413- if include_labels == None and exclude_labels == None:
1414- self.fetchAllMail(date_range)
1415- elif include_labels != None:
1416- for l in include_labels:
1417- self.fetchMailByLabel(l, date_range)
1418- elif exclude_labels != None:
1419- self.fetchAllMail(date_range, exclude_labels)
1420+ def makeDir(self):
1421+ if not os.path.exists(self.options.backup_dir):
1422+ os.mkdir(self.options.backup_dir)
1423+ self.checkDir()
1424+
1425+ def execute(self):
1426+ self.login()
1427+ self.peek = self.options.keep_read
1428+ self.makeDir()
1429+ self.readLabelFile()
1430+
1431+ try:
1432+ self.__fetchByLabels()
1433 finally:
1434- self.outputLable()
1435- for m in self.mboxs:
1436- self.mboxs[m].flush()
1437-
1438- def backupTo(self, date_range = None, overwrite = False, include_labels = None, exclude_labels = None):
1439- self.checkDir(overwrite)
1440- self.doBackup(date_range, include_labels, exclude_labels)
1441-
1442- def incrementalBackupTo(self, date_range = None, include_labels = None, exclude_labels = None):
1443- try:
1444- with open("%s/label" % (self.dest, )) as f:
1445- for line in f.readlines():
1446- m = MailMetaData.fromStr(line.strip())
1447- self.mails[m.id] = m
1448- except:
1449- self.backupTo(date_range, False, include_labels, exclude_labels)
1450- return
1451- self.doBackup(date_range, include_labels, exclude_labels)
1452-
1453+ self.__outputLable()
1454+ self.canceling = False
1455+
1456+class SaveMbox(Gmail):
1457+ def __init__(self, options, progress):
1458+ super(SaveMbox, self).__init__(options, progress)
1459+
1460+ def __addToMBox(self, label, mail):
1461+ if label not in self.mboxs:
1462+ odir = os.path.expanduser(self.options.mbox_export)
1463+ self.mboxs[label] = mailbox.mbox('%s/%s.mbox' % (odir, label.replace('/', '-'), ), create = True)
1464+ self.mboxs[label].clear()
1465+ self.mboxs[label].flush()
1466+ self.mboxs[label].add(mail)
1467+
1468+ def execute(self):
1469+ date_range = [self.options.start_date, self.options.end_date]
1470+ amFilteringDates = (date_range[0], date_range[1]) != (None, None)
1471+ lfilt = self.get_FilterLabels()
1472+
1473+ self.checkDir()
1474+ self.readLabelFile()
1475+
1476+ odir = os.path.expanduser(self.options.mbox_export)
1477+ if not os.path.exists(odir):
1478+ os.mkdir(odir)
1479+
1480+ ntotal = len(self.mails)
1481+ self.progress.setRange(0, ntotal, 0)
1482+ self.progress.setText("Exporting messages to mbox(es) [@value/@max]")
1483+
1484+ nsaved = 0
1485+ for i, m in enumerate(self.mails.values()):
1486+ if self.canceling:
1487+ self.progress.setText('Export was canceled by user.')
1488+ self.progress.newLine()
1489+ break
1490+ self.progress.setValue(i + 1)
1491+ updateLabel = lfilt.filter(m.labels)
1492+ if len(updateLabel) < 1:
1493+ continue
1494+ with open("%s/%s/%s" % (self.options.backup_dir, m.folder, m.hash_value)) as f:
1495+ mail = f.read()
1496+ e = email.message_from_string(mail)
1497+ if amFilteringDates:
1498+ dateTuple = email.utils.parsedate(e.get('date'))
1499+ if not self.isInTimeFrame(date_range, dateTuple):
1500+ continue
1501+
1502+ for label in updateLabel:
1503+ self.__addToMBox(label, mail)
1504+ nsaved += 1
1505+
1506+ for i, m in enumerate(self.mboxs.values()):
1507+ m.flush()
1508+
1509+ self.progress.setText("Exported %d of %d message(s) to mbox(es)" % (nsaved, ntotal))
1510+ self.progress.newLine()
1511+ self.canceling = False
1512
1513 class RestoreGmail(Gmail):
1514- def __init__(self, username, password, src, progress):
1515- super(RestoreGmail, self).__init__(username, password)
1516- self.labels = set(self.fetchLabelNames())
1517- self.progress = progress
1518- self.src = src
1519- self.mails = {}
1520+ def __init__(self, options, progress):
1521+ super(RestoreGmail, self).__init__(options, progress)
1522
1523- def appendMessage(self, message, date, mailbox = None):
1524- ret, msg = self.gmail.append(mailbox, None, date, message)
1525+ def __appendMessage(self, message, date, mailbox = None):
1526+ utf7mailbox = None
1527+ if mailbox is not None:
1528+ utf7mailbox = imapUTF7Encode(mailbox.decode('utf-8'))
1529+ if isinstance(date, str):
1530+ if len(date) < 1:
1531+ date = None
1532+ elif (date[0],date[-1]) != ('"','"'):
1533+ date = '"%s"' % date
1534+ ret, msg = self.gmail.append(utf7mailbox, None, date, message)
1535+ if ret != 'OK':
1536+ return ''
1537 return re.findall("APPENDUID [0-9]+ ([0-9]+)", msg[0])[0]
1538
1539- def assignLabel(self, uid, label):
1540- #FIXME need support for multi lanugage
1541- #if label == "%s/All Mail" % (self.getGmailPrefix(), ): return
1542+ def __assignLabel(self, uid, label):
1543+ self.__ensureLabel(label)
1544+ utf7label = imapUTF7Encode(label.decode('utf-8'))
1545+ ret, msg = self.gmail.uid('COPY', uid, utf7label)
1546+
1547+ def __ensureLabel(self, label):
1548 if label not in self.labels:
1549- self.gmail.create(label)
1550+ utf7label = imapUTF7Encode(label.decode('utf-8'))
1551+ self.gmail.create(utf7label)
1552 self.labels = set(self.fetchLabelNames())
1553- ret, msg = self.gmail.uid('COPY', uid, label)
1554-
1555- def isInTimeFrame(self, date_range, date):
1556- if date == None:
1557- return True
1558- if date_range == None or (date_range[0] == None and date_range[1] == None):
1559- return True
1560- if date_range[0] == None:
1561- end = datetime.strptime(date_range[1], "%d-%b-%Y")
1562- return date < end
1563- if date_range[1] == None:
1564- start = datetime.strptime(date_range[0], "%d-%b-%Y")
1565- return start < date
1566- start = datetime.strptime(date_range[0], "%d-%b-%Y")
1567- end = datetime.strptime(date_range[1], "%d-%b-%Y")
1568- return start < date and date < end
1569-
1570- def restore(self, date_range = None, include_labels = None, exclude_labels = None):
1571- with open("%s/label" % (self.src, )) as f:
1572- for line in f.readlines():
1573- m = MailMetaData.fromStr(line.strip())
1574- self.mails[m.id] = m
1575+
1576+ def execute(self):
1577+ date_range = [self.options.start_date, self.options.end_date]
1578+ amFilteringDates = (date_range[0], date_range[1]) != (None, None)
1579+ lfilt = self.get_FilterLabels()
1580+
1581+ self.checkDir()
1582+ self.login()
1583+
1584+ # Read label file for messages, but then set self.labels to what
1585+ # exists on the server. Each message in self.mails will still have
1586+ # its private set of labels
1587+ self.readLabelFile()
1588+ self.labels = set(self.fetchLabelNames())
1589+
1590+ ntotal = len(self.mails)
1591+ self.progress.setRange(0, ntotal, 0)
1592+ self.progress.setText("Processing messages for restore [@value/@max]")
1593
1594- #FIXME need support for multi lanugage
1595- #mail_count = self.selectMailBox('%s/All Mail' % (self.getGmailPrefix(), ))
1596- mail_count = self.selectMailBox('INBOX')
1597+ specials = self.fetchSpecialLabels()
1598+ inBoxes = [ 'inbox', specials['\\Inbox'].lower() ]
1599+ if '\\AllMail' not in specials: # AllMail with no space
1600+ raise self.ApplicationError('\\AllMail is not IMAP accessible!')
1601+ allMail = specials['\\AllMail']
1602+ labelTarget = allMail
1603+ if self.options.label_target is not None:
1604+ self.__ensureLabel(self.options.label_target)
1605+ labelTarget = self.options.label_target
1606+
1607+ nrestored = 0
1608+ mail_count = self.selectMailBox(labelTarget)
1609 for i, m in enumerate(self.mails.values()):
1610- print "\r%d" % (i),
1611- sys.stdout.flush()
1612-
1613- include = m.labels.intersection(include_labels) if include_labels != None else m.labels
1614- exclude = m.labels.intersection(exclude_labels) if exclude_labels != None else set()
1615- if include_labels != None and include == set():
1616- continue
1617- if exclude_labels != None and exclude != set():
1618- continue
1619- with open("%s/%s/%s" % (self.src, m.folder, m.hash_value)) as f:
1620+ if self.canceling:
1621+ self.progress.setText("Restore was canceled by user.")
1622+ self.progress.newLine()
1623+ break
1624+ self.progress.setValue(i + 1)
1625+ updateLabel = lfilt.filter(m.labels)
1626+ if len(updateLabel) < 1:
1627+ continue
1628+ with open("%s/%s/%s" % (self.options.backup_dir, m.folder, m.hash_value)) as f:
1629 mail = f.read()
1630 e = email.message_from_string(mail)
1631- date = email.utils.parsedate(e.get('date'))
1632- if date != None and not self.isInTimeFrame(date_range, datetime(*date[:7])):
1633- continue
1634- #FIXME need support for multi lanugage
1635- #uid = self.appendMessage(mail, date, '%s/All Mail' % (self.getGmailPrefix(), ))
1636- uid = self.appendMessage(mail, date, 'INBOX')
1637- updateLabel = m.labels.difference(exclude).intersection(include)
1638- for label in updateLabel:
1639- self.assignLabel(uid, label)
1640- print
1641+ date2822 = e.get('date')
1642+ if amFilteringDates:
1643+ dateTuple = email.utils.parsedate(date2822)
1644+ if not self.isInTimeFrame(date_range, dateTuple):
1645+ continue
1646+ uid = self.__appendMessage(mail, date2822, labelTarget)
1647+ if len(uid) < 1:
1648+ self.progress.newLine()
1649+ self.progress.setText("Failed to append %s/%s." % (m.folder, m.hash_value))
1650+ self.progress.newLine()
1651+ else:
1652+ nrestored += 1
1653+ for label in updateLabel:
1654+ if label.lower() not in inBoxes and label != allMail:
1655+ self.__assignLabel(uid, label)
1656+
1657+ self.progress.setText("Restored %d of %d message(s)." % (nrestored, ntotal))
1658+ self.progress.newLine()
1659+ self.canceling = False
1660
1661 class TerminalProgress:
1662 def __init__(self):
1663 self.value = 0
1664 self.min = 0
1665 self.max = 0
1666-
1667- def setRange(self, a, b):
1668+ self.maxWidth = 0
1669+ self.formatter = self.justString
1670+
1671+ def justString(self, v):
1672+ return str(v)
1673+
1674+ def setRange(self, a, b, v):
1675 self.min = a
1676 self.max = b
1677- self.update()
1678+ if v is not None:
1679+ self.value = v
1680
1681- def setValue(self, value):
1682+ def setValue(self, value, noupdate=False):
1683 self.value = value
1684- self.update()
1685+ if (not noupdate):
1686+ self.update()
1687
1688 def setText(self, t):
1689 self.text = t
1690@@ -454,111 +686,188 @@
1691
1692 def update(self):
1693 x = self.text
1694- x = x.replace('@value', str(self.value))
1695- x = x.replace('@max', str(self.max))
1696- print '\r%s' % (x, ),
1697+ x = x.replace('@value', self.formatter(self.value))
1698+ x = x.replace('@max', self.formatter(self.max))
1699+ xlen = len(x)
1700+ if xlen < self.maxWidth:
1701+ x = x + ' ' * (self.maxWidth - xlen)
1702+ else:
1703+ self.maxWidth = xlen
1704+ print '\r%s\r' % (x, ),
1705 sys.stdout.flush()
1706+
1707+ def newLine(self):
1708+ self.maxWidth = 0
1709+ print
1710+
1711+class GmailDate:
1712+ GMAIL_DFMT = '%d-%b-%Y' # i.e., dd-MMM-yyyy
1713+ POSIX_MONTHS = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
1714+
1715+ @classmethod
1716+ def toLocal(cls, gmail_date, format=GMAIL_DFMT):
1717+ dd, pMMM, yyyy = gmail_date.split('-', 3)
1718+ iMMM = cls.POSIX_MONTHS.index(pMMM)
1719+ pdate = date(int(yyyy), iMMM, int(dd))
1720+ return pdate.strftime(cls.GMAIL_DFMT)
1721+
1722+ @classmethod
1723+ def fromLocal(cls, date_string, format=GMAIL_DFMT):
1724+ d = datetime.strptime(date_string, format)
1725+ return '%02d-%s-%04d' % (d.day, cls.POSIX_MONTHS[d.month], d.year)
1726+
1727+class KeyringUtil:
1728+ def __init__(self, service_template):
1729+ self.service_template = service_template
1730+ try:
1731+ import keyring
1732+ except ImportError:
1733+ print >> sys.stderr, 'WARNING: keyring for secure passwords is not configured'
1734+ self.get_password_function = self.__noop_get_password
1735+ self.set_password_function = self.__noop_set_password
1736+ else:
1737+ self.get_password_function = keyring.get_password
1738+ self.set_password_function = keyring.set_password
1739+
1740+ def get_password(self, username):
1741+ servicename = self.service_template % (username, )
1742+ return self.get_password_function(servicename, username)
1743+
1744+ def set_password(self, username, password):
1745+ servicename = self.service_template % (username, )
1746+ self.set_password_function(servicename, username, password)
1747+
1748+ def __noop_get_password(self, servicename, username):
1749+ return None
1750+
1751+ def __noop_set_password(self, servicename, username, password):
1752+ return
1753
1754 def loadConfigFile(options, filename):
1755 config = ConfigParser.SafeConfigParser()
1756 config.read([filename, os.path.expanduser('~/.backup_gmail.cfg')])
1757+ keyu = KeyringUtil(KC_SERVICE_TEMPLATE)
1758 result = {}
1759 for section in config.sections():
1760- result[section] = copy.copy(options)
1761- result[section].username = config.get(section, 'username')
1762- result[section].password = config.get(section, 'password')
1763- result[section].backup_dir = config.get(section, 'backup_dir')
1764+ rsec = result[section] = copy.copy(options)
1765+ rsec.username = config.get(section, 'username')
1766+ rsec.backup_dir = config.get(section, 'backup_dir')
1767 if config.has_option(section, 'keep_read'):
1768- result[section].keep_read = config.getboolean(section, 'keep_read')
1769- if config.has_option(section, 'incremental'):
1770- result[section].incremental = config.getboolean(section, 'incremental')
1771+ rsec.keep_read = config.getboolean(section, 'keep_read')
1772 if config.has_option(section, 'start_date'):
1773- result[section].start_date = config.get(section, 'start_date')
1774+ rsec.start_date = config.get(section, 'start_date')
1775 if config.has_option(section, 'end_date'):
1776- result[section].end_date = config.get(section, 'end_date')
1777+ rsec.end_date = config.get(section, 'end_date')
1778 if config.has_option(section, 'include_labels'):
1779- result[section].include_labels = config.get(section, 'include_labels')
1780+ rsec.include_labels = config.get(section, 'include_labels')
1781 if config.has_option(section, 'exclude_labels'):
1782- result[section].exclude_labels = config.get(section, 'exclude_labels')
1783+ rsec.exclude_labels = config.get(section, 'exclude_labels')
1784+ if config.has_option(section, 'mbox_export'):
1785+ rsec.mbox_export = config.get(section, 'mbox_export')
1786+ if config.has_option(section, 'strict_exclude'):
1787+ rsec.strict_exclude = config.getboolean(section, 'strict_exclude')
1788+ if config.has_option(section, 'match_regex'):
1789+ rsec.match_regex = config.get(section, 'match_regex')
1790+ if rsec.username is not None and len(rsec.username):
1791+ rsec.password = keyu.get_password(rsec.username)
1792+ if rsec.password is None and config.has_option(section, 'password'):
1793+ rsec.password = config.get(section, 'password')
1794 return result
1795
1796 def saveConfigFile(profiles, filename):
1797 def set_helper(cfg, section, option, value):
1798 if value == None:
1799 return
1800- return cfg.set(section, option, str(value))
1801+ return cfg.set(section, option, value)
1802+ keyu = KeyringUtil(KC_SERVICE_TEMPLATE)
1803 config = ConfigParser.SafeConfigParser()
1804 for section in profiles:
1805 p = profiles[section]
1806 config.add_section(section)
1807 set_helper(config, section, 'username', p.username)
1808- set_helper(config, section, 'password', p.password)
1809 set_helper(config, section, 'backup_dir', p.backup_dir)
1810- set_helper(config, section, 'keep_read', p.keep_read)
1811- set_helper(config, section, 'incremental', p.incremental)
1812+ set_helper(config, section, 'keep_read', str(p.keep_read))
1813 set_helper(config, section, 'start_date', p.start_date)
1814 set_helper(config, section, 'end_date', p.end_date)
1815 set_helper(config, section, 'include_labels', p.include_labels)
1816 set_helper(config, section, 'exclude_labels', p.exclude_labels)
1817+ set_helper(config, section, 'mbox_export', p.mbox_export)
1818+ set_helper(config, section, 'strict_exclude', str(p.strict_exclude))
1819+ set_helper(config, section, 'match_regex', p.match_regex)
1820+ if p.password is not None and len(p.password):
1821+ if p.username is not None and len(p.username):
1822+ keyu.set_password(p.username, p.password)
1823 with open(filename, 'w') as f:
1824 config.write(f)
1825
1826 def getOptionParser():
1827- parser = optparse.OptionParser(usage = "%prog backup_dir email@address password")
1828- parser.add_option("-r", "--restore", dest="restore", action="store_true", default = False, help = "Restore backup to online gmail account")
1829- parser.add_option("-i", "--inc", dest="incremental", action="store_true", default = False, help = "Use incremental backup")
1830- parser.add_option("-k", "--keep_status", dest="keep_read", action="store_true", default = False, help = "Keep the mail read status (Slow)")
1831- parser.add_option("-s", "--start", dest="start_date", action="store", help = "Backup mail starting from this date. Format: 30-Jan-2010")
1832- parser.add_option("-e", "--end", dest="end_date", action="store", help = "Backup mail until to this date Format: 30-Jan-2010")
1833- parser.add_option("--include", dest="include_labels", action="store", help = "Only backup these labels. Seperate labels by '^' Format: label1^label2")
1834- parser.add_option("--exclude", dest="exclude_labels", action="store", help = "Do not backup these labels. If --include is used this flag will be ignored. Seperate labels by '^' Format: label1^label2")
1835+ parser = optparse.OptionParser(usage = "%prog [options] [backup_dir email@address password]")
1836+ parser.add_option("--dest", dest="backup_dir", action="store", help="Backup destination")
1837+ parser.add_option("--user", dest="username", action="store", help = "Gmail email@address")
1838+ parser.add_option("--password", dest="password", action="store", help = "Gmail password")
1839+ parser.add_option("-P", "--prompt", dest="prompt", action="store_true", default = False, help = "Prompt for Gmail credentials")
1840+ parser.add_option("-r", "--restore", dest="restore", action="store_true", default = False, help = "Restore backup to gmail (see --label)")
1841+ parser.add_option("-m", "--mbox_export", dest="mbox_export", action="store", help = "Save mbox(es) to directory")
1842+ parser.add_option("-k", "--keep_status", dest="keep_read", action="store_true", default = False, help = "Keep the mail read status")
1843+ parser.add_option("-s", "--start", dest="start_date", action="store",
1844+ help = "Process mail starting from this date (inclusive SINCE). Format: dd-MMM-yyyy in user's locale")
1845+ parser.add_option("-e", "--end", dest="end_date", action="store",
1846+ help = "Process mail until this date (exclusive BEFORE). Format: dd-MMM-yyyy in user's locale")
1847+ parser.add_option("--include", dest="include_labels", action="store",
1848+ help = "Only process these labels. Separate by '^' Format: label1^label2")
1849+ parser.add_option("--exclude", dest="exclude_labels", action="store",
1850+ help = "Do not process these labels. Separate by '^' Format: label1^label2")
1851+ parser.add_option("--strict_exclude", dest="strict_exclude", action="store_true", default = False,
1852+ help = "Backup: exclude also by message-id; Restore/Save: exclude completely if labeled")
1853+ parser.add_option("--match", dest="match_regex", action="store",
1854+ help = "Match labels to process by regex")
1855+ parser.add_option("-l", "--label", dest="label_target", action="store", help = "Restore also to specified label")
1856 parser.add_option("-c", "--config", dest="config_file", action="store", help = "Load setting from config file")
1857 parser.add_option("-p", "--profile", dest="profile", action="store", default = "Main", help = "Use this profile in the config file.")
1858 return parser
1859
1860-def doBackup(options, progress, overwrite = False):
1861- include_labels = exclude_labels = None
1862- if options.include_labels != None:
1863- include_labels = options.include_labels.split('^')
1864- if options.exclude_labels != None:
1865- exclude_labels = options.exclude_labels.split('^')
1866-
1867- backup = BackupGmail(options.username, options.password, options.backup_dir, progress)
1868- backup.keep_read_status = options.keep_read
1869- if options.incremental:
1870- backup.incrementalBackupTo([options.start_date, options.end_date], include_labels, exclude_labels)
1871- else:
1872- backup.backupTo([options.start_date, options.end_date], overwrite, include_labels, exclude_labels)
1873-
1874-def doRestore(options, progress, dummy = False):
1875- include_labels = exclude_labels = None
1876- if options.include_labels != None:
1877- include_labels = options.include_labels.split('^')
1878- if options.exclude_labels != None:
1879- exclude_labels = options.exclude_labels.split('^')
1880-
1881- restore = RestoreGmail(options.username, options.password, options.backup_dir, progress)
1882- restore.restore([options.start_date, options.end_date], include_labels, exclude_labels)
1883-
1884 if __name__ == '__main__':
1885+ locale.setlocale(locale.LC_TIME, '')
1886 parser = getOptionParser()
1887 (options, args) = parser.parse_args()
1888-
1889- if len(args) < 3 and options.config_file == None:
1890- parser.print_help()
1891- exit()
1892-
1893+
1894 if options.config_file != None:
1895 options = loadConfigFile(options, options.config_file)[options.profile]
1896- else:
1897- options.backup_dir= args[0]
1898+
1899+ if len(args) >= 1:
1900+ options.backup_dir = args[0]
1901+ elif options.backup_dir is None:
1902+ parser.print_help()
1903+ exit()
1904+
1905+ if len(args) >= 2:
1906 options.username = args[1]
1907+ if len(args) >= 3:
1908 options.password = args[2]
1909+
1910+ if options.prompt:
1911+ import getpass
1912+ options.username = raw_input('Username: ')
1913+ options.password = getpass.getpass()
1914+
1915+ canConnect = (options.username is not None and options.password is not None)
1916+ if options.mbox_export is None and canConnect == False:
1917+ parser.print_help()
1918+ exit()
1919+
1920 try:
1921- if options.restore == True:
1922- doRestore(options, TerminalProgress())
1923+ if canConnect == False:
1924+ pass
1925+ elif options.restore == True:
1926+ grestore = RestoreGmail(options, TerminalProgress())
1927+ grestore.execute()
1928 else:
1929- doBackup(options, TerminalProgress())
1930+ gbackup = BackupGmail(options, TerminalProgress())
1931+ gbackup.execute()
1932+
1933+ if options.mbox_export is not None:
1934+ gmbox = SaveMbox(options, TerminalProgress())
1935+ gmbox.execute()
1936 except Exception as e:
1937 traceback.print_exc(e)
1938 exit()
1939
1940=== modified file 'gui.py'
1941--- gui.py 2011-04-14 02:17:02 +0000
1942+++ gui.py 2016-09-30 23:55:37 +0000
1943@@ -6,7 +6,9 @@
1944 """
1945
1946 import sys
1947+import locale
1948 import traceback
1949+from datetime import datetime, date
1950 from PySide.QtCore import *
1951 from PySide.QtGui import *
1952
1953@@ -14,15 +16,13 @@
1954
1955 def getGuiOptionParser():
1956 parser = backup_gmail.getOptionParser()
1957- parser.add_option("--user", dest="username", action="store", help = "Gmail account name")
1958- parser.add_option("--password", dest="password", action="store", help = "Gmail account password")
1959- parser.add_option("--dest", dest="backup_dir", action="store", help = "Backup destination")
1960 return parser
1961
1962 class MainWindow(QMainWindow):
1963 def __init__(self, parent=None):
1964 super(MainWindow, self).__init__(parent)
1965 self.setWindowTitle("Backup Gmail")
1966+ self.setMinimumSize(640, 0)
1967
1968 self.config_label = QLabel("Profile:")
1969 self.config_select = QComboBox()
1970@@ -44,8 +44,8 @@
1971 self.backup_path = QLineEdit()
1972 self.backup_path_btn = QPushButton("Select")
1973
1974- self.keep_read = QCheckBox("Keep read/unread (Slow)")
1975- self.inc = QCheckBox("Incremental Backup")
1976+ self.keep_read = QCheckBox("Keep the mail read status")
1977+ self.keep_read.setChecked(True)
1978
1979 self.start_date_label = QLabel("From:")
1980 self.start_date = QDateEdit()
1981@@ -63,12 +63,21 @@
1982 self.end_date_enable = QCheckBox("Enable")
1983 self.end_date_enable.stateChanged.connect(self.end_date.setEnabled)
1984
1985- self.label_filter_label = QLabel("Label Filter:")
1986+ self.label_filter_label = QLabel("Label(s) Filter:")
1987 self.include_label = QRadioButton("Include")
1988 self.include_label.setChecked(True)
1989 self.exclude_label = QRadioButton("Exclude")
1990+ self.strict_exclude = QRadioButton("Exclude (Strict)")
1991 self.label_filter_text = QLineEdit()
1992- self.label_filter_text.setPlaceholderText("Keep empty to fetch all labels")
1993+ self.label_filter_text.setPlaceholderText("Optional; separate by '^'")
1994+
1995+ self.label_regex_label = QLabel("Label Regex:")
1996+ self.label_regex_text = QLineEdit()
1997+ self.label_regex_text.setPlaceholderText("Optional")
1998+
1999+ self.label_target_label = QLabel("Restore also to:")
2000+ self.label_target_text = QLineEdit()
2001+ self.label_target_text.setPlaceholderText("Optional label")
2002
2003 self.load_config_btn = QPushButton("Load Config")
2004 self.store_config_btn = QPushButton("Save Config")
2005@@ -100,12 +109,18 @@
2006 vTmp = QVBoxLayout()
2007 vTmp.addWidget(self.include_label)
2008 vTmp.addWidget(self.exclude_label)
2009+ vTmp.addWidget(self.strict_exclude)
2010 layout.addLayout(vTmp, 5, 2)
2011-
2012- layout.addWidget(self.backup_label, 6, 0)
2013- layout.addWidget(self.backup_path, 6, 1)
2014- layout.addWidget(self.backup_path_btn, 6, 2)
2015-
2016+
2017+ layout.addWidget(self.label_regex_label, 6, 0)
2018+ layout.addWidget(self.label_regex_text, 6, 1)
2019+
2020+ layout.addWidget(self.backup_label, 7, 0)
2021+ layout.addWidget(self.backup_path, 7, 1)
2022+ layout.addWidget(self.backup_path_btn, 7, 2)
2023+
2024+ layout.addWidget(self.label_target_label, 8, 0)
2025+ layout.addWidget(self.label_target_text, 8, 1)
2026
2027 btnLayout = QHBoxLayout()
2028 btnLayout.addWidget(self.load_config_btn)
2029@@ -115,7 +130,6 @@
2030
2031 checkLayout = QHBoxLayout()
2032 checkLayout.addWidget(self.keep_read)
2033- checkLayout.addWidget(self.inc)
2034
2035 vLayout.addLayout(layout)
2036 vLayout.addLayout(checkLayout)
2037@@ -160,58 +174,86 @@
2038 self.current_profile = text
2039
2040 def setUI(self, options):
2041- self.user_text.setText(options.username)
2042- self.pass_text.setText(options.password)
2043- self.backup_path.setText(options.backup_dir)
2044+ if options.username is not None:
2045+ self.user_text.setText(options.username.decode('utf-8'))
2046+ else:
2047+ self.user_text.clear()
2048+ if options.password is not None:
2049+ self.pass_text.setText(options.password.decode('utf-8'))
2050+ else:
2051+ self.pass_text.clear()
2052+ if options.backup_dir is not None:
2053+ self.backup_path.setText(options.backup_dir.decode('utf-8'))
2054+ else:
2055+ self.backup_path.clear()
2056
2057 self.keep_read.setChecked(options.keep_read == True)
2058- self.inc.setChecked(options.incremental == True)
2059
2060 if options.start_date != None:
2061+ sdate = QDate.fromString(options.start_date.decode('utf-8'), "dd-MMM-yyyy")
2062 self.start_date_enable.setChecked(True)
2063- self.start_date.setDate(QDate.fromString(options.start_date, "dd-MMM-yyyy"))
2064+ self.start_date.setDate(sdate)
2065 else:
2066 self.start_date_enable.setChecked(False)
2067
2068 if options.end_date != None:
2069+ # options.end_date is exclusive, but UI is inclusive, so subtract 1 day
2070+ edate = QDate.fromString(options.end_date.decode('utf-8'), "dd-MMM-yyyy").addDays(-1)
2071 self.end_date_enable.setChecked(True)
2072- self.end_date.setDate(QDate.fromString(options.end_date, "dd-MMM-yyyy"))
2073+ self.end_date.setDate(edate)
2074 else:
2075 self.end_date_enable.setChecked(False)
2076
2077 if options.include_labels != None:
2078 self.include_label.setChecked(True)
2079- self.label_filter_text.setText(options.include_labels)
2080+ self.label_filter_text.setText(options.include_labels.decode('utf-8'))
2081 elif options.exclude_labels != None:
2082- self.exclude_label.setChecked(True)
2083- self.label_filter_text.setText(options.exclude_labels)
2084+ if options.strict_exclude:
2085+ self.strict_exclude.setChecked(True)
2086+ else:
2087+ self.exclude_label.setChecked(True)
2088+ self.label_filter_text.setText(options.exclude_labels.decode('utf-8'))
2089 else:
2090 self.label_filter_text.setText("")
2091+
2092+ if options.match_regex is not None:
2093+ self.label_regex_text.setText(options.match_regex.decode('utf-8'))
2094+ else:
2095+ self.label_regex_text.setText("")
2096
2097 def saveUI(self, options):
2098- options.username = self.user_text.text()
2099- options.password = self.pass_text.text()
2100- options.backup_dir = self.backup_path.text()
2101+ options.username = self.user_text.text().encode('utf-8')
2102+ options.password = self.pass_text.text().encode('utf-8')
2103+ options.backup_dir = self.backup_path.text().encode('utf-8')
2104 options.keep_read = self.keep_read.isChecked()
2105- options.incremental = self.inc.isChecked()
2106+
2107 if self.start_date_enable.isChecked():
2108- options.start_date = self.start_date.date().toString("dd-MMM-yyyy")
2109+ options.start_date = self.start_date.date().toString("dd-MMM-yyyy").encode('utf-8')
2110 else:
2111 options.start_date = None
2112
2113 if self.end_date_enable.isChecked():
2114- options.end_date = self.end_date.date().toString("dd-MMM-yyyy")
2115+ # options.end_date is exclusive, so add 1 day
2116+ options.end_date = self.end_date.date().addDays(1).toString("dd-MMM-yyyy").encode('utf-8')
2117 else:
2118 options.end_date = None
2119
2120+ options.include_labels = None
2121+ options.exclude_labels = None
2122 if self.label_filter_text.text() != '':
2123 if self.include_label.isChecked():
2124- options.include_labels = self.label_filter_text.text()
2125+ options.include_labels = self.label_filter_text.text().encode('utf-8')
2126 else:
2127- options.exclude_labels = self.label_filter_text.text()
2128- else:
2129- options.include_labels = None
2130- options.exclude_labels = None
2131+ options.exclude_labels = self.label_filter_text.text().encode('utf-8')
2132+ options.strict_exclude = self.strict_exclude.isChecked()
2133+
2134+ options.match_regex = None
2135+ if self.label_regex_text.text() != '':
2136+ options.match_regex = self.label_regex_text.text().encode('utf-8')
2137+
2138+ options.label_target = None
2139+ if self.label_target_text.text() != '':
2140+ options.label_target = self.label_target_text.text().encode('utf-8')
2141
2142 def storeConfig(self):
2143 name = QFileDialog.getSaveFileName(self, "Open File", ".", "Config (*.cfg)")
2144@@ -234,7 +276,7 @@
2145 for section in result:
2146 self.config_select.addItem(section)
2147 self.current_profile = self.config_select.itemText(0)
2148- self.setUI(result[self.config_select.itemText(0)])
2149+ self.setUI(result[self.current_profile])
2150 self.config_file = result
2151
2152 def backup(self):
2153@@ -246,80 +288,89 @@
2154 self.restore_btn.setDisabled(True)
2155 self.backup_btn.setDisabled(True)
2156
2157- self.t = BackupRestoreThread(backup_gmail.doBackup, self.config_file[self.current_profile])
2158+ self.progress = QProgressDialog(self)
2159+ self.progress.setAutoClose(False)
2160+ self.progress.setWindowModality(Qt.WindowModal)
2161+ self.progress.setWindowTitle("Backup from %s" % (self.user_text.text(), ))
2162+ self.progress.setLabelText(" " * 100)
2163+ self.progress.canceled.connect(self.cancel_operation)
2164+
2165+ self.t = BackupRestoreThread(self.getBackerup, self.config_file[self.current_profile])
2166 self.t.finished.connect(self.backup_restore_finished)
2167 self.t.error.connect(self.show_error)
2168 self.t.backup_success.connect(self.show_backup_success)
2169- self.t.start()
2170+
2171 self.timer = QTimer(self)
2172 self.timer.timeout.connect(self.update_progress)
2173+
2174+ self.t.start()
2175 self.timer.start(1000)
2176-
2177- self.progress = QProgressDialog(self)
2178- self.progress.setAutoClose(False)
2179- self.progress.setWindowModality(Qt.WindowModal)
2180- self.progress.setWindowTitle("Backup from %s" % (self.user_text.text(), ))
2181- self.progress.setLabelText(" " * 100)
2182 self.progress.show()
2183
2184+ def getBackerup(self, options, progress):
2185+ return backup_gmail.BackupGmail(options, progress)
2186+
2187 def restore(self):
2188 self.restore_btn.setDisabled(True)
2189 self.backup_btn.setDisabled(True)
2190 self.saveUI(self.config_file[self.current_profile])
2191- self.t = BackupRestoreThread(backup_gmail.doRestore, self.config_file[self.current_profile])
2192+
2193+ self.progress = QProgressDialog(self)
2194+ self.progress.setAutoClose(False)
2195+ self.progress.setWindowModality(Qt.WindowModal)
2196+ self.progress.setWindowTitle("Restore to %s" % (self.user_text.text(), ))
2197+ self.progress.setLabelText(" " * 100)
2198+ self.progress.canceled.connect(self.cancel_operation)
2199+
2200+ self.t = BackupRestoreThread(self.getRestorer, self.config_file[self.current_profile])
2201 self.t.finished.connect(self.backup_restore_finished)
2202 self.t.error.connect(self.show_error)
2203 self.t.backup_success.connect(self.show_restore_success)
2204- self.t.start()
2205+
2206 self.timer = QTimer(self)
2207 self.timer.timeout.connect(self.update_progress)
2208+
2209+ self.t.start()
2210 self.timer.start(1000)
2211-
2212- self.progress = QProgressDialog(self)
2213- self.progress.setAutoClose(False)
2214- self.progress.setWindowModality(Qt.WindowModal)
2215- self.progress.setWindowTitle("Restore to %s" % (self.user_text.text(), ))
2216- self.progress.setLabelText(" " * 100)
2217 self.progress.show()
2218+
2219+ def getRestorer(self, options, progress):
2220+ return backup_gmail.RestoreGmail(options, progress)
2221+
2222+ def cancel_operation(self):
2223+ if self.t.gobj is not None:
2224+ self.t.gobj.cancel()
2225
2226 def show_error(self, message):
2227 msgBox = QMessageBox()
2228- msgBox.setWindowTitle("Error")
2229- msgBox.setIcon(QMessageBox.Critical)
2230- msgBox.setText(message)
2231- msgBox.exec_()
2232-
2233- def show_password_error(self):
2234- msgBox = QMessageBox()
2235- msgBox.setWindowTitle("Error")
2236- msgBox.setIcon(QMessageBox.Critical)
2237- msgBox.setText("username or password incorrect")
2238- msgBox.exec_()
2239-
2240- def show_backup_success(self):
2241- msgBox = QMessageBox()
2242- msgBox.setWindowTitle("Success")
2243- msgBox.setIcon(QMessageBox.Information)
2244- msgBox.setText("Backup success")
2245- msgBox.exec_()
2246-
2247- def show_restore_success(self):
2248- msgBox = QMessageBox()
2249- msgBox.setWindowTitle("Success")
2250- msgBox.setIcon(QMessageBox.Information)
2251- msgBox.setText("Restore success")
2252+ msgBox.setText("An error has occurred.")
2253+ msgBox.setIcon(QMessageBox.Critical)
2254+ msgBox.setInformativeText(message)
2255+ msgBox.exec_()
2256+
2257+ def show_backup_success(self, progress):
2258+ msgBox = QMessageBox()
2259+ msgBox.setText("The backup finished with no errors.")
2260+ msgBox.setIcon(QMessageBox.Information)
2261+ msgBox.setInformativeText(progress)
2262+ msgBox.exec_()
2263+
2264+ def show_restore_success(self, progress):
2265+ msgBox = QMessageBox()
2266+ msgBox.setText("The restore finished with no errors.")
2267+ msgBox.setIcon(QMessageBox.Information)
2268+ msgBox.setInformativeText(progress)
2269 msgBox.exec_()
2270
2271 def backup_restore_finished(self):
2272 self.restore_btn.setDisabled(False)
2273 self.backup_btn.setDisabled(False)
2274-
2275 self.progress.close()
2276
2277 def update_progress(self):
2278 self.progress.setRange(self.t.prog.min, self.t.prog.max)
2279 self.progress.setValue(self.t.prog.value)
2280- self.progress.setLabelText(self.t.prog.getText())
2281+ self.progress.setLabelText(self.t.prog.getText().decode('utf-8'))
2282
2283 class GuiProgress:
2284 def __init__(self):
2285@@ -327,42 +378,59 @@
2286 self.max = 1000
2287 self.value = 0
2288 self.text = ""
2289+ self.lines = []
2290+ self.formatter = self.justString
2291
2292- def setRange(self, a, b):
2293+ def setRange(self, a, b, v):
2294 self.min = a
2295- self.max = b / 1000.0
2296+ self.max = b
2297+ if v is not None:
2298+ self.value = v
2299
2300 def setValue(self, value):
2301- self.value = value / 1000.0
2302+ self.value = value
2303
2304 def setText(self, text):
2305 self.text = text
2306
2307+ def newLine(self):
2308+ self.lines.append(self.getText())
2309+ return
2310+
2311+ def getLines(self):
2312+ return self.lines
2313+
2314+ def justString(self, value):
2315+ return str(value)
2316+
2317 def getText(self):
2318- tmp = self.text.replace("@max", str(self.max))
2319- tmp = tmp.replace("@min", str(self.min))
2320- tmp = tmp.replace("@value", str(self.value))
2321+ tmp = self.text.replace("@max", self.formatter(self.max))
2322+ tmp = tmp.replace("@min", self.formatter(self.min))
2323+ tmp = tmp.replace("@value", self.formatter(self.value))
2324 return tmp
2325
2326 class BackupRestoreThread(QThread):
2327 error = Signal(str)
2328- backup_success = Signal()
2329+ backup_success = Signal(str)
2330 def __init__(self, func, options, parent=None):
2331 super(BackupRestoreThread, self).__init__(parent)
2332 self.func = func
2333 self.options = options
2334 self.prog = GuiProgress()
2335+ self.gobj = None
2336
2337 def run(self):
2338 try:
2339- self.func(self.options, self.prog, True)
2340+ self.gobj = self.func(self.options, self.prog)
2341+ self.gobj.execute()
2342 except Exception as e:
2343 traceback.print_exc(e)
2344 self.error.emit(e.__str__())
2345 return
2346- self.backup_success.emit()
2347+ self.backup_success.emit('\n'.join(self.prog.getLines()).decode('utf-8'))
2348
2349 if __name__ == '__main__':
2350+ locale.setlocale(locale.LC_TIME, '')
2351 app = QApplication(sys.argv)
2352 main = MainWindow()
2353 main.show()
2354
2355=== added file 'imapUTF7.py'
2356--- imapUTF7.py 1970-01-01 00:00:00 +0000
2357+++ imapUTF7.py 2016-09-30 23:55:37 +0000
2358@@ -0,0 +1,210 @@
2359+# -*- coding: iso-8859-1 -*-
2360+# Used with permission; See
2361+# http://mxm-mad-science.blogspot.com/2008/03/python-unicode-lessons-from-school-of.html
2362+# http://svn.plone.org/svn/collective/mxmImapClient/trunk/imapUTF7.py
2363+
2364+"""
2365+Imap folder names are encoded using a special version of utf-7 as defined in RFC
2366+2060 section 5.1.3.
2367+
2368+5.1.3. Mailbox International Naming Convention
2369+
2370+ By convention, international mailbox names are specified using a
2371+ modified version of the UTF-7 encoding described in [UTF-7]. The
2372+ purpose of these modifications is to correct the following problems
2373+ with UTF-7:
2374+
2375+ 1) UTF-7 uses the "+" character for shifting; this conflicts with
2376+ the common use of "+" in mailbox names, in particular USENET
2377+ newsgroup names.
2378+
2379+ 2) UTF-7's encoding is BASE64 which uses the "/" character; this
2380+ conflicts with the use of "/" as a popular hierarchy delimiter.
2381+
2382+ 3) UTF-7 prohibits the unencoded usage of "\"; this conflicts with
2383+ the use of "\" as a popular hierarchy delimiter.
2384+
2385+ 4) UTF-7 prohibits the unencoded usage of "~"; this conflicts with
2386+ the use of "~" in some servers as a home directory indicator.
2387+
2388+ 5) UTF-7 permits multiple alternate forms to represent the same
2389+ string; in particular, printable US-ASCII chararacters can be
2390+ represented in encoded form.
2391+
2392+ In modified UTF-7, printable US-ASCII characters except for "&"
2393+ represent themselves; that is, characters with octet values 0x20-0x25
2394+ and 0x27-0x7e. The character "&" (0x26) is represented by the two-
2395+ octet sequence "&-".
2396+
2397+ All other characters (octet values 0x00-0x1f, 0x7f-0xff, and all
2398+ Unicode 16-bit octets) are represented in modified BASE64, with a
2399+ further modification from [UTF-7] that "," is used instead of "/".
2400+ Modified BASE64 MUST NOT be used to represent any printing US-ASCII
2401+ character which can represent itself.
2402+
2403+ "&" is used to shift to modified BASE64 and "-" to shift back to US-
2404+ ASCII. All names start in US-ASCII, and MUST end in US-ASCII (that
2405+ is, a name that ends with a Unicode 16-bit octet MUST end with a "-
2406+ ").
2407+
2408+ For example, here is a mailbox name which mixes English, Japanese,
2409+ and Chinese text: ~peter/mail/&ZeVnLIqe-/&U,BTFw-
2410+
2411+"""
2412+import binascii
2413+import codecs
2414+
2415+# encoding
2416+
2417+def modified_base64(s):
2418+ s = s.encode('utf-16be')
2419+ return binascii.b2a_base64(s).rstrip('\n=').replace('/', ',')
2420+
2421+def doB64(_in, r):
2422+ if _in:
2423+ r.append('&%s-' % modified_base64(''.join(_in)))
2424+ del _in[:]
2425+
2426+def encoder(s):
2427+ r = []
2428+ _in = []
2429+ for c in s:
2430+ ordC = ord(c)
2431+ if 0x20 <= ordC <= 0x25 or 0x27 <= ordC <= 0x7e:
2432+ doB64(_in, r)
2433+ r.append(c)
2434+ elif c == '&':
2435+ doB64(_in, r)
2436+ r.append('&-')
2437+ else:
2438+ _in.append(c)
2439+ doB64(_in, r)
2440+ return (str(''.join(r)), len(s))
2441+
2442+
2443+# decoding
2444+
2445+def modified_unbase64(s):
2446+ b = binascii.a2b_base64(s.replace(',', '/') + '===')
2447+ return unicode(b, 'utf-16be')
2448+
2449+
2450+def decoder(s):
2451+ r = []
2452+ decode = []
2453+ for c in s:
2454+ if c == '&' and not decode:
2455+ decode.append('&')
2456+ elif c == '-' and decode:
2457+ if len(decode) == 1:
2458+ r.append('&')
2459+ else:
2460+ r.append(modified_unbase64(''.join(decode[1:])))
2461+ decode = []
2462+ elif decode:
2463+ decode.append(c)
2464+ else:
2465+ r.append(c)
2466+ if decode:
2467+ r.append(modified_unbase64(''.join(decode[1:])))
2468+ bin_str = ''.join(r)
2469+ return (bin_str, len(s))
2470+
2471+
2472+class StreamReader(codecs.StreamReader):
2473+ def decode(self, s, errors='strict'):
2474+ return decoder(s)
2475+
2476+
2477+class StreamWriter(codecs.StreamWriter):
2478+ def decode(self, s, errors='strict'):
2479+ return encoder(s)
2480+
2481+
2482+def imap4_utf_7(name):
2483+ if name == 'imap4-utf-7':
2484+ return (encoder, decoder, StreamReader, StreamWriter)
2485+codecs.register(imap4_utf_7)
2486+
2487+
2488+## testing methods
2489+
2490+def imapUTF7Encode(ust):
2491+ "Returns imap utf-7 encoded version of string"
2492+ return ust.encode('imap4-utf-7')
2493+
2494+def imapUTF7EncodeSequence(seq):
2495+ "Returns imap utf-7 encoded version of strings in sequence"
2496+ return [imapUTF7Encode(itm) for itm in seq]
2497+
2498+
2499+def imapUTF7Decode(st):
2500+ "Returns utf7 encoded version of imap utf-7 string"
2501+ return st.decode('imap4-utf-7')
2502+
2503+def imapUTF7DecodeSequence(seq):
2504+ "Returns utf7 encoded version of imap utf-7 strings in sequence"
2505+ return [imapUTF7Decode(itm) for itm in seq]
2506+
2507+
2508+def utf8Decode(st):
2509+ "Returns utf7 encoded version of imap utf-7 string"
2510+ return st.decode('utf-8')
2511+
2512+
2513+def utf7SequenceToUTF8(seq):
2514+ "Returns utf7 encoded version of imap utf-7 strings in sequence"
2515+ return [itm.decode('imap4-utf-7').encode('utf-8') for itm in seq]
2516+
2517+
2518+__all__ = ['imapUTF7Encode', 'imapUTF7Decode', ]
2519+
2520+if __name__=='__main__':
2521+
2522+## print u'bøx'.encode('imap4-utf-7')
2523+## print 'expected b&APg-x'
2524+##
2525+## print u'båx'.encode('imap4-utf-7')
2526+## print 'expected b&AOU-x'
2527+##
2528+ print '#######'
2529+ print 'bøx'
2530+ e = imapUTF7Encode(u'bøx')
2531+ print e
2532+ print imapUTF7Decode(e).encode('utf-8')
2533+
2534+ print '#######'
2535+ print 'båx'
2536+ e = imapUTF7Encode(u'båx')
2537+ print e
2538+ print imapUTF7Decode(e).encode('utf-8')
2539+
2540+ print '#######'
2541+ print '~/bågø'
2542+ e = imapUTF7Encode(u'~/bågø')
2543+ print e
2544+ print imapUTF7Decode(e).encode('utf-8')
2545+
2546+ print '#######'
2547+ print 'Ting & Såger'
2548+ e = imapUTF7Encode(u'Ting & Såger')
2549+ print e
2550+ print imapUTF7Decode(e).encode('utf-8')
2551+
2552+## e = imapUTF7Decode('b&AOU-x')
2553+## print e.encode('latin-1')
2554+##
2555+## e = imapUTF7Decode('b&APg-x')
2556+## print e.encode('latin-1')
2557+##
2558+ print '#######'
2559+ print '~/Følder/mailbåx & stuff + more'
2560+ n = u'~/Følder/mailbåx & stuff + more'
2561+ e = imapUTF7Encode(n)
2562+ print e
2563+ print imapUTF7Decode(e).encode('utf-8')
2564+
2565+ print '#######'
2566+ print '~peter/mail/&ZeVnLIqe-/&U,BTFw-'
2567+ print imapUTF7Decode('~peter/mail/&ZeVnLIqe-/&U,BTFw-').encode('utf-8')
2568+
2569\ No newline at end of file

Subscribers

People subscribed via source and target branches