Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
cjoudrey committed Mar 7, 2011
0 parents commit a38fdcf
Show file tree
Hide file tree
Showing 16 changed files with 402 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
.monitor
lib
Empty file added .gitmodules
Empty file.
Empty file added CHANGELOG.md
Empty file.
Empty file added Cakefile
Empty file.
19 changes: 19 additions & 0 deletions LICENSE
@@ -0,0 +1,19 @@
Copyright (C) 2011 by Christian Joudrey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Empty file added README.md
Empty file.
4 changes: 4 additions & 0 deletions TODO.md
@@ -0,0 +1,4 @@
# TODO

- Auto-rebuild cache when an article is changed or added. Use `find` from nodemon
- Add RSS.feed
24 changes: 24 additions & 0 deletions package.json
@@ -0,0 +1,24 @@
{
"name": "typhoon",
"version": "0.0.1",
"description": "Minimalist blog engine",
"keywords": ["blog"],
"homepage": "http://github.com/cjoudrey/typhoon",
"author": "Christian Joudrey <cmallette@gmail.com> (http://twitter.com/cjoudrey)",
"repository": {
"type":"git",
"url":"http://github.com/ajaxorg/ace.git"
},
"dependencies": {
"connect": ">= 1.0.0",
"hamljs": ">= 0.4.5",
"node-markdown": ">= 0.1.0"
},
"devDependencies": {
"coffee-script": ">= 1.0.1"
},
"main": "lib/index.js",
"engines": {
"node": ">= 0.4.0 < 0.5.0"
}
}
5 changes: 5 additions & 0 deletions spec/fixtures/articles/test.txt
@@ -0,0 +1,5 @@
title: Test
date: 2010/01/30
custom: 1234

# test
4 changes: 4 additions & 0 deletions spec/fixtures/articles/test2.txt
@@ -0,0 +1,4 @@
title: Test 2
date: 2010/02/30

# test
2 changes: 2 additions & 0 deletions spec/fixtures/layout.haml
@@ -0,0 +1,2 @@
= testglobal
= body
2 changes: 2 additions & 0 deletions spec/fixtures/test.haml
@@ -0,0 +1,2 @@
= testglobal
= testlocal
1 change: 1 addition & 0 deletions src/index.coffee
@@ -0,0 +1 @@
module.exports = require("./typhoon")
223 changes: 223 additions & 0 deletions src/typhoon/article.coffee
@@ -0,0 +1,223 @@
fs = require('fs')
markdown = require('node-markdown').Markdown
View = require('./view').View

###
Init app and setup routes
###

app = (configs) ->
configs ?= {}

exports.Article.baseUrl configs.baseUrl
exports.cache.build configs.articlesDir, configs.encoding || "utf8"
View.templatesDir configs.templatesDir

View.globals
site_title: 'test'
site_url: 'yeah'
title: 'yahh'

articleView = new View '/article.haml', configs.encoding || "utf8"
listView = new View '/list.haml', configs.encoding || "utf8"
feedView = new View '/feed.haml', configs.encoding || "utf8"

configs.perPage ?= 10

return (app) ->
app.get /^(?:(?:\/([0-9]{4})(?:\/([0-9]{2})(?:\/([0-9]{2}))?)?)?)(?:\/?page\/([0-9]+))?\/?$/, (req, res, next) ->
if !exports.cache.ready() then throw new Error(503)

locals =
articles: []

[filterYear, filterMonth, filterDay, filterPage] = req.params

filterMonth = if !filterMonth then 0 else filterMonth - 1
filterDay ?= 1
filterPage ?= 1

if req.params[0]
startDate = new Date Date.UTC(filterYear, filterMonth, filterDay, 0, 0, 0)
endDate = new Date Date.UTC(filterYear, filterMonth, filterDay, 0, 0, 0)

if req.params[2]
endDate.setUTCDate endDate.getUTCDate() + 1
else if req.params[1]
endDate.setUTCMonth endDate.getUTCMonth() + 1
else
endDate.setUTCFullYear endDate.getUTCFullYear() + 1

endDate.setUTCSeconds -1

for entry in exports.cache.getListing filterPage, configs.perPage, startDate ? null, endDate ? null
locals.articles.push(exports.cache.getArticle entry.permalink)

listView.render res, locals, (err) ->
if err then throw new Error(500)

app.get /^(\/([0-9]{4})\/([0-9]{2})\/([0-9]{2})\/(.*)\/?)$/, (req, res, next) ->
if !exports.cache.ready() then throw new Error(503)

article = exports.cache.getArticle req.params[0]
if !article then throw new Error(404)

locals =
article: article

articleView.render res, locals, (err) ->
if err then throw new Error(500)

app.get '/feed.xml', (req, res, next) ->
if !exports.cache.ready() then throw new Error(503)
locals =
articles: exports.cache.getListing 1, 25

feedView.partial locals, (err, data) ->
if err then throw new Error(500)
res.writeHead 200, {"content-type": "text/xml"}
res.end data

###
Cache object used by the Article object
###

class Cache
@cache = null
getListing: (page = 1, perPage = 10, startDate = null, endDate = null) ->
if !@ready() then return []
if page < 1 then return []
offset = (page * perPage) - perPage
articles = []
for entry, i in @cache.listing
if i < offset then continue
if endDate && entry.date > endDate then continue
if startDate && entry.date < startDate then break
articles.push entry
if articles.length == perPage then break
return articles
getArticle: (permalink) ->
if !@ready() then return null
return @cache.articles[permalink]
putArticle: (article) ->
@cache.articles[article.permalink true] = article
build: (articlesDir, encoding) ->
cache =
articles: {}
listing: []
that = this
fs.readdir articlesDir, (err, files) ->
if err then throw new Error(503)
loadNext = ->
file = files.shift()
if file
articleFile = articlesDir + '/' + file
exports.Article.fromFile articleFile, encoding, (err, article) ->
if !err
permalink = article.permalink true
cache.articles[permalink] = article
cache.listing.push permalink: permalink, date: article.date()
loadNext()
else
cache.listing.sort (a, b) ->
if a.date < b.date
return 1
else if a.date > b.date
return -1
else
return 0
that.cache = cache
loadNext()
ready: -> return !!@cache

###
Article object
###

class Article
constructor: (data) ->
@body_md = null
@_meta = {}

data = data.replace(/\r\n/g, "\n")
meta = data.split(/\n\n/, 1).toString()

@_body = data.substring meta.length + 2

# @todo Replace with haml.js when the string issue is fixed
while match = meta.match /([a-z0-9]+)\:\s*(.*)\s*\n?/i
metaKey = match[1].toLowerCase()
@_meta[metaKey] = match[2]
meta = meta.substring match[0].length

@_baseUrl: null
@baseUrl: ->
Article._baseUrl = arguments[0] if arguments.length > 0
return Article._baseUrl

@fromFile: (file, encoding, callback) ->
fs.readFile file, encoding, (err, data) ->
if err then return callback err
article = new Article data
callback null, article

meta: (key = null) -> return if key then @_meta[key] else @_meta

title: -> return @meta 'title'

tags: -> return null # @todo

date: (raw) ->
date = @meta('date')
if raw
return date
else
[year, month, day] = date.split('/')
return new Date Date.UTC(year, month - 1, day)

@slugify: (str) ->
# Trim spaces
str = str.replace /^\s+|\s+$/g, ''

# Lowercase
str = str.toLowerCase()

# Remove accents by swapping
from = 'àáäâèéëêìíïîòóöôùúüûñç·/_,:;'
to = 'aaaaeeeeiiiioooouuuunc------'

for char, i in from
str = str.replace new RegExp(char, 'g'), to.charAt i

# Remove uncatched invalid chars
str = str.replace /[^a-z0-9\s\-]/g, ''

# Collapse spaces and replace with dashes
str = str.replace /\s+/g, '-'

# Collapse dashes
str = str.replace /-+/g, '-'

return str

slug: -> return @meta('slug') || Article.slugify @title()

body: (raw) -> return if raw then @_body else @body_md || @body_md = markdown @_body

permalink: (relative = false)->
pad = (n) ->
if n < 10 then '0' + n else n

date = @date()
base = if relative then '' else Article.baseUrl()

return base + '/' + date.getUTCFullYear() + '/' + pad(date.getUTCMonth() + 1) + '/' + pad(date.getUTCDate()) + '/' + @slug()

###
Module Exports
###

exports.Cache = Cache
exports.Article = Article
exports.cache = new Cache()
exports.app = app
41 changes: 41 additions & 0 deletions src/typhoon/index.coffee
@@ -0,0 +1,41 @@
###
connect = require('connect')
server = connect.createServer()
server.use connect.logger()
server.use connect.router require('./article').app()
server.use connect.static '/mnt/twonky/web/node-tinyblog_working/public'
server.use (req, res) ->
res.writeHead 200
res.end "test test"
server.listen 8080
###

connect = require 'connect'

listen = (configs) ->
configs ?= {}

server = connect.createServer()
if configs.env == 'dev'
server.use connect.logger()
server.use connect.profiler()
server.use connect.responseTime()

server.use connect.favicon(configs.favicon) if configs.favicon
server.use connect.static(configs.staticDir) if configs.staticDir
server.use connect.router require('./article').app(configs)
server.use connect.errorHandler({ stack: true, dump: true })

server.listen configs.port || 8080, configs.host || '127.0.0.1'

###
Module Exports
###

exports.listen = listen

0 comments on commit a38fdcf

Please sign in to comment.