-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProjectController.py
executable file
·375 lines (259 loc) · 11.3 KB
/
ProjectController.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## SERGIO DEL CASTILLO t.me/sercliff
import auth
import pyrebase
import time
import json
import hashlib
import os
import glob
import threading
import Project
import DataController as dc
import UpdatesController
from aux import d2j
from aux import iprint
from aux import DEBUG
from aux import set_log as log
class ProjectController:
def __init__(self, owner_id, collaborators, project_id, link, platform):
self.owner_id = owner_id
self.project_id = project_id
self.link = link
self.platform = platform
self.updates_controller = None
## FUTURE: En colaboradores incluir en primer momento el owner(unico usuario e ir añadiendole el resto)
## FUTURE: Collaborators solo sirve en caso de querer incluir varios usuarios desde un primer momento pero no tiene que ser una funcionalidad necesaria
self.collaborators = collaborators
def new_project(self, scope, permissions):
"""
MAKE A NEW PROJECT AND SAVE IN THE DATABASE
scope : Determine the range of work, Project or file, and where are all
permissions : Determine the permissions of all project (For partial sharing in selected_text() method)
-> Return : Link/id of the project
"""
## TODO: Controlar gitignore
general_permissions = dict()
general_permissions['general'] = Project.Permissions.READ.value ## By default the permissions of files will be READ
if permissions == Project.Project_Permissions.FULL:
general_permissions['general'] = Project.Permissions.WRITE.value
current_directory = os.getcwd()+"/"
if self.platform != "web":
if 'range' in scope and scope['range'] == "project": ## We are sharing all our project
## MAKING FULL PROJECT WITH ALL PROJECT
#FUTURE: Para que solo algún archivo del proyecto se pueda editar y el resto visualizar, utilizar el método selected_text()
all_files = glob.glob(current_directory+'**', recursive=True) ## This version return an iterator, glob.glob returns a list
all_files.remove(os.getcwd()+"/")
iprint (DEBUG.PRINT, current_directory)
# iprint (DEBUG.PRINT, "\n|\t\tDIRECTORIES\r\t\t\t\t\t|\t\tDIRECTORY")
# for file in all_files:
# if os.path.isdir(file):
# iprint (DEBUG.PRINT, "| "+os.path.basename(file)+"\r\t\t\t\t\t| "+file.replace(current_directory, "/"))
# iprint (DEBUG.PRINT, "\n|\t\tFILE\r\t\t\t\t\t|\t\tDIRECTORY")
files = dict()
for file in all_files:
if os.path.isfile(file):
iprint (DEBUG.PRINT, "| "+os.path.basename(file)+"\r\t\t\t\t\t| "+file.replace(current_directory, "/"))
name = str(os.path.basename(file))
path = file.replace(current_directory, "/")
iprint (DEBUG.PRINT, "| "+name+"\r\t\t\t\t\t| "+path)
row_info = create_project_rowInfo(file, general_permissions) ## GENERAL PERMISSIONS EXPLAINED ON THE METHOD
file = create_project_files(name, path, permissions.value, row_info)
name_id = hashlib.md5(name.encode("utf-8")).hexdigest()
files[name_id] = file
project = dict()
project[self.project_id] = create_project(self.project_id, self.link, permissions.value, self.owner_id, files, self.collaborators)
# dc.update_project(project_to_json(project))
dc.update_project(d2j(project))
self.updates_controller = UpdatesController.UpdatesController(self.project_id, self.owner_id)
begin_updates(self.updates_controller)
elif 'range' in scope and scope['range'] == "file": ## Only we will share the file with name is in scope['path']
## MAKING FULL PROJECT WITH ONE FILE
file = scope['path']
name = str(os.path.basename(file))
path = file.replace(current_directory, "/")
iprint (DEBUG.PRINT, "| "+name+"\r\t\t\t\t\t| "+path)
row_info = create_project_rowInfo(file, general_permissions)
file = create_project_files(name, path, permissions.value, row_info)
files = dict()
name_id = hashlib.md5(name.encode("utf-8")).hexdigest()
files[name_id] = file
project = dict()
project[self.project_id] = create_project(self.project_id, self.link, permissions.value, self.owner_id, files, self.collaborators)
# dc.update_project(project_to_json(project))
dc.update_project(d2j(project))
self.updates_controller = UpdatesController.UpdatesController(self.project_id, self.owner_id)
begin_updates(self.updates_controller)
#TODO: CREAR SISTEMA DE SOPORTE PARA ARCHIVOS BINARIOS, FOTOGRAFÍAS, ETC
else:
iprint(DEBUG.PRINT, "With web platform create a new file of project and begin")
# TODO: CREAR LO NECESARIO PARA PLATAFORMA WEB
def add_collaborator(user_id, project_id):
#TODO: add_collaborator
iprint (DEBUG.PRINT, "NEW COLLABORATOR")
self.updates_controller = UpdatesController.UpdatesController(self.project_id, self.owner_id)
begin_updates(self.updates_controller)
def show_project_id(self):
#TODO: show_project_id, crear método que represente esta información en el plugin
return self.link
def stop_streaming(self):
stop_updates(self.updates_controller)
def selected_text(self, owner_id, permissions):
#TODO: selected_text
iprint (DEBUG.PRINT, "something")
def change_permissions(self, permissions):
#TODO: change_permissions
""" Mostrar permisos, decir a que pueden cambiar y cambiar """
iprint (DEBUG.PRINT, "something")
## ············································································································································ ##
def test_update(project_id, owner_id):
updates_controller = UpdatesController.UpdatesController(project_id, owner_id)
begin_updates(updates_controller)
def begin_updates(updates_controller):
""" PROCESS TO MANAGE UPDATES TO A USER """
iprint(DEBUG.WARNING, "Starting streaming updates")
t = threading.Thread(target=updates_controller.receive_updates)
# t = threading.Thread(target=u.updates, args=("mugreee",))
t.start()
def stop_updates(updates_controller):
""" FINISHING STREAMING UPDATES """
iprint(DEBUG.WARNING, "Finishing updates")
updates_controller.stop_updates()
iprint(DEBUG.WARNING, "Finished")
def create_project(project_id, link, permissions, owner_id, files, users):
project = dict()
project_data = dict()
project_data["id"] = project_id
project_data["permissions"] = permissions
project_data["link"] = link
project_data["owner_id"] = owner_id
project["project"] = project_data
file_files = dict()
file_data = dict()
for key, data in files.items():
file_files[key] = data["files"]
file_data[key] = data["file_data"]
project["files"] = file_files
project["file_data"] = file_data
project["users"] = users
return project
def create_user(user_id, name, platform):
user = dict()
user["user_id"] = user_id
user["name"] = name
user["platform"] = platform
return user
def create_project_files(name, path, permissions, data):
# return Project.Files(name, path, permissions, data)
iprint (DEBUG.PRINT, "CREATING PROJECT FILE INFO")
project_files = dict()
project_data = dict()
project_data["name"] = name
project_data["path"] = path
project_data["permissions"] = permissions
project_files["files"] = project_data
project_files["file_data"] = data
return project_files
def create_project_rowInfo(file_path, permissions):
"""
Make a RowInfo class with the information content in the file
file_path : The path of file that will be readed
permissions : dict[row, permission] with special permissions (if is empty all rows have Permissions.WRITE) || 'general' to assign manually general permissions
-> Return : dict[row, RowInfo] filled with the file_path information
"""
iprint (DEBUG.WARNING, "CREATING PROJECT RowInfo to: "+str(file_path))
row_info = dict()
row_json = dict()
try:
timestamp = "00/00/0000"
if len(permissions):
row_permissions = Project.Permissions.READ.value
elif 'general' in permissions:
row_permissions = permissions['general']
else:
row_permissions = Project.Permissions.WRITE.value
try:
with open(file_path) as file:
row=1
for line in file:
rowinfo_json = dict()
rowinfo_json["text"] = line
rowinfo_json["permissions"] = row_permissions
rowinfo_json["timestamp"] = timestamp
row_json[row] = rowinfo_json
del rowinfo_json
row+=1
# row_info[row] = Project.RowInfo(line, row_permissions, timestamp)
# print("\nrow_json")
# print(row_json)
# print("\nrow_json[1]")
# print(row_json[1])
# print("\nrow_json[1][text]")
# print(row_json[80]["text"])
try:
if not 'general' in permissions and len(permissions):
iprint(DEBUG.PRINT, "Rewrite rows with special permissions")
for row, permission in permissions.items():
row_info[row].set_permissions(permission)
except Exception as e:
iprint(DEBUG.ERROR, "[ProjectController][create_project_rowInfo] : Changing File Permissions was thrown an exception: "+str(e))
except Exception as e: ##---------------> TO BINARY FILES
#TODO: Mirar como solucionar el asunto para archivos que no son legibles
#TODO: Evitar almacenar información de archivos de los que no tenemos datos almacenados
iprint(DEBUG.WARNING, "---------------> THATS A BINARY FILE")
# with open(file_path, "rb") as file:
except Exception as e:
iprint(DEBUG.ERROR, "[ProjectController][create_project_rowInfo] : Reading File was thrown an exception: "+str(e))
iprint(DEBUG.WARNING, "RowInfo was done\n")
return row_json
# return row_info
def project_to_json(project):
""" Change project created on classes to JSON to be saved
-> Return a json with all elements of project
"""
iprint (DEBUG.PRINT, "***************************")
iprint (DEBUG.PRINT, "PARSE PROJECT TO JSON\n")
projects = dict()
project_data = dict()
project_data["id"] = project.get_project_id()
project_data["permissions"] = project.get_permissions()
project_data["link"] = project.get_link()
project_data["owner_id"] = project.get_owner_id()
files = dict()
file_data = dict()
for name, file in project.get_files().items():
name = hashlib.md5(name.encode('utf-8')).hexdigest()
files[name] = dict()
files[name]["name"] = file.get_name()
files[name]["path"] = file.get_path()
files[name]["permissions"] = file.get_name()
file_data[name] = dict()
for row, row_data in file.get_data().items():
file_data[name][row] = dict()
file_data[name][row]["text"] = row_data.get_text()
file_data[name][row]["permissions"] = row_data.get_permissions()
file_data[name][row]["timestamp"] = row_data.get_timestamp()
del row_data
del file
users = dict()
for user_id, user in project.get_users().items():
users[user_id] = dict()
users[user_id]["name"] = user.get_name()
users[user_id]["platform"] = user.get_platform()
users[user_id]["user_id"] = user.get_user_id()
del user
del project
# iprint (DEBUG.PRINT, "")
item = dict()
item["project"] = project_data
item["files"] = files
item["file_data"] = file_data
item["users"] = users
projects[project_data["id"]] = item
# iprint (DEBUG.PRINT, projects)
returned_data = json.dumps(projects)
data_string = json.dumps(projects, sort_keys=True, indent=4, separators=(',', ': '))
iprint (DEBUG.PRINT, 'JSON:'+ str(data_string))
# return returned_data
return json.loads(returned_data)