Coverage for app/logic/fileHandler.py: 88%
67 statements
« prev ^ index » next coverage.py v7.2.7, created at 2024-01-29 16:34 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2024-01-29 16:34 +0000
1import os
2from flask import redirect, url_for
3from app import app
4from app.models.attachmentUpload import AttachmentUpload
6class FileHandler:
7 def __init__(self,files=None, courseId=None, eventId=None):
8 self.files=files
9 self.path = app.config['files']['base_path']
10 self.courseId = courseId
11 self.eventId = eventId
12 if courseId:
13 self.path = os.path.join(self.path, app.config['files']['course_attachment_path'], str(courseId))
14 elif eventId:
15 # eventID is not included in the path, because it is now a part of the attachment filename.
16 self.path = os.path.join(self.path, app.config['files']['event_attachment_path'])
18 def makeDirectory(self):
19 # This creates a directory.
20 # Created to remove duplicates when an event is recurring.
21 try:
22 extraDir = str(self.eventId) if self.eventId else ""
23 os.makedirs(os.path.join(self.path, extraDir))
24 # Error 17 Occurs when we try to create a directory that already exists
25 except OSError as e:
26 if e.errno != 17:
27 print(f'Fail to create directory: {e}')
28 raise e
30 def getFileFullPath(self, newfilename = ''):
31 """
32 This creates the directory/path for the object from the "Choose File" input in the create event and edit event.
33 :returns: directory path for attachment
34 """
36 # Added the eventID of the first recurring event to track the file path for subsequent recurring events.
37 try:
38 # tries to create the full path of the files location and passes if
39 # the directories already exist or there is no attachment
40 filePath=(os.path.join(self.path, newfilename))
41 except AttributeError: # will pass if there is no attachment to save
42 pass
43 except FileExistsError:
44 pass
46 return filePath
48 def saveFiles(self, saveOriginalFile=None):
49 """ Saves the attachment in the app/static/files/eventattachments/ or courseattachements/ directory """
50 try:
51 for file in self.files:
52 saveFileToFilesystem = None
53 if self.eventId:
54 attachmentName = str(saveOriginalFile.id) + "/" + file.filename
56 # isFileInEvent checks if the attachment exists in the database under that eventId and filename.
57 isFileInEvent = AttachmentUpload.select().where(AttachmentUpload.event_id == self.eventId,
58 AttachmentUpload.fileName == attachmentName).exists()
59 if not isFileInEvent:
60 AttachmentUpload.create(event = self.eventId, fileName = attachmentName)
62 # Only save the file if our event is on its own, or the first of a recurring series
63 if saveOriginalFile and saveOriginalFile.id == self.eventId:
64 saveFileToFilesystem = attachmentName
66 elif self.courseId:
67 isFileInCourse = AttachmentUpload.select().where(AttachmentUpload.course == self.courseId, AttachmentUpload.fileName == file.filename).exists()
68 if not isFileInCourse:
69 AttachmentUpload.create(course = self.courseId, fileName = file.filename)
70 saveFileToFilesystem = file.filename
72 if saveFileToFilesystem:
73 self.makeDirectory()
74 file.save(self.getFileFullPath(newfilename = saveFileToFilesystem))
76 except AttributeError: # will pass if there is no attachment to save
77 pass
79 def retrievePath(self,files):
80 pathDict={}
81 for file in files:
82 pathDict[file.fileName] = ((self.path+"/"+ file.fileName)[3:], file)
84 return pathDict
86 def deleteFile(self, fileId):
87 """
88 Deletes attachmant from the app/static/files/eventattachments/ or courseattachments/ directory
89 """
90 file = AttachmentUpload.get_by_id(fileId)
91 file.delete_instance()
93 # checks if there are other instances with the same filename in the AttachmentUpload table
94 if not AttachmentUpload.select().where(AttachmentUpload.fileName == file.fileName).exists():
95 path = os.path.join(self.path, file.fileName)
96 os.remove(path)
98 def changeDisplay(self, fileId):
99 file = AttachmentUpload.get_by_id(fileId)
100 AttachmentUpload.update(isDisplayed=False).where(AttachmentUpload.event == file.event, AttachmentUpload.isDisplayed==True).execute()
101 AttachmentUpload.update(isDisplayed=True).where(AttachmentUpload.id == fileId).execute()
102 return ""