File size: 4,783 Bytes
ae4627d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#GENERAL HELPER CLASSES: FileManager, Switch 
import cherrypy, os, threading, subprocess

#=======MANAGE FILES==========================================================#
class FileManager:

    # initialise the object
    def __init__(self): 
        self.lock = threading.Lock() 

    # Generate the filepath to the datadir when given an fid or uuid
    def grab_datapath(self, theid, whichpath='fidpath'):
        # Check if theid is a uuid
        if len(theid) > 20:
            fid = 'we need to discover the fid'
        else:
            fid = theid
        # Now lets build the path
        datadir = os.path.join(os.path.dirname(__file__), cherrypy.config['datadir'])  
        fidpath = os.path.join(datadir, fid)  
        # And finally return the full path
        if whichpath is 'fidpath':
            return fidpath
        elif whichpath is 'original':
            return os.path.join(fidpath, 'original')
    
    # Grab the full path to a file uploaded the the 'original' dir in 'data/fid/original'
    def grab_originalfilepath(self, theid, filename):
        originalpath = self.grab_datapath(theid, 'original')
        fullfilepath = os.path.join(originalpath, filename)  
        if not os.path.exists(fullfilepath): 
            return False
        else:
            return fullfilepath
    
    # Grab the full filwpath when given two segments
    def grab_joinedpath(self, left, right):
        return os.path.join(left, right)  
           
    # Save a string to a file
    def saveStringToFile(self, string, filepath):
        with open(filepath, "w") as text_file:
            print(string, file=text_file)
    
    # Save a downloaded file in chunks
    def saveAsChunks(self, myFile, basePath):
        filepath = os.path.join(basePath, myFile.filename)
        out = "length: %s Name: %s Mimetype: %s"
        size = 0
        while True:
            data = myFile.file.read(8192)
            if not data:
                break
            with open(filepath, "ba") as mynewfile:
                mynewfile.write(data)
                mynewfile.close()
            size += len(data)
        return out % (size, myFile.filename, myFile.content_type)
    
    # Check if the file has one of a collection of filetypes 
    def fileisoneof(self, filename, allowedfiletypes):
        msg = ''
        allowed = allowedfiletypes.split()
        dotpos = filename.rfind('.')
        suffix = filename[ dotpos+1 : filename.__len__() ]   
        if dotpos > -1 and suffix in allowed:
            return True
        else :
            return False

    # Create a directory at the specified path
    def createDirAt(self, fullpath) :
        # Check the new name doesn't already exist
        if not os.path.exists(fullpath):
            os.makedirs(fullpath)
            return fullpath
        else :
            return "Error: No Directory Created"

    # Create a new unique directory in the style of "0000001"
    def createUniqueDirAt(self, parentdir):
        # Make sure this can only be run once at a time
        self.lock.acquire() 
        # Grab the most recently modified directory
        try:
            recent = max([os.path.join(parentdir,d) for d in os.listdir(parentdir)], key=os.path.getmtime) 
        except:
            recent = "0"
        recent = recent.replace(parentdir+'/', '') 
        # Convert directory name to an int
        recentint = int(recent)
        # Generate a new directory name and filepath incremended by one
        newdir=str(recentint+1)
        newdir=newdir.zfill(9)
        newfullpath = parentdir+'/'+newdir
        # Check the new name doesn't already exist
        success = self.createDirAt(newfullpath)
        # We done what we've needed so lets release the lock
        self.lock.release() 
        return newdir
    
    # Grab the first line of a file
    def grabheader(self, fullfilepath):
        if os.path.exists(fullfilepath):  
            thebytes = subprocess.check_output("head -n1 "+fullfilepath, shell=True)
            # Output is returned as bytes so we need to convert it to a string
            return thebytes.decode("utf-8").strip()
        else:
            return 'no file found at: '+fullfilepath

# Nice switch statement object
class Switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration
    
    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False