aboutsummaryrefslogtreecommitdiffstats
path: root/object.py
blob: 6825a700bbba87661b28982f7bed0a60d0b599bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# -*- coding: utf-8 -*-
import StringIO
import hashlib
import sys
import os
import os.path
import zlib
import datetime
import fileinput
import logging

from permission import *
from config import config

class Object:

    def __get_path(self):
        return self.name[:2] + '/' + self.name[2:]

    def __create_dir(self):
        if (not os.path.exists(self.name[:2])):
            os.mkdir(self.name[:2])

        if (not os.path.exists(self.path)):
            os.mkdir(self.path)

    ##
    # Save the object on the disk.
    def save(self):
        self.__createDir()

        header = "author " + self.data['author'] + "\n"
        header += "parent " + self.data['parent'] + "\n"
        header += "created " + self.data['created'] + "\n"
        header += "#\n" #end of header
        store = header + self.data['content']

        file = open(self.path + "/object", 'w')
        file.write(zlib.compress(store))
        file.close()
        os.mknod(self.path + "/childs")
        os.mknod(self.path + "/permissions")
        self.saved = True

    ##
    # Class constructor.
    def __init__(self, init):

        if isinstance(init, dict):
            if 'author' not in init:
                init['author'] = 'None'
            if 'parent' not in init:
                init['parent'] = 'None'
            if 'content' not in init:
                init['content'] = 'None'

            self.data = init
            self.data['created'] = str(datetime.datetime.now())
            self.name = hashlib.sha1(str(self.data)).hexdigest()
            self.path = self.__getPath()
            self.saved = False

        elif isinstance(init, str):
            if (os.path.exists(init)):
                file = open(self.path + '/object', 'r')
                contentStream = StringIO.StringIO(zlib.decompress(file.read()))
                data = {}

                for line in contentStream:
                    if (line == "#\n"):
                        data['content'] = contentStream.read()
                        break
                    else:
                        key, sep, value = line.rstrip('\n').partition(' ')
                        data[key] = value

                self.data = data
                file.close()

    def append_to(self, father):
        father.appendChild(self)

    def append_child(self, child):
        if not self.saved:
            self.save()

        file = open(self.path + "/childs", 'a')
        file.write(child.name + "\n")
        file.close()

    @staticmethod
    def get_permission_by_hash(hash, user):
        path = hash[:2] + '/' + hash[2:]
        try:
            file = open(path + '/permissions', 'r')
        except IOError:
            print 'cannot open', path
        else:
            for line in file:
                name, sep, perm = line.rstrip('\n').partition(' ')
                if name == user:
                    return perm

            return 0

    def get_permission(self, user):
        file = open(self.path + '/permissions', 'r')
        for line in file:
            name, sep, perm = line.rstrip('\n').partition(' ')
            if name == user:
                return perm
        
        return 0

    def set_permission(self, user, permission):
        if not self.saved:
            self.save()

        sentinel = False
        for line in fileinput.input(self.path + "/permissions", inplace = 1):
            name, sep, perm = line.rstrip('\n').partition(' ')
            if name == user:
                sys.stdout.write(name + ' ' + str(permission) + '\n')
                sentinel = True
            else:
                sys.stdout.write(line)

        if not sentinel:
            file = open(self.path + '/permissions', 'a')
            file.write(user + ' ' + str(permission) + '\n')
            file.close()

class ObjectHandler:

    def __init__(self, user):
        self.user = user
        self.root_directory = config.root + user + '/'
        self.root_object = hashlib.sha1(user).hexdigest()

        if not os.path.exists(self.root_directory):
            logging.error("User %s root doesn't exist" % self.user)

    def get_object_directory(self, hash):
        directory = self.root_directory + hash[:2] + '/' + hash[2:]
        if (os.path.exists(directory)):
            return directory
        else :
            return None

    def get_object(self, hash):
        directory = self.get_object_directory(hash)
        if directory is None :
            logging.error("Object %s doesn't exist" % hash)
        else :
            return Object(directory)

    #return a list of hash,permission pairs
    def get_child_list(self, hash, user):
        directory = self.get_object_directory(hash)
        if (directory) :
            result = []
            file = open(directory + "/childs", 'r')
            for line in file :
                name = line.rstrip('\n')
                result.append(name)
            file.close()
            return result
        else :
            return None

    def create_home_node(self):
        pass

    def get_home_node(self):
        return self.root_object

if __name__ == '__main__':
    x = Object({'parent' : 'toto', 'author' : 'Zaran'})
    x.setPermission("test", READ)
    x.setPermission("toto", READ | MODIFY)
    x.setPermission("toto", READ | MODIFY | APPEND)
    x.setPermission("toto2", READ | MODIFY | APPEND)
    print x.getPermission("toto")
    print Object.getPermissionByHash(x.name, "toto")
    child = Object({'parent' : x.name, 'author' : 'Zaran'})
    child.save()

    x.appendChild(child)

    y = Object(x.name)
    print y.data['author']
    print y.data['parent']
    print y.data['content']
    print y.data['created']