Mikael's blog

A developers sixth time trying to maintain a blog

Source Code - Root / controllers / listController.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*****************************************
*   List Controller
*****************************************
*   Author:  mikael.lofjard@gmail.com
*   Website: http://lofjard.se
*   License: MIT License
****************************************/
  
var ListController = (function () {
  
  var querystring = require('querystring');
  
  var marked = require('../forked/marked');
  
  var viewManager = require('../viewManager').ViewManager;
  var responseManager = require('../responseManager').ResponseManager;
  var env = require('../environmentManager').EnvironmentManager;
  var misc = require('../misc').Misc;
  
  var db = null;
  
  return {
  
    init : function (dbInit) {
      db = dbInit;
    },
  
    page : function (request, response) {
      //var key = url.parse(request.url, true).query.key;
      var key = request.params.key;
  
      var startKey = 'A';
      var pageSize = 6; // 5 for show and 1 for reference
      var desc = true;
      var firstPage = true;
  
      if (key) {
        var prefix = key.substring(0, 1);
        desc = (prefix != 'p');
        startKey = key.substring(1);
        firstPage = false;
      }
  
      env.info("Blog Post Controller: Page request recieved");
      env.info(" - Current page key: " + key);
  
      var nextPageKey = null;
      var prevPageKey = null;
  
      db.view('posts/byDateTime', {
        descending : desc,
        limit : (desc ? pageSize : pageSize + 1),
        startkey : startKey
      }, function (err, doc) {
        if (err) {
          env.info("CouchDB: DB Read error");
          //staticFileController.error(request, response, 404);
          return;
        }
  
        db.view('comments/countByReadableKey', { group: true }, function (comerr, comdoc) {
          if (comerr) {
            env.info("CouchDB: DB Read error");
            //staticFileController.error(request, response, 404);
            return;
          }
  
          var comments = {};
          for (var ci in comdoc) {
            comments[comdoc[ci].key] = comdoc[ci].value;
          }
  
          if (!desc) {
            if (doc.length < pageSize + 1) {
              firstPage = true;
            } else {
              doc.pop();
            }
  
            // reverse doc if we came from a "prev page" click
            // since we then selected with descending: false;
            doc.reverse();
          }
  
          if (doc.length == pageSize) {
            nextPageKey = doc.pop().key;
            env.info(" - Next page key: " + nextPageKey);
          }
  
          if (doc.length > 0 && !firstPage) {
            prevPageKey = doc[0].key;
            env.info(" - Prev page key: " + prevPageKey);
          }
  
          for (var blogpost in doc) {
            doc[blogpost].value['readableDateTime'] = misc.prettyDate(doc[blogpost].value.dateTime);
  
            // apply syntax highlighting
            doc[blogpost].value.htmlContent = marked(doc[blogpost].value.htmlContent);
  
            // assign comment count
            commentCount = comments[doc[blogpost].value.readableKey];
            if (typeof(commentCount) == 'undefined') {
              doc[blogpost].value.commentCount = '0';
            } else {
              doc[blogpost].value.commentCount = commentCount;
            }
          }
  
          var postList = {
            posts : doc,
            olderPosts : (nextPageKey != null),
            nextPageKey : 'n' + nextPageKey,
            newerPosts : (prevPageKey != null),
            prevPageKey : 'p' + prevPageKey,
            renderPageNav : ((prevPageKey != null) || (nextPageKey != null))
          };
  
          // render view
          var responseData = viewManager.renderView(response, 'list', postList);
          responseManager.writeResponse(request, response, responseData);
          return;
        });
      });
    },
  
    archive : function (request, response) {
  
      var currentYear = new Date().getFullYear();
      var year = request.params.year;
      if (year == null) {
        year = currentYear;
      }
      year = Number(year);
  
      var startKey = year + '-12-31T23:59:59';
      var endKey = year + '-01-01T00:00:00';
        
      db.view('archive/byDateTime', {
        descending : true,
        startkey: startKey,
        endkey: endKey
      }, function (err, doc) {
        if (err) {
          env.info("CouchDB: DB Read error");
          env.info(JSON.stringify(err));
          staticFileController.error(request, response, 404);
          return;
        }
  
        //var now = new Date();
        var lastYear = -1;
        var lastMonth = -1;
        var lastDate = -1;
  
        var mi = -1;
        var di = -1;
  
        var archive = {
          year: year,
          previousYear: (year > 2011) ? (year - 1) : false,
          nextYear: (year < currentYear) ? (year + 1) : false,
          months : []
        };
        for (var i in doc) {
          //doc[i].value['readableDateTime'] = prettyDate(doc[i].value.dateTime);
  
          var date = new Date(doc[i].value.dateTime);
          var currentMonth = date.getMonth();
          var currentDate = date.getDate();
          var currentDay = date.getDay();
  
/*          if (currentYear != lastYear) {
            yi++;
            archive.years.push({
              year : currentYear + '',
              months : []
            });
            mi = -1;
          }*/
          if (currentMonth != lastMonth) {
            mi++;
            archive.months.push({
              year : year + '',
              name : misc.monthNames[currentMonth + 1],
              days : []
            });
            di = -1;
          }
          if (currentMonth != lastMonth || currentDate != lastDate) {
            di++;
            archive.months[mi].days.push({
              day : currentDate,
              name : misc.dayNames[currentDay],
              posts : []
            });
          }
  
          env.info(' - adding month ' + mi + ' day ' + di);
          // add post to correct position
          archive.months[mi].days[di].posts.push(doc[i].value);
  
          lastMonth = currentMonth;
          lastDate = currentDate;
        }
  
        // this is what archive should look like
        //testarchive = { years: [ { year: '2011', months: [ { year: '2011', name: 'November', days: [ {day: 13, name: "Sunday", posts: [ {a:"a"}, {a:"b"} ] } ] } ] } ] };
  
        // render view
        var responseData = viewManager.renderView(response, 'archive', archive);
        responseManager.writeResponse(request, response, responseData);
        return;
      });
    },
  
    tags : function (request, response) {
      db.view('tags/publishedByTag', {
        group : true
      }, function (err, doc) {
        if (err) {
          env.info("CouchDB: DB Read error");
          staticFileController.error(request, response, 404);
          return;
        }
  
        var model = {};
        model.tags = new Array();
  
        var minSize = 12;
        var maxSize = 44;
  
        var maxCount = 0;
        var minCount = 999999;
  
        for (var i in doc) {
          if (doc[i].value > maxCount)
            maxCount = doc[i].value;
          if (doc[i].value < minCount)
            minCount = doc[i].value;
        }
  
        var countDiff = Math.log(maxCount) - Math.log(minCount);
        var sizeDiff = maxSize - minSize;
        if (countDiff == 0)
          countDiff = 1; // no divide by zero
  
        for (var i in doc) {
          var weight = (Math.log(doc[i].value) - Math.log(minCount)) / countDiff;
          var size = minSize + Math.round(sizeDiff * weight);
          model.tags.push({
            tag : doc[i].key,
            size : size,
            count : doc[i].value
          });
        }
  
        var responseData = viewManager.renderView(response, 'tags', model);
        responseManager.writeResponse(request, response, responseData);
        return;
      });
    },
  
    tag : function (request, response) {
      var tag = request.params.tag;
  
      db.view('posts/byTagAndDateTime', {
        startkey : [tag, 1],
        endkey : [tag],
        descending : true
      }, function (err, doc) {
        if (err) {
          env.info("CouchDB: DB Read error");
          staticFileController.error(request, response, 404);
          return;
        }
  
        var model = {};
        model.posts = new Array();
  
        for (var i in doc) {
          var post = doc[i].value;
          post.readableDateTime = misc.prettyDate(doc[i].key[2]);
  
          model.posts.push(post);
        }
  
        model.tag = tag;
        var responseData = viewManager.renderView(response, 'tag', model);
        responseManager.writeResponse(request, response, responseData);
        return;
      });
    }
  };
  
}());
  
typeof(exports) != 'undefined' ? exports.ListController = ListController : null;