This repository has been archived by the owner on May 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
classesLib.py
284 lines (271 loc) · 11.4 KB
/
classesLib.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
import os, locale
from typing import Union
import datetime
from cfgLib import Config
from helpersLib import get_dirname, purify, concat_dict, smartsize, sort, purify_filename
class DictAsObject(dict):
""" Let you use a dict like an object in JavaScript.
More to say, it's the ability to get a key with dot:
```
obj[key] = value
obj.key = value
```
"""
def __init__(self, **kwargs):
super().__init__(kwargs)
def __getattr__(self, key):
return self.get(key, None)
def __setattr__(self, key, value):
self[key] = value
return
def object_from_dict(d: dict):
""" Get a `DictAsObject` from a normal `dict`
"""
n = DictAsObject()
for i in d:
n[i] = d[i]
return n
class Page():
""" A generated page.
`content`: Text representation of page.
`status`: Status code.
`headers`: Headers to add, as a `dict`.
`cookies`: Cookies to add, as a `list`.
"""
content: str
status: int
headers: Union[dict, DictAsObject] = DictAsObject()
def __init__(self, content: str, status: int, headers=DictAsObject()):
self.content = content
self.status = status
self.headers = headers
class TplSection():
""" A template section.
`content`: Text in this section.
`params`: Params of this section. e.g. public, no log.
`symbols`: Symbols of this section, which is a `dict` with callable values.
"""
content: str
params: list
symbols: dict
def __init__(self, content: str, params: list, symbols: dict):
self.content = content
self.params = params
self.symbols = symbols
class UniParam():
""" Universal params.
`params`: A `list` of params, used by macros etc.
`symbols`: A `dict` with callable values, used by interpreter.
`interpreter`: A `TplInterpreter` instance.
`request`: The WSGI request.
`filelist`: A `FileList` object.
"""
params: list
symbols: dict = {}
interpreter = None
request = None
filelist = None
statistics = None
def __init__(self, params: list, **kwargs):
self.params = params
for i in kwargs:
setattr(self, i, kwargs[i])
def __getitem__(self, key):
return self.params[key]
def __setitem__(self, key, value):
self.params[key] = value
return
class MacroResult():
""" Macro result after executing.
`content`: Text representation of result.
`do_break`: Break macro execution?
`disconnect`: Disconnect this request?
`headers`: Headers to add, as a `dict`.
"""
content: str
do_break: bool = False
disconnect: bool = False
headers: dict = {}
def __init__(self, content: str, **kwargs):
self.content = content
for i in kwargs:
setattr(self, i, kwargs[i])
class MacroToCallable():
""" Make a string representing a macro (usually in special:alias) can be called as those in `scriptLib.py`
"""
def __init__(self, macro_str: str, param: UniParam, possibly_missing_markers=False):
# macro_str = param.interpreter.unquote(macro_str, param, False).content
if possibly_missing_markers:
if not (macro_str[0:2] == '{.' and macro_str[-2:] == '.}'):
macro_str = '{.' + macro_str + '.}'
self.macro_str = macro_str
self.interpreter = param.interpreter
def __call__(self, param: UniParam) -> MacroResult:
new_str = self.macro_str # Prevent changing original string
for i, j in enumerate(param.params):
new_str = new_str.replace('$' + str(i), j)
return self.interpreter.parse_text(new_str, param)
class FakeStatResult():
""" Works like a `os.stat_result`, but is writable and only contains what we want
"""
st_size: int # size of file, in bytes,
st_atime: float # time of most recent access,
st_mtime: float # time of most recent content modification,
def __init__(self, sr: os.stat_result):
self.st_size = sr.st_size
self.st_atime = sr.st_atime
self.st_mtime = sr.st_mtime
class ItemEntry():
""" A class that acts like `os.DirEntry`, but with more.
"""
name: str
path: str
url: str
_is_dir: bool
_stat: FakeStatResult
def __init__(self, path_real: str, path_virtual: str, base_virtual_dir='/'):
levels_real = path_real.split('/')
self.name = levels_real[-2] if path_real[-1] == '/' else levels_real[-1]
self.path = path_real
self.url = path_virtual[len(base_virtual_dir):]
self._is_dir = os.path.isdir(path_real)
self._stat = os.stat(path_real)
def is_file(self):
return not self._is_dir
def is_dir(self):
return self._is_dir
def stat(self):
return self._stat
class ZipItemEntry(ItemEntry):
""" Works for previewing files inside a zip
"""
name: str
path: str
url: str
_is_dir: bool
_stat: FakeStatResult
def __init__(self, zipinfo, zip_file_path_real: str, zip_file_path_virtual: str, base_virtual_dir='/'):
levels = zipinfo.filename.split('/')
self.name = levels[-2] if zipinfo.filename[-1] == '/' else levels[-1]
self.path = zip_file_path_real
self.url = zip_file_path_virtual + '?getitem=' + purify_filename(zipinfo.filename)
self._is_dir = zipinfo.filename[-1:] == '/'
zip_file_stats = FakeStatResult(os.stat(zip_file_path_real))
zip_file_stats.st_size = zipinfo.file_size
self._stat = zip_file_stats
class FileList():
""" A file list used in `tplLib.py` for generating `%list%`
`items`: A `list` of `ItemEntry`.
"""
items: list
def __init__(self, items: list):
self.items = items # sorted(items, key=lambda x: x.stat().st_ino)
self.count = len(items)
self.count_folders = len([True for x in items if x.is_dir()])
self.count_files = self.count - self.count_folders
def to_list(self, param: UniParam):
interpreter = param.interpreter
scanresult = self.items
fileinfos_file = { # for sorting
'name': [],
'ext': [],
'modified': [],
'added': [],
'size': []
}
fileinfos_folder = { # for sorting
'name': [],
'ext': [],
'modified': [],
'added': [],
'size': []
}
_file = interpreter.sections.get('file', interpreter.sections['_empty'])
_folder = interpreter.sections.get('folder', interpreter.sections['_empty'])
_link = interpreter.sections.get('link', interpreter.sections['_empty'])
links_file = []
links_folder = []
for e in scanresult:
# if not (os.path.exists(e.path) and os.access(e.path, os.R_OK)): # sometimes appears a non-exist or unreadable file
# continue
stats = e.stat()
url = e.url + ('' if e.is_file() and e.url[-1] != '/' else '/')
url = '{:' + url + ':}'
name = '{:' + e.name + ':}'
last_modified = str(datetime.datetime.fromtimestamp(stats.st_mtime)).split('.')[0]
last_modified_dt = stats.st_mtime
size = stats.st_size
if e.is_file():
fileinfos_file['name'].append(name)
fileinfos_file['ext'].append(name.split('.')[-1])
fileinfos_file['modified'].append(last_modified_dt)
fileinfos_file['added'].append(last_modified_dt)
fileinfos_file['size'].append(size)
param.symbols = concat_dict(param.symbols, {
'item-url': lambda p: MacroResult(url),
'item-full-url': lambda p: MacroResult(url),
'item-name': lambda p: MacroResult(name),
'item-ext': lambda p: MacroResult(name.split('.')[-1]),
'item-modified': lambda p: MacroResult(last_modified),
'item-modified-dt': lambda p: MacroResult(str(last_modified_dt)),
'item-size': lambda p: MacroResult(smartsize(size)),
'item-comment': lambda p: MacroResult(''),
'item-icon': lambda p: MacroResult('')
})
links_file.append(interpreter.parse_text(_file.content, param).content)
else:
fileinfos_folder['name'].append(name)
fileinfos_folder['ext'].append(name.split('.')[-1])
fileinfos_folder['modified'].append(last_modified_dt)
fileinfos_folder['added'].append(last_modified_dt)
fileinfos_folder['size'].append(size)
param.symbols = concat_dict(param.symbols, {
'item-url': lambda p: MacroResult(url),
'item-full-url': lambda p: MacroResult(url),
'item-name': lambda p: MacroResult(name),
'item-ext': lambda p: MacroResult(name.split('.')[-1]),
'item-modified': lambda p: MacroResult(last_modified),
'item-modified-dt': lambda p: MacroResult(str(last_modified_dt)),
'item-size': lambda p: MacroResult(smartsize(size)),
'item-comment': lambda p: MacroResult(''),
'item-icon': lambda p: MacroResult('')
})
links_folder.append(interpreter.parse_text(_folder.content, param).content)
sorting_comp = 'name'
sort_encoding = 'utf-8'
if Config.sort_encoding == '':
sort_encoding = locale.getpreferredencoding()
else:
sort_encoding = Config.sort_encoding
sorting_func = lambda a, b: int(sorted([a, b], key=lambda x: x.encode(sort_encoding)) != [a, b])
if 'sort' in param.request.args:
sort_by = param.request.args['sort']
rev = 'rev' in param.request.args
if sort_by == 'e' and not rev:
sorting_comp = 'ext'
sorting_func = lambda a, b: int(sorted([a, b]) != [a, b])
elif sort_by == 'n' and not rev:
sorting_comp = 'name'
sorting_func = lambda a, b: int(sorted([a, b], key=lambda x: x.encode(sort_encoding)) != [a, b])
elif sort_by == 't' and not rev:
sorting_comp = 'modified'
sorting_func = lambda a, b: a - b
elif sort_by == 's' and not rev:
sorting_comp = 'size'
sorting_func = lambda a, b: a - b
elif sort_by == '!e' or (sort_by == 'e' and rev):
sorting_comp = 'ext'
sorting_func = lambda a, b: int(sorted([a, b]) == [a, b])
elif sort_by == '!n' or (sort_by == 'n' and rev):
sorting_comp = 'name'
sorting_func = lambda a, b: int(sorted([a, b], key=lambda x: x.encode(sort_encoding)) == [a, b])
elif sort_by == '!t' or (sort_by == 't' and rev):
sorting_comp = 'modified'
sorting_func = lambda a, b: b - a
elif sort_by == '!s' or (sort_by == 's' and rev):
sorting_comp = 'size'
sorting_func = lambda a, b: b - a
links_folder = sort(links_folder, fileinfos_folder[sorting_comp], sorting_func)
links_file = sort(links_file, fileinfos_file[sorting_comp], sorting_func)
page_content = ''.join(links_folder) + ''.join(links_file)
return page_content