File: save_load.py

package info (click to toggle)
cycle 0.3.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 572 kB
  • sloc: python: 1,987; makefile: 23
file content (150 lines) | stat: -rw-r--r-- 5,588 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# coding: koi8-r
# ====================================================
#	Cycle - calendar for women
#	Distributed under GNU Public License
# Author: Oleg S. Gints (altgo@users.sourceforge.net)
# Home page: http://cycle.sourceforge.net
# ===================================================
import hashlib
import pickle
import os.path
import os
import cal_year
import wx
import warnings
# deprecated since release 2.3
warnings.filterwarnings("ignore",
                        category=DeprecationWarning,
                        message='.*rotor module', module=__name__)

try:
    import rotor
except:
    import p_rotor as rotor

# Unpickler with class renaming for compatibility with old saves
import io
class OldCycleUnpickler(pickle.Unpickler):
    def find_class(self, module, name):
        renamed_module = module
        if module == "sip":
            renamed_module = "wx.siplib"
        return super(OldCycleUnpickler, self).find_class(renamed_module, name)

def loadPickledCycles(s):
    file = io.BytesIO(s)
    return OldCycleUnpickler(file).load()

def Save_Cycle(name='cycle', passwd='123', file='cycle'):
    """ Save the contents of our document to disk.
    """
    objSave = []
    m = hashlib.md5()
    m.update(passwd.encode('utf-8'))
    rt = rotor.newrotor(m.digest())
    objSave.append(['period', cal_year.cycle.period])
    objSave.append(['by_average', cal_year.cycle.by_average])
    objSave.append(['disp', cal_year.cycle.disp])
    objSave.append(['first_week_day', cal_year.cycle.first_week_day])
    objSave.append(['note', cal_year.cycle.note])
    for d in cal_year.cycle.begin:
        objSave.append(['begin', [d.GetDay(), d.GetMonth(), d.GetYear()]])

    for d in cal_year.cycle.last:
        objSave.append(['last', [d.GetDay(), d.GetMonth(), d.GetYear()]])

    for d in cal_year.cycle.tablet:
        objSave.append(['tablet', [d.GetDay(), d.GetMonth(), d.GetYear()]])

    for d in list(cal_year.cycle.colour_set.keys()):
        objSave.append(['colour', [d, cal_year.cycle.colour_set[d].Get()]])

    tmp = rt.encrypt(b'Cycle'+pickle.dumps(objSave))
    tmp = b"UserName="+pickle.dumps(name)+b"==="+tmp
    p, f_name = get_f_name(file)

    if not os.path.exists(p):
        os.mkdir(p, 0o700)
    f = open(f_name, "wb")
    f.write(tmp)
    f.close()
#    print "All data saved to disk"


def Load_Cycle(name='cycle', passwd='123', file='cycle'):

    p, f_name = get_f_name(file)
    if os.path.isfile(f_name):
        m = hashlib.md5()
        m.update(passwd.encode('utf-8'))
        rt = rotor.newrotor(m.digest())
        f = open(f_name, "rb")
        tmp = f.read()
        if tmp[:len(b"UserName=")] == b"UserName=":
            # new format
            n = tmp.find(b"===")+len(b"===")
            tmp = tmp[n:]  # remove username
        tmp = rt.decrypt(tmp)
        f.close()
        if tmp[0:5] != b'Cycle':
            #	    print 'Password is invalid'
            return False
        else:
            tmp = tmp[5:]  # remove control word 'Cycle'
            objLoad = loadPickledCycles(tmp)
            set_color_default()
            for type, d in objLoad:
                #		print "Load: ", type, d
                if type == 'period':
                    cal_year.cycle.period = int(d)
                elif type == 'by_average':
                    cal_year.cycle.by_average = int(d)
                elif type == 'disp':
                    cal_year.cycle.disp = int(d)
                elif type == 'first_week_day':
                    cal_year.cycle.first_week_day = int(d)
                elif type == 'begin':
                    dt = wx.DateTime.FromDMY(d[0], d[1], d[2])
                    cal_year.cycle.begin.append(dt)
                elif type == 'last':
                    dt = wx.DateTime.FromDMY(d[0], d[1], d[2])
                    cal_year.cycle.last.append(dt)
                elif type == 'tablet':
                    dt = wx.DateTime.FromDMY(d[0], d[1], d[2])
                    cal_year.cycle.tablet.append(dt)
                elif type == 'note':
                    cal_year.cycle.note = d.copy()
                elif type == 'colour':  # d=['item', (r,g,b)]
                    c = wx.Colour(d[1][0], d[1][1], d[1][2])
                    if d[0] in cal_year.cycle.colour_set:
                        cal_year.cycle.colour_set[d[0]] = c
                    else:
                        cal_yaar.cycle.colour_set.update({d[0]: c})
#	    print "Load OK"
            return True

# -------------------------------------------------------


def get_f_name(name=""):
    if '__WXMSW__' in wx.PlatformInfo:
        p = os.path.join(os.getcwd(), "data")
    else:
        p = os.path.expanduser("~/.cycle")
    f_name = os.path.join(p, name)

    return p, f_name

# -------------------------------------------------------


def set_color_default():
    cal_year.cycle.colour_set = {'begin': wx.TheColourDatabase.Find('RED'),
                                 'prog begin': wx.TheColourDatabase.Find('PINK'),
                                 'conception': wx.TheColourDatabase.Find('MAGENTA'),
                                 'safe sex': wx.TheColourDatabase.Find('WHEAT'),
                                 'fertile': wx.TheColourDatabase.Find('GREEN YELLOW'),
                                 'ovule': wx.TheColourDatabase.Find('SPRING GREEN'),
                                 '1-st tablet': wx.TheColourDatabase.Find('GOLD'),
                                 'pause': wx.TheColourDatabase.Find('LIGHT BLUE'),
                                 'next 1-st tablet': wx.TheColourDatabase.Find('PINK')}