Mikael's blog

A developers sixth time trying to maintain a blog

Source Code - Root / controllers / sourceController.js
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
/*****************************************
 *   Source Controller
 *****************************************
 *   Author:  mikael.lofjard@gmail.com
 *   Website: http://lofjard.se
 *   License: MIT License
 ****************************************/
  
var SourceController = (function() {
  
    var fs = require('fs');
    var path = require('path');
  
    // Server Side Syntax Highlighting
    var sh = require('../forked/sssh/shCore').SyntaxHighlighter;
  
    var viewManager = require('../viewManager').ViewManager;
    var env = require('../environmentManager').EnvironmentManager;
    var responseManager = require('../responseManager').ResponseManager;
    var misc = require('../misc').Misc;
  
    var db = null;
    var staticFileController = null;
    var fileStructure = { name: 'Root' };
      
    var excludedDirectoryNames = [ 'content/img/upload', 'secrets', 'certs', 'node_modules' ];
   
    function populateFileStructure(dirPath, node) {
        node.files = [];
        node.directories = [];
          
        var filesInPath = fs.readdirSync(path.join(process.cwd(), dirPath));
          
        for (var i in filesInPath) {
            var fileName = filesInPath[i];
            var filePath = path.join(dirPath, fileName);
            var stat = fs.statSync(path.join(process.cwd(), filePath));
              
            if (stat.isFile()) {
                var fetchPath = filePath.replace(/\./g, '-dot-').replace(/\//g, '-slash-');
                var file = {
                    icon: '',
                    name: fileName,
                    path: fetchPath,
                    sourcePath: getSourcePath(fetchPath),
                    content: getFileContent(path.join(process.cwd(), filePath)),
                    size: getFileSize(stat.size)
                }
                  
                node.files.push(file);
            }
            else if (stat.isDirectory()) {
                if (excludedDirectoryNames.indexOf(filePath) == -1) {
                    var fetchPath = filePath.replace(/\//g, '-slash-');
                    var subDir = {
                        icon: '',
                        name: fileName,
                        path: fetchPath,
                        sourcePath: getSourcePath(fetchPath)
                    };
                      
                    populateFileStructure(filePath, subDir);
                    node.directories.push(subDir);
                }
            }
        }
    }
      
    function getFileSize(size) {
        if (size > 1024) {
            return (size / 1024).toFixed(1) + ' kb';
        } else if (size > (1024 * 1024)) {
            return (size / (1024 * 1024)).toFixed(1) + ' mb';
        }
        return size + ' b'
    }
      
    function getSourcePath(fetchPath) {
        var sourcePath = '<a href="/source">Root</a>';
        var basePath = '';
        var splitPath = fetchPath.split('-slash-');
        if (splitPath.length > 1 ) {
            for (var i = 0; i < splitPath.length - 1; i++) {
            basePath += ((i == 0) ? '' : '-slash-') + splitPath[i];
            sourcePath += ' / <a href="/source/dir/' + basePath + '">' + splitPath[i] + '</a>'
            }
        }
          
        return sourcePath;
    }
  
    function getFileContent(filePath) {
        var ending = path.extname(filePath);
        var cssClass = '';
        var fileContent = fs.readFileSync(filePath, 'utf-8');
          
        switch(ending) {
        case '.inc':
            cssClass = 'brush: js; html-script: true, toolbar: false';
            var temp = fileContent.replace(/\{/g, '{');
            temp = temp.replace(/\}/g, '}');
            temp = temp.replace(/\>/g, '>');
            temp = temp.replace(/\</g, '<');
            fileContent = temp;
            break;
        case '.js':
            cssClass = 'brush: js; toolbar: false';
            var temp = fileContent.replace(/\>/g, '>');
            temp = temp.replace(/\</g, '<');
            fileContent = temp;
            break;
        case '.css':
            cssClass = 'brush: css; toolbar: false';
            break;
        case '.mu':
        case '.html':
            cssClass = 'brush: html; toolbar: false';
            var temp = fileContent.replace(/\{/g, '{');
            temp = temp.replace(/\}/g, '}');
            temp = temp.replace(/\>/g, '>');
            temp = temp.replace(/\</g, '<');
            fileContent = temp;
            break;
        case '.png':
        case '.jpg':
        case '.gif':
        case '.ico':
            var relPath = path.join('/',
                path.relative(
                    path.join(process.cwd(), '/content'),
                    path.dirname(filePath)
                ), path.basename(filePath));
            return '<img src="' + relPath + '" />'
            break;
        default:
            cssClass = 'brush: none; toolbar: false'
        }
          
        var startTag = '<pre class="' + cssClass + '">\n';
        var endTag = '\n</pre>';
          
        return startTag + fileContent + endTag;
    }
      
    function getDirFromPath(dirPath) {
        pathParts = dirPath.split('-slash-');
          
        var dir = getDirRecursive(pathParts, fileStructure);
        return dir;
    }
  
    function getFileFromPath(filePath) {
        pathParts = filePath.split('-slash-');
          
        var file = getFileRecursive(pathParts, fileStructure);
        return file;
    }
      
    function getDirRecursive(pathParts, node) {
        env.info("Recurse dir call - parts: " + pathParts);
        {
            for (var di in node.directories) {
                var dir = node.directories[di];
                  
                if (dir.name == pathParts[0])
                {
                    env.info("Recurse dir call - found dir");
                    if (pathParts.length == 1) {
                        env.info("Recurse dir call - found last dir, returning it");
                        return dir;
                    } else {
                        pathParts.reverse();
                        pathParts.pop();
                        pathParts.reverse();
                        return getDirRecursive(pathParts, dir);
                    }
                }
            }
            return -1;
        }
    }
      
    function getFileRecursive(pathParts, node) {
        env.info("Recurse call - parts: " + pathParts);
        if (pathParts.length == 1) {
            env.info("Recurse call - only one part, search files");
            for (var fi in node.files) {
                var file = node.files[fi];
                  
                env.info("Recurse call - compare " + file.name + " with " + pathParts[0].replace(/-dot-/g,'.'));
                if (file.name == pathParts[0].replace(/-dot-/g,'.')) {
                    return file;
                }
            }
            return -1;
        } else
        {
            for (var di in node.directories) {
                var dir = node.directories[di];
                  
                if (dir.name == pathParts[0])
                {
                    pathParts.reverse();
                    pathParts.pop();
                    pathParts.reverse();
                    return getFileRecursive(pathParts, dir);
                }
            }
            return -1;
        }
    }
      
    return {
      
        init: function(dbInit, staticFileControllerInit) {
            db = dbInit;
            staticFileController = staticFileControllerInit;
              
            populateFileStructure('', fileStructure);
        },
          
        index: function(request, response) {
            env.info('SourceController - Source Directory Root requested');
          
            var model = {
                directories: fileStructure.directories,
                files: fileStructure.files,
                sourcePath: fileStructure.name
            }
              
            var responseData = viewManager.renderView(response, 'sourcedir', model);
            responseManager.writeResponse(request, response, responseData);
  
            return;
        },
  
        dir: function(request, response) {
            env.info('SourceController - Source Directory requested');
          
            var dir = (request.params.dir == null) ? fileStructure : getDirFromPath(request.params.dir);
            if (dir === -1) {
                staticFileController.error(request, response, 404);
                return;
            }
              
            var model = {
                name: dir.name,
                sourcePath: dir.sourcePath,
                directories: dir.directories,
                files: dir.files
            }
              
            var responseData = viewManager.renderView(response, 'sourcedir', model);
            responseManager.writeResponse(request, response, responseData);
  
            return;
        },
  
        file: function(request, response) {
            env.info('SourceController - Source File requested');
  
            var file = getFileFromPath(request.params.file);
            if (file === -1) {
                staticFileController.error(request, response, 404);
                return;
            }
              
            var model = {
                sourcePath: file.sourcePath,
                name: file.name,
                content: sh.highlight(file.content),
                size: file.size
            };
              
            var responseData = viewManager.renderView(response, 'sourcefile', model);
            responseManager.writeResponse(request, response, responseData);
  
            return;
        }
    };
  
}());
  
typeof(exports) != 'undefined' ? exports.SourceController = SourceController : null;