Explorar el Código

Some major code drop

Johannes Zellner hace 11 años
padre
commit
9d6f2796e2
Se han modificado 25 ficheros con 1255 adiciones y 616 borrados
  1. 1 0
      .dockerignore
  2. 1 1
      .gitignore
  3. 7 0
      .jshintrc
  4. 4 4
      Dockerfile
  5. 28 8
      app.js
  6. 0 25
      bower.json
  7. 179 0
      frontend/index.html
  8. 194 0
      frontend/js/core.js
  9. 39 0
      frontend/js/filter.js
  10. 90 0
      frontend/js/main.js
  11. 48 0
      frontend/js/settings.js
  12. 88 0
      frontend/js/thing.js
  13. 59 0
      frontend/scss/index.scss
  14. 49 0
      frontend/scss/settings.scss
  15. 2 40
      frontend/scss/spinner.scss
  16. 71 0
      gulpfile.js
  17. 25 0
      package.json
  18. 0 162
      public/index.html
  19. 0 242
      public/index.js
  20. 7 0
      src/config.js
  21. 41 134
      src/routes.js
  22. 39 0
      src/settings.js
  23. 44 0
      src/tags.js
  24. 211 0
      src/things.js
  25. 28 0
      things.json

+ 1 - 0
.dockerignore

@@ -3,3 +3,4 @@
 .dockerignore
 node_modules
 bower_components
+public

+ 1 - 1
.gitignore

@@ -1,2 +1,2 @@
 node_modules/
-bower_components/
+public/

+ 7 - 0
.jshintrc

@@ -0,0 +1,7 @@
+{
+	"node": true,
+	"browser": true,
+	"unused": true,
+	"globalstrict": true,
+	"predef": [ "angular", "$" ]
+}

+ 4 - 4
Dockerfile

@@ -7,13 +7,13 @@ RUN mkdir -p /app/code
 WORKDIR /app/code
 
 ADD src/ /app/code/src/
-ADD public/ /app/code/public/
-ADD bower.json package.json app.js start.sh /app/code/
+ADD frontend/ /app/code/frontend/
+ADD gulpfile.js package.json app.js start.sh /app/code/
 
 ENV PATH /usr/local/node-4.2.1/bin:$PATH
 
 RUN npm install
-RUN npm install -g bower
-RUN bower install --allow-root
+RUN npm install -g gulp-cli
+RUN gulp default
 
 CMD [ "/app/code/start.sh" ]

+ 28 - 8
app.js

@@ -6,7 +6,9 @@ require('supererror')({ splatchError: true });
 
 var express = require('express'),
     json = require('body-parser').json,
+    cors = require('cors'),
     routes = require('./src/routes.js'),
+    things = require('./src/things.js'),
     lastmile = require('connect-lastmile'),
     serveStatic = require('serve-static');
 
@@ -26,23 +28,41 @@ router.get ('/api/tags', routes.getTags);
 router.post('/api/settings', routes.settingsSave);
 router.get ('/api/settings', routes.settingsGet);
 
+router.get ('/api/export', routes.exportThings);
+
 app
+    .use(cors())
     .use(json({ strict: true })) // only parse objects and arrays
     .use(serveStatic(__dirname + '/public'))
     .use(serveStatic(__dirname + '/bower_components'))
     .use(router)
     .use(lastmile());
 
+function exit(error) {
+    if (error) console.error(error);
+    process.exit(error ? 1 : 0);
+}
+
+function welcomeIfNeeded(callback) {
+    things.getAll({}, function (error, result) {
+        if (error) return callback(error);
+        if (result.length > 0) return callback(null);
+
+        things.imp(require('./things.json'), callback);
+    });
+}
+
 routes.init(function (error) {
-    if (error) {
-        console.error(error);
-        process.exit(1);
-    }
+    if (error) exit(error);
+
+    welcomeIfNeeded(function (error) {
+        if (error) exit(error);
 
-    var server = app.listen(3000, function () {
-        var host = server.address().address;
-        var port = server.address().port;
+        var server = app.listen(3000, function () {
+            var host = server.address().address;
+            var port = server.address().port;
 
-        console.log('App listening at http://%s:%s', host, port);
+            console.log('App listening at http://%s:%s', host, port);
+        });
     });
 });

+ 0 - 25
bower.json

@@ -1,25 +0,0 @@
-{
-  "name": "holyguacamoly",
-  "description": "",
-  "main": "index.js",
-  "authors": [
-    "Johannes Zellner <johannes@nebulon.de>"
-  ],
-  "license": "ISC",
-  "moduleType": [],
-  "homepage": "",
-  "ignore": [
-    "**/.*",
-    "node_modules",
-    "bower_components",
-    "test",
-    "tests"
-  ],
-  "dependencies": {
-    "angular": "~1.4.8",
-    "bootstrap": "~3.3.6",
-    "bootstrap-material-design": "~0.5.2",
-    "angular-marked": "~1.0.1",
-    "mdi": "~1.3.41"
-  }
-}

+ 179 - 0
frontend/index.html

@@ -0,0 +1,179 @@
+<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8" />
+    <title></title>
+
+    <link rel="icon" type="image/png" href="/favicon.png" />
+
+    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
+
+    <link rel="stylesheet" href="3rdparty/css/font-awesome.min.css"/>
+    <link rel="stylesheet" href="3rdparty/css/bootstrap.min.css"/>
+    <link rel="stylesheet" href="3rdparty/css/material.min.css"/>
+    <link rel="stylesheet" href="3rdparty/css/ripples.min.css"/>
+    <link rel="stylesheet" href="3rdparty/css/roboto.min.css"/>
+
+    <link rel="stylesheet" href="index.min.css"/>
+
+    <script type="text/javascript" src="3rdparty/jquery.min.js"></script>
+    <script type="text/javascript" src="3rdparty/js/bootstrap.min.js"></script>
+    <script type="text/javascript" src="3rdparty/js/material.min.js"></script>
+    <script type="text/javascript" src="3rdparty/js/ripples.min.js"></script>
+
+  </head>
+  <body id="application">
+
+    <div class="modal fade" id="modalAdd">
+      <div class="modal-dialog">
+        <div class="modal-content">
+          <div class="modal-header">
+            <button type="button" class="close">×</button>
+            <h4 class="modal-title">Add something</h4>
+          </div>
+          <div class="modal-body">
+            <textarea class="form-control" id="inputContent" rows="5" v-model="content" autofocus></textarea>
+          </div>
+          <div class="modal-footer">
+            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
+            <button type="button" class="btn btn-success" v-on:click="save">Save</button>
+          </div>
+        </div>
+      </div>
+    </div>
+
+    <div class="modal fade" id="modalEdit">
+      <div class="modal-dialog">
+        <div class="modal-content">
+          <div class="modal-header">
+            <button type="button" class="close">×</button>
+            <h4 class="modal-title">Edit</h4>
+          </div>
+          <div class="modal-body">
+            <textarea class="form-control" id="inputContent" rows="5" v-model="thing.content" autofocus></textarea>
+          </div>
+          <div class="modal-footer">
+            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
+            <button type="button" class="btn btn-success" v-on:click="save">Save</button>
+          </div>
+        </div>
+      </div>
+    </div>
+
+    <div class="modal fade" id="modalDel">
+      <div class="modal-dialog">
+        <div class="modal-content">
+          <div class="modal-header">
+            <h4 class="modal-title">Really Delete this Thing?</h4>
+          </div>
+          <div class="modal-footer">
+            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
+            <button type="button" class="btn btn-danger" v-on:click="del">Delete</button>
+          </div>
+        </div>
+      </div>
+    </div>
+
+    <div class="settings" id="settings">
+      <div class="backdrop hide" v-on:click="toggleSettings" v-bind:class="{ 'open': open }"></div>
+      <div class="action">
+        <button class="btn btn-default btn-fab" v-on:click="toggleSettings"><i class="fa fa-cog"></i></button>
+      </div>
+      <div class="container" v-bind:class="{ 'open': open }">
+        <div class="row">
+          <div class="col-md-12">
+            <h4>Interface</h4>
+          </div>
+        </div>
+        <div class="row">
+          <form class="form-horizontal">
+            <div class="form-group">
+              <label htmlFor="inputTitle" class="col-sm-4 control-label">Title</label>
+              <div class="col-sm-7">
+                <input type="text" class="form-control" id="inputTitle" v-model="settings.title" placeholder="Title" />
+              </div>
+            </div>
+            <div class="form-group">
+              <label htmlFor="inputBackgroundImage" class="col-sm-4 control-label">Background</label>
+              <div class="col-sm-7">
+                <input type="text" class="form-control" id="inputBackgroundImage" v-model="settings.backgroundUrl" placeholder="url" />
+              </div>
+            </div>
+          </form>
+        </div>
+        <div class="row">
+          <div class="col-md-offset-1 col-md-5">
+            <button class="btn btn-default" v-on:click="toggleSettings">Cancel</button>
+          </div>
+          <div class="col-md-5">
+            <button class="btn btn-success pull-right" v-on:click="saveSettings">Save</button>
+          </div>
+        </div>
+        <br/>
+        <div class="row">
+          <div class="col-md-12">
+            <h4>Content</h4>
+          </div>
+        </div>
+        <div class="row">
+          <div class="col-md-offset-1 col-md-10">
+            <button class="btn btn-primary pull-right" v-on:click="exportThings">Export</button>
+          </div>
+        </div>
+      </div>
+    </div>
+
+    <div class="container main">
+      <div class="row">
+        <div class="col-md-2 col-md-offset-5">
+            <button class="btn btn-raised btn-block btn-success" v-on:click="showThingAdd">Add</button>
+        </div>
+      </div>
+      <div class="row">
+        <div class="col-md-6 col-md-offset-3">
+          <div class="form-group has-success">
+            <label class="control-label" for="inputFilter">Search</label>
+            <input class="form-control" id="inputFilter" type="text" v-model="search" v-on:keyup.enter="doSearch"/>
+          </div>
+        </div>
+      </div>
+      <div class="row">
+        <div class="col-md-2 tags">
+          <div v-show="!busyTags">
+            <h5>Tags</h5>
+            <div v-for="tag in tags | orderBy 'usage' -1">
+              <a href="{{'/#search?#' + tag.name}}" v-on:click="tagSearch(tag)" transition="present">#{{ tag.name }}</a>
+            </div>
+            <br/>
+          </div>
+          <div v-show="busyTags">
+            <br/>
+            <br/>
+            <br/>
+            <center><i class="spinner"></i></center>
+          </div>
+        </div>
+        <div class="col-md-8">
+          <div v-show="!busyThings">
+            <div class="well well-sm thing" v-for="thing in things">
+                <div class="col-md-12 thing-title-date">
+                  {{ thing.createdAt | prettyDateOffset }}
+                  <button class="btn btn-xs btn-default" v-on:click="showThingDel(thing)">delete</button>
+                  <button class="btn btn-xs btn-default" v-on:click="showThingEdit(thing)">edit</button>
+              </div>
+              <div class="content">{{{ thing.richContent | markdown }}}</div>
+            </div>
+          </div>
+          <div v-show="busyThings">
+            <br/>
+            <br/>
+            <br/>
+            <center><i class="spinner"></i></center>
+          </div>
+        </div>
+      </div>
+    </div>
+
+    <script src="bundle.js"></script>
+  </body>
+</html>

+ 194 - 0
frontend/js/core.js

@@ -0,0 +1,194 @@
+var superagent = require('superagent');
+
+function guid() {
+    function s4() {
+        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
+    }
+
+    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
+}
+
+function Thing(id, createdAt, tags, content, richContent) {
+    this.id = id;
+    this.createdAt = createdAt || 0;
+    this.tags = tags || [];
+    this.content = content;
+    this.richContent = richContent;
+}
+
+function Things(server) {
+    this._server = server;
+    this._addCallbacks = [];
+    this._editCallbacks = [];
+    this._delCallbacks = [];
+    this.data = [];
+    this._operation = '';
+}
+
+Things.prototype.get = function (filter, callback) {
+    var that = this;
+    var url = this._server + '/api/things';
+    var operation = guid();
+
+    this._operation = operation;
+
+    if (filter) url += '?filter=' + encodeURIComponent(filter);
+
+    superagent.get(url).end(function (error, result) {
+        // ignore this if we moved on
+        if (that._operation !== operation) {
+            console.log('ignore this call');
+            return;
+        }
+
+        if (error) return callback(error);
+        if (result.status !== 200) return callback(new Error('Failed: ' + result.status + '. ' + result.text));
+
+        that.data = result.body.things.map(function (thing) {
+            return new Thing(thing._id, new Date(thing.createdAt).getTime(), thing.tags, thing.content, thing.richContent);
+        });
+
+        callback(null, that.data);
+    });
+};
+
+Things.prototype.add = function (content, callback) {
+    var that = this;
+    var url = this._server + '/api/things';
+
+    superagent.post(url).send({ content: content }).end(function (error, result) {
+        if (error) return callback(error);
+        if (result.status !== 201) return callback(new Error('Failed: ' + result.status + '. ' + result.text));
+
+        that._addCallbacks.forEach(function (callback) {
+            setTimeout(callback, 0);
+        });
+
+        callback(null);
+    });
+};
+
+Things.prototype.edit = function (thing, callback) {
+    var that = this;
+    var url = this._server + '/api/things/' + thing.id;
+
+    superagent.put(url).send({ content: thing.content }).end(function (error, result) {
+        if (error) return callback(error);
+        if (result.status !== 201) return callback(new Error('Failed: ' + result.status + '. ' + result.text));
+
+        that._editCallbacks.forEach(function (callback) {
+            setTimeout(callback, 0);
+        });
+
+        callback(null);
+    });
+};
+
+Things.prototype.del = function (thing, callback) {
+    var that = this;
+    var url = this._server + '/api/things/' + thing.id;
+
+    superagent.del(url).end(function (error, result) {
+        if (error) return callback(error);
+        if (result.status !== 200) return callback(new Error('Failed: ' + result.status + '. ' + result.text));
+
+        that._delCallbacks.forEach(function (callback) {
+            setTimeout(callback, 0);
+        });
+
+        callback(null);
+    });
+};
+
+Things.prototype.onAdded = function (callback) {
+    this._addCallbacks.push(callback);
+};
+
+Things.prototype.onEdited = function (callback) {
+    this._editCallbacks.push(callback);
+};
+
+Things.prototype.onDeleted = function (callback) {
+    this._delCallbacks.push(callback);
+};
+
+Things.prototype.export = function () {
+    window.location.href = this._server + '/api/export';
+};
+
+function Settings(server) {
+    this._server = server;
+    this._changeCallbacks = [];
+    this.data = {
+        title: '',
+        backgroundUrl: ''
+    };
+}
+
+Settings.prototype.save = function (callback) {
+    var url = this._server + '/api/settings';
+
+    superagent.post(url).send({ settings: this.data }).end(function (error, result) {
+        if (error) return callback(error);
+        if (result.status !== 202) return callback(new Error('Failed: ' + result.status + '. ' + result.text));
+
+        callback(null);
+    });
+};
+
+Settings.prototype.get = function (callback) {
+    var that = this;
+    var url = this._server + '/api/settings';
+
+    superagent.get(url).end(function (error, result) {
+        if (error) return callback(error);
+        if (result.status !== 200) return callback(new Error('Failed: ' + result.status + '. ' + result.text));
+
+        that.set(result.body.settings);
+
+        callback(null, result.body.settings);
+    });
+};
+
+Settings.prototype.set = function (data) {
+    var that = this;
+
+    this.data.title = data.title;
+    this.data.backgroundUrl = data.backgroundUrl;
+
+    this._changeCallbacks.forEach(function (callback) {
+        setTimeout(callback.bind(null, that.data), 0);
+    });
+};
+
+Settings.prototype.onChanged = function (callback) {
+    this._changeCallbacks.push(callback);
+};
+
+function Tags(server) {
+    this._server = server;
+}
+
+Tags.prototype.get = function (callback) {
+    var url = this._server + '/api/tags';
+
+    superagent.get(url).end(function (error, result) {
+        if (error) return callback(error);
+        if (result.status !== 200) return callback(new Error('Failed: ' + result.status + '. ' + result.text));
+
+        callback(null, result.body.tags);
+    });
+};
+
+function Core() {
+    this._server = '';
+
+    this.settings = new Settings(this._server);
+    this.things = new Things(this._server);
+    this.tags = new Tags(this._server);
+}
+
+module.exports = {
+    Thing: Thing,
+    Core: new Core()
+};

+ 39 - 0
frontend/js/filter.js

@@ -0,0 +1,39 @@
+var Vue = require('vue'),
+    MarkdownIt = require('markdown-it'),
+    twemoji = require('twemoji');
+
+var md = MarkdownIt({
+    breaks: true,
+    linkify: true
+}).use(require('markdown-it-emoji'))
+.use(require('markdown-it-highlightjs'))
+.use(require('markdown-it-checkbox'));
+
+md.renderer.rules.emoji = function(token, idx) {
+  return twemoji.parse(token[idx].content);
+};
+
+Vue.filter('markdown', function (value) {
+    return md.render(value);
+});
+
+Vue.filter('prettyDateOffset', function (time) {
+    var date = new Date(time),
+        diff = (((new Date()).getTime() - date.getTime()) / 1000),
+        day_diff = Math.floor(diff / 86400);
+
+    if (isNaN(day_diff) || day_diff < 0)
+        return;
+
+    return day_diff === 0 && (
+            diff < 60 && 'just now' ||
+            diff < 120 && '1 minute ago' ||
+            diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago' ||
+            diff < 7200 && '1 hour ago' ||
+            diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago') ||
+        day_diff === 1 && 'Yesterday' ||
+        day_diff < 7 && day_diff + ' days ago' ||
+        day_diff < 31 && Math.ceil( day_diff / 7 ) + ' weeks ago' ||
+        day_diff < 365 && Math.round( day_diff / 30 ) +  ' months ago' ||
+                          Math.round( day_diff / 365 ) + ' years ago';
+});

+ 90 - 0
frontend/js/main.js

@@ -0,0 +1,90 @@
+var Vue = require('vue'),
+    Core = require('./core.js').Core,
+    Thing = require('./core.js').Thing;
+
+require('./filter.js');
+var vueThings = require('./thing.js');
+var vueSettings = require('./settings.js');
+
+// Vue.config.debug = true;
+
+var vue = new Vue({
+    el: '#application',
+    data: {
+        tags: [],
+        things: [],
+        busyThings: true,
+        busyTags: true,
+        search: ''
+    },
+    methods: {
+        showThingAdd: function () {
+            vueThings.add.open();
+        },
+        showThingEdit: function (thing) {
+            vueThings.edit.open(thing);
+        },
+        showThingDel: function (thing) {
+            vueThings.del.open(thing);
+        },
+        doSearch: function () {
+            window.location.href = '/#search?' + encodeURIComponent(this.search);
+        },
+        tagSearch: function (tag) {
+            window.location.href = '/#search?#' + encodeURIComponent(tag.name);
+        }
+    }
+});
+
+Core.settings.onChanged(function (data) {
+    window.document.title = data.title;
+    window.document.body.style.backgroundImage = 'url("' + data.backgroundUrl + '")';
+});
+
+function hashChangeHandler() {
+    var action = window.location.hash.split('?')[0];
+    var params = window.location.hash.indexOf('?') > 0 ? decodeURIComponent(window.location.hash.slice(window.location.hash.indexOf('?') + 1)) : null;
+
+    if (action === '#add') {
+        vue.showThingAdd();
+    } else if (action === '#settings') {
+        vueSettings.show();
+    } else if (action === '#search' && params !== null) {
+        vue.search = params;
+        refresh(vue.search);
+    } else {
+        refresh(vue.search);
+    }
+}
+
+window.addEventListener('hashchange', hashChangeHandler, false);
+
+function refresh(search) {
+    vue.busyThings = true;
+
+    Core.things.get(search || '', function (error) {
+        if (error) return console.error(error);
+
+        vue.things = Core.things.data;
+        vue.busyThings = false;
+    });
+}
+
+Core.things.onAdded(refresh);
+Core.things.onEdited(refresh);
+Core.things.onDeleted(refresh);
+
+// Main
+Core.settings.get(function (error) {
+    if (error) return console.error(error);
+
+    Core.tags.get(function (error, tags) {
+        if (error) return console.error(error);
+
+        vue.tags = tags;
+
+        vue.busyTags = false;
+
+        hashChangeHandler();
+    });
+});

+ 48 - 0
frontend/js/settings.js

@@ -0,0 +1,48 @@
+var Vue = require('vue'),
+    Core = require('./core.js').Core;
+
+var vueSettings = new Vue({
+    el: '#settings',
+    data: {
+        settings: Core.settings.data,
+        open: false
+    },
+    methods: {
+        show: function () {
+            this.open = true;
+
+            $('.backdrop').removeClass('hide');
+            $('.settings').addClass('open');
+        },
+        hide: function () {
+            this.open = false;
+
+            // wait for animation to finish
+            setTimeout(function () {
+                $('.backdrop').addClass('hide');
+                $('.settings').removeClass('open');
+            }, 500);
+        },
+        toggleSettings: function (event) {
+            if (this.open) this.hide();
+            else this.show();
+        },
+        saveSettings: function (event) {
+            var that = this;
+
+            Core.settings.set(this.settings);
+
+            Core.settings.save(function (error) {
+                if (error) return console.error(error);
+
+                vueSettings.hide();
+            });
+        },
+        exportThings: function (event) {
+            Core.things.export();
+            vueSettings.hide();
+        }
+    }
+});
+
+module.exports = vueSettings;

+ 88 - 0
frontend/js/thing.js

@@ -0,0 +1,88 @@
+var Vue = require('vue'),
+    Core = require('./core.js').Core;
+
+var vueThingAdd = new Vue({
+    el: '#modalAdd',
+    data: {
+        content: ''
+    },
+    created: function () {
+        $('#modalAdd').on('shown.bs.modal', function () {
+            $(this).find("[autofocus]:first").focus();
+        });
+    },
+    methods: {
+        close: function () {
+            $('#modalAdd').modal('hide');
+        },
+        open: function () {
+            this.content = '';
+            $('#modalAdd').modal('show');
+        },
+        save: function (event) {
+            Core.things.add(this.content, function (error) {
+                if (error) return console.error(error);
+
+                vueThingAdd.close();
+            });
+        }
+    }
+});
+
+var vueThingEdit = new Vue({
+    el: '#modalEdit',
+    data: {
+        thing: {}
+    },
+    created: function () {
+        $('#modalEdit').on('shown.bs.modal', function () {
+            $(this).find("[autofocus]:first").focus();
+        });
+    },
+    methods: {
+        close: function () {
+            $('#modalEdit').modal('hide');
+        },
+        open: function (thing) {
+            this.thing = thing;
+            $('#modalEdit').find("[autofocus]:first").focus();
+            $('#modalEdit').modal('show');
+        },
+        save: function (event) {
+            Core.things.edit(this.thing, function (error) {
+                if (error) return console.error(error);
+
+                vueThingEdit.close();
+            });
+        }
+    }
+});
+
+var vueThingDelete = new Vue({
+    el: '#modalDel',
+    data: {
+        thing: {}
+    },
+    methods: {
+        close: function () {
+            $('#modalDel').modal('hide');
+        },
+        open: function (thing) {
+            this.thing = thing;
+            $('#modalDel').modal('show');
+        },
+        del: function (event) {
+            Core.things.del(this.thing, function (error) {
+                if (error) return console.error(error);
+
+                vueThingDelete.close();
+            });
+        }
+    }
+});
+
+module.exports = {
+    add: vueThingAdd,
+    edit: vueThingEdit,
+    del: vueThingDelete
+};

+ 59 - 0
frontend/scss/index.scss

@@ -0,0 +1,59 @@
+
+body {
+    background-repeat: no-repeat;
+    background-position: right top;
+    background-attachment: fixed;
+    background-size: cover;
+}
+
+.main {
+    margin-top: 50px;
+}
+
+.filter {
+    width: 100%;
+}
+
+.well {
+    position: relative;
+}
+
+.thing-title-date {
+    font-size: 12px;
+    text-align: right;
+}
+
+.thing-title-date,.btn {
+    margin: 0;
+}
+
+.modal-content .modal-body {
+    padding-top: 0;
+}
+
+.content {
+    width: 100%;
+    overflow-x: auto;
+}
+
+@import 'settings';
+@import 'spinner';
+
+.present-transition {
+    transition: all .3s ease;
+    opacity: 1;
+    transform: scale(1);
+}
+
+.present-enter, .present-leave {
+    transform: scale(0.8);
+    opacity: 0;
+}
+
+.tags {
+    background-color: white;
+}
+
+.emoji {
+  height: 1.2em;
+}

+ 49 - 0
frontend/scss/settings.scss

@@ -0,0 +1,49 @@
+.settings {
+    width: 100%;
+    height: 100%;
+    position: fixed;
+    top: 0;
+    left: 0;
+    overflow: hidden;
+
+    &.open {
+        z-index: 1000;
+    }
+
+    .action {
+        display: inline-block;
+        position: absolute;
+        top: 20px;
+        right: 20px;
+    }
+
+    .container {
+        position: absolute;
+        top: 0;
+        width: 400px;
+        height: 100%;
+        right: -400px;
+        background-color: white;
+        transition: right 250ms;
+        box-shadow: 0 8px 17px 0 rgba(0,0,0,.2),0 6px 20px 0 rgba(0,0,0,.19);
+        z-index: 2000;
+
+        &.open {
+            right: 0;
+        }
+    }
+
+    .backdrop {
+        width: 100%;
+        height: 100%;
+        position: fixed;
+        top: 0;
+        left: 0;
+        transition: background-color 400ms;
+
+        &.open {
+            background-color: rgba(0,0,0,0.3);
+            opacity: 0.5;
+        }
+    }
+}

+ 2 - 40
public/index.css → frontend/scss/spinner.scss

@@ -1,44 +1,6 @@
-
-.main {
-    margin-top: 50px;
-}
-
-.filter {
-    width: 100%;
-}
-
-.well {
-    position: relative;
-}
-
-.thing-title-date {
-    font-size: 12px;
-    text-align: right;
-}
-
-.thing-title-date,.btn {
-    margin: 0;
-}
-
-.modal-content .modal-body {
-    padding-top: 0;
-}
-
-.content {
-    width: 100%;
-    overflow-x: auto;
-}
-
-.settings-action {
-    display: inline-block;
-    position: absolute;
-    top: 20px;
-    right: 20px;
-}
-
 .spinner {
     background-color: transparent;
-    border: 3px dashed #03a9f4;
+    border: 3px solid #03a9f4;
     border-radius: 50%;
     border-top-color: transparent;
     border-right-color: transparent;
@@ -58,4 +20,4 @@
     100% {
         transform:rotate(360deg)
     }
-}
+}

+ 71 - 0
gulpfile.js

@@ -0,0 +1,71 @@
+var gulp = require('gulp'),
+    source = require('vinyl-source-stream'),
+    sourcemaps = require('gulp-sourcemaps'),
+    sass = require('gulp-sass'),
+    minifycss = require('gulp-minify-css'),
+    autoprefixer = require('gulp-autoprefixer'),
+    del = require('del'),
+    rename = require('gulp-rename'),
+    browserify = require('browserify'),
+    buffer = require('vinyl-buffer'),
+    uglify = require('gulp-uglify'),
+    gutil = require('gulp-util');
+
+gulp.task('styles', function () {
+    return gulp.src('frontend/scss/index.scss')
+        .pipe(sourcemaps.init())
+        .pipe(sass({ includePaths: [] }).on('error', sass.logError))
+        .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
+        .pipe(rename({suffix: '.min'}))
+        .pipe(minifycss())
+        .pipe(sourcemaps.write())
+        .pipe(gulp.dest('public/'));
+});
+
+gulp.task('browserify', function () {
+    browserify({
+        entries: 'frontend/js/main.js',
+        debug: true
+    }).bundle()
+        .pipe(source('bundle.js'))
+        .pipe(buffer())
+        .pipe(sourcemaps.init({loadMaps: true}))
+        .pipe(sourcemaps.write('./'))
+        .pipe(gulp.dest('public/'));
+});
+
+gulp.task('html', function () {
+    return gulp.src('frontend/*.html').pipe(gulp.dest('public/'));
+});
+
+gulp.task('favicon', function () {
+    return gulp.src('logo.png')
+        .pipe(rename('favicon.png'))
+        .pipe(gulp.dest('public/'));
+});
+
+gulp.task('3rdparty', function () {
+    return gulp.src([
+        'node_modules/jquery/dist/*.min.js*',
+        'node_modules/bootstrap/dist/**/*.min.css*',
+        'node_modules/bootstrap/dist/**/*.min.js*',
+        'node_modules/bootstrap-material-design/dist/**/*.min.css*',
+        'node_modules/bootstrap-material-design/dist/**/*.min.js*',
+        'node_modules/font-awesome/**/font-awesome.min.css',
+        'node_modules/font-awesome/**/font-awesome.css.map',
+        'node_modules/font-awesome/**/*.+(otf|eot|svg|ttf|woff|woff2)'
+    ]).pipe(gulp.dest('public/3rdparty/'));
+});
+
+gulp.task('default', ['clean', 'html', 'favicon', 'styles', 'browserify', '3rdparty'], function() {});
+
+gulp.task('clean', function () {
+    del.sync(['public/']);
+});
+
+gulp.task('watch', ['default'], function () {
+    gulp.watch('frontend/scss/*.scss', ['styles']);
+    gulp.watch('frontend/**/*.js', ['browserify']);
+    gulp.watch('frontend/**/*.html', ['html']);
+    gulp.watch('frontend/img/*', ['images']);
+});

+ 25 - 0
package.json

@@ -16,10 +16,35 @@
     "async": "^1.5.0",
     "body-parser": "^1.14.1",
     "connect-lastmile": "0.0.13",
+    "cors": "^2.7.1",
     "express": "^4.13.3",
     "mongodb": "^2.0.49",
     "serve-static": "^1.10.0",
     "superagent": "^1.5.0",
     "supererror": "^0.7.1"
+  },
+  "devDependencies": {
+    "bootstrap": "^3.3.6",
+    "bootstrap-material-design": "^0.3.0",
+    "browserify": "^12.0.1",
+    "del": "^2.2.0",
+    "font-awesome": "^4.5.0",
+    "gulp": "^3.9.0",
+    "gulp-autoprefixer": "^3.1.0",
+    "gulp-minify-css": "^1.2.2",
+    "gulp-rename": "^1.2.2",
+    "gulp-sass": "^2.1.1",
+    "gulp-sourcemaps": "^1.6.0",
+    "gulp-uglify": "^1.5.1",
+    "gulp-util": "^3.0.7",
+    "jquery": "^2.1.4",
+    "markdown-it": "^5.0.2",
+    "markdown-it-checkbox": "^1.1.0",
+    "markdown-it-emoji": "^1.1.0",
+    "markdown-it-highlightjs": "^2.0.0",
+    "twemoji": "^1.4.1",
+    "vinyl-buffer": "^1.0.0",
+    "vinyl-source-stream": "^1.1.0",
+    "vue": "^1.0.11"
   }
 }

+ 0 - 162
public/index.html

@@ -1,162 +0,0 @@
-<html ng-app="app" ng-controller="MainController">
-<head>
-
-<title>{{settings.title}}</title>
-
-<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
-
-<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"/>
-
-<link rel="stylesheet" href="/bootstrap/dist/css/bootstrap.min.css"/>
-<link rel="stylesheet" href="/bootstrap-material-design/dist/css/bootstrap-material-design.min.css"/>
-<link rel="stylesheet" href="/bootstrap-material-design/dist/css/ripples.min.css"/>
-<link rel="stylesheet" href="/mdi/css/materialdesignicons.min.css" media="all" type="text/css"/>
-
-<script type="text/javascript" src="/jquery/dist/jquery.min.js"></script>
-<script type="text/javascript" src="/bootstrap/dist/js/bootstrap.min.js"></script>
-<script type="text/javascript" src="/bootstrap-material-design/dist/js/material.min.js"></script>
-<script type="text/javascript" src="/bootstrap-material-design/dist/js/ripples.min.js"></script>
-
-<script type="text/javascript" src="/angular/angular.min.js"></script>
-<script type="text/javascript" src="/marked/marked.min.js"></script>
-<script type="text/javascript" src="/angular-marked/dist/angular-marked.min.js"></script>
-
-<link rel="stylesheet" href="/index.css"/>
-<script type="text/javascript" src="/index.js"></script>
-
-</head>
-
-<body ng-style="{'background-image':'url(' + settings.backgroundUrl + ')'}">
-
-<div class="modal fade" id="modalAdd">
-  <div class="modal-dialog">
-    <div class="modal-content">
-      <div class="modal-header">
-        <button type="button" class="close">×</button>
-        <h4 class="modal-title">Add something</h4>
-      </div>
-      <div class="modal-body">
-        <textarea class="form-control" id="inputContent" rows="5" ng-model="addFormData.content" autofocus></textarea>
-      </div>
-      <div class="modal-footer">
-        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
-        <button type="button" class="btn btn-success" ng-click="addThing()">Save</button>
-      </div>
-    </div>
-  </div>
-</div>
-
-<div class="modal fade" id="modalEdit">
-  <div class="modal-dialog">
-    <div class="modal-content">
-      <div class="modal-header">
-        <button type="button" class="close">×</button>
-        <h4 class="modal-title">Edit</h4>
-      </div>
-      <div class="modal-body">
-        <textarea class="form-control" id="inputContent" rows="5" ng-model="editFormData.content" autofocus></textarea>
-      </div>
-      <div class="modal-footer">
-        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
-        <button type="button" class="btn btn-success" ng-click="editThing()">Save</button>
-      </div>
-    </div>
-  </div>
-</div>
-
-<div class="modal fade" id="modalDel">
-  <div class="modal-dialog">
-    <div class="modal-content">
-      <div class="modal-header">
-        <h4 class="modal-title">Really Delete this Thing?</h4>
-      </div>
-      <div class="modal-footer">
-        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
-        <button type="button" class="btn btn-danger" ng-click="delThing()">Delete</button>
-      </div>
-    </div>
-  </div>
-</div>
-
-<div class="modal fade" id="modalSettings">
-  <div class="modal-dialog">
-    <div class="modal-content">
-      <div class="modal-header">
-        <button type="button" class="close">×</button>
-        <h4 class="modal-title">Settings</h4>
-      </div>
-      <div class="modal-body">
-        <form class="form-horizontal">
-          <div class="form-group">
-            <label for="inputTitle" class="col-sm-2 control-label">Title</label>
-            <div class="col-sm-10">
-              <input type="text" class="form-control" id="inputTitle" ng-model="settings.title" placeholder="Title">
-            </div>
-          </div>
-          <div class="form-group">
-            <label for="inputBackgroundImage" class="col-sm-2 control-label">Background</label>
-            <div class="col-sm-10">
-              <input type="text" class="form-control" id="inputBackgroundImage" ng-model="settings.backgroundUrl" placeholder="url">
-            </div>
-          </div>
-        </form>
-      </div>
-      <div class="modal-footer">
-        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
-        <button type="button" class="btn btn-success" ng-click="saveSettings()">Save</button>
-      </div>
-    </div>
-  </div>
-</div>
-
-<div class="settings-action">
-  <button class="btn btn-default btn-fab" data-toggle="modal" data-target="#modalSettings"><i class="mdi mdi-dots-horizontal"></i></button>
-</div>
-
-
-<div class="container main">
-  <div class="row">
-    <div class="col-md-2 col-md-offset-5">
-        <button class="btn btn-raised btn-block btn-success" data-toggle="modal" data-target="#modalAdd">Add</button>
-    </div>
-  </div>
-  <div class="row">
-    <div class="col-md-6 col-md-offset-3">
-      <div class="form-group has-success">
-        <label class="control-label" for="inputFilter">Filter</label>
-        <input class="form-control" id="inputFilter" type="text" ng-model="filter" ng-enter="fetchThings()"/>
-      </div>
-    </div>
-  </div>
-  <div class="row">
-    <div class="col-md-2">
-      <div ng-hide="tagsBusy">
-        <button class="btn btn-primary btn-sm" ng-repeat="tag in tags" ng-click="addFilterTag(tag)">{{tag.name}}</button>
-      </div>
-      <div ng-show="tagsBusy">
-        <center><i class="spinner"></i></center>
-      </div>
-    </div>
-    <div class="col-md-8">
-      <div ng-hide="thingsBusy">
-        <div class="well well-sm thing" ng-repeat="thing in things">
-            <div class="col-md-12 thing-title-date">
-              {{thing.createdAt | prettyDateOffset}}
-              <button class="btn btn-xs btn-default" ng-click="showDelThing(thing._id)">delete</button>
-              <button class="btn btn-xs btn-default" ng-click="showEditThing(thing._id, thing.content)">edit</button>
-          </div>
-          <div class="content" marked="thing.richContent"></div>
-        </div>
-      </div>
-      <div ng-show="thingsBusy">
-        <br/>
-        <br/>
-        <br/>
-        <center><i class="spinner"></i></center>
-      </div>
-    </div>
-  </div>
-</div>
-
-</body>
-</html>

+ 0 - 242
public/index.js

@@ -1,242 +0,0 @@
-/* jslint browser:true */
-/* global angular */
-/* global $ */
-
-'use strict';
-
-var app = angular.module('app', [
-    'hc.marked'
-]);
-
-app.config(['markedProvider', function (markedProvider) {
-    markedProvider.setOptions({gfm: true});
-}]);
-
-app.controller('MainController', function ($scope, $http, $timeout, $document) {
-
-    $scope.things = [];
-    $scope.tags = [];
-    $scope.filter = '';
-    $scope.thingsBusy = true;
-    $scope.tagsBusy = true;
-
-    $scope.addFormData = {
-        busy: true,
-        content: ''
-    };
-
-    $scope.editFormData = {
-        busy: true,
-        id: '',
-        content: ''
-    };
-
-    $scope.delFormData = {
-        busy: true,
-        id: ''
-    };
-
-    $scope.settings = {
-        title: 'Holy Guacamoly',
-        backgroundUrl: ''
-    };
-
-    $scope.addFilterTag = function (tag) {
-        var hashed = '#' + tag.name;
-
-        if ($scope.filter.indexOf(hashed) === -1)  {
-            $scope.filter = $scope.filter + ' ' + hashed;
-        } else {
-            $scope.filter = $scope.filter.replace(hashed, '');
-        }
-
-        $scope.fetchThings();
-    };
-
-    $scope.showEditThing = function (id, content) {
-        $scope.editFormData.busy = false;
-        $scope.editFormData.id = id;
-        $scope.editFormData.content = content;
-
-        $('#modalEdit').modal('show');
-    };
-
-    $scope.showDelThing = function (id) {
-        $scope.delFormData.busy = false;
-        $scope.delFormData.id = id;
-
-        $('#modalDel').modal('show');
-    };
-
-    $scope.addThing = function () {
-        $scope.addFormData.busy = true;
-
-        $http.post('/api/things', { content: $scope.addFormData.content }, {}).then(function (result) {
-            $scope.addFormData.busy = false;
-            $scope.addFormData.content = '';
-
-            $('#modalAdd').modal('hide');
-
-            $scope.fetchThings();
-            $scope.fetchTags();
-        }, function (result) {
-            console.error('error:', result);
-            $scope.addFormData.busy = false;
-        });
-    };
-
-    $scope.editThing = function () {
-        $scope.editFormData.busy = true;
-
-        $http.put('/api/things/' + $scope.editFormData.id, { content: $scope.editFormData.content }, {}).then(function (result) {
-            $scope.editFormData.busy = false;
-            $scope.editFormData.id = '';
-            $scope.editFormData.content = '';
-
-            $('#modalEdit').modal('hide');
-
-            $scope.fetchThings();
-            $scope.fetchTags();
-        }, function (result) {
-            console.error('error:', result);
-            $scope.editFormData.busy = false;
-        });
-    };
-
-    $scope.delThing = function (id) {
-        $scope.delFormData.busy = true;
-
-        $http.delete('/api/things/' + $scope.delFormData.id, {}).then(function (result) {
-            $scope.delFormData.busy = false;
-            $scope.delFormData.id = '';
-
-            $('#modalDel').modal('hide');
-
-            $scope.fetchThings();
-        }, function (result) {
-            console.error('error:', result);
-            $scope.delFormData.busy = false;
-        });
-    };
-
-    $scope.fetchThings = function () {
-        $scope.thingsBusy = true;
-
-        var url = '/api/things';
-
-        if ($scope.filter) {
-            url += '?filter=' + encodeURIComponent($scope.filter);
-        }
-
-        $http.get(url, {}).then(function (result) {
-            angular.copy(result.data.things, $scope.things);
-            $scope.thingsBusy = false;
-        }, function (result) {
-            console.error('error:', result);
-            $scope.thingsBusy = false;
-        });
-    };
-
-    $scope.fetchTags = function () {
-        $scope.tagsBusy = true;
-
-        $http.get('/api/tags', {}).then(function (result) {
-            angular.copy(result.data.tags, $scope.tags);
-            $scope.tagsBusy = false;
-        }, function (result) {
-            console.error('error:', result);
-            $scope.tagsBusy = false;
-        });
-    };
-
-    $('#modalSettings').on('hidden.bs.modal', function () {
-        $scope.fetchSettings();
-    });
-
-    $scope.saveSettings = function () {
-        $http.post('/api/settings', { settings: $scope.settings }, {}).then(function (result) {
-            $('#modalSettings').modal('hide');
-        }, function (result) {
-            console.error('error:', result);
-        });
-    };
-
-    $scope.fetchSettings = function () {
-        $http.get('/api/settings', {}).then(function (result) {
-            angular.extend($scope.settings, result.data.settings);
-        }, function (result) {
-            console.error('error:', result);
-        });
-    };
-
-    $scope.fetchThings();
-    $scope.fetchTags();
-    $scope.fetchSettings();
-
-    $timeout(function () {
-        $.material.init();
-
-        $('#modalAdd').on('shown.bs.modal', function () {
-            $('#inputContent').focus();
-        });
-    });
-});
-
-app.filter('prettyDateOffset', function () {
-    // http://ejohn.org/files/pretty.js
-    return function prettyDateOffset(time){
-        var date = new Date(time),
-            diff = (((new Date()).getTime() - date.getTime()) / 1000),
-            day_diff = Math.floor(diff / 86400);
-
-        if (isNaN(day_diff) || day_diff < 0)
-            return;
-
-        return day_diff === 0 && (
-                diff < 60 && 'just now' ||
-                diff < 120 && '1 minute ago' ||
-                diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago' ||
-                diff < 7200 && '1 hour ago' ||
-                diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago') ||
-            day_diff === 1 && 'Yesterday' ||
-            day_diff < 7 && day_diff + ' days ago' ||
-            day_diff < 31 && Math.ceil( day_diff / 7 ) + ' weeks ago' ||
-            day_diff < 365 && Math.round( day_diff / 30 ) +  ' months ago' ||
-                              Math.round( day_diff / 365 ) + ' years ago';
-    };
-});
-
-app.filter('prettyDate', function () {
-    var months = new Array(12);
-    months[0] = 'January';
-    months[1] = 'February';
-    months[2] = 'March';
-    months[3] = 'April';
-    months[4] = 'May';
-    months[5] = 'June';
-    months[6] = 'July';
-    months[7] = 'August';
-    months[8] = 'September';
-    months[9] = 'October';
-    months[10] = 'November';
-    months[11] = 'December';
-
-    return function prettyDateOffset(time) {
-        var date = new Date(time);
-        return date.getUTCMonth() + 1 + ' ' + months[date.getDate()] + ' ' + date.getUTCFullYear();
-    };
-});
-
-app.directive('ngEnter', function () {
-    return function (scope, element, attrs) {
-        element.bind('keydown keypress', function (event) {
-            if(event.which === 13) {
-                scope.$apply(function (){
-                    scope.$eval(attrs.ngEnter);
-                });
-
-                event.preventDefault();
-            }
-        });
-    };
-});

+ 7 - 0
src/config.js

@@ -0,0 +1,7 @@
+/* jslint node:true */
+
+'use strict';
+
+exports = module.exports = {
+    databaseUrl: process.env.MONGODB_URL || 'mongodb://127.0.0.1:27017/guacamoly'
+};

+ 41 - 134
src/routes.js

@@ -2,10 +2,11 @@
 
 'use strict';
 
-var MongoClient = require('mongodb').MongoClient,
-    ObjectId = require('mongodb').ObjectID,
+var fs = require('fs'),
     async = require('async'),
-    superagent = require('superagent'),
+    things = require('./things.js'),
+    tags = require('./tags.js'),
+    settings = require('./settings.js'),
     HttpError = require('connect-lastmile').HttpError,
     HttpSuccess = require('connect-lastmile').HttpSuccess;
 
@@ -18,69 +19,16 @@ exports = module.exports = {
     del: del,
     getTags: getTags,
     settingsSave: settingsSave,
-    settingsGet: settingsGet
+    settingsGet: settingsGet,
+    exportThings: exportThings
 };
 
-var databaseUrl = process.env.MONGODB_URL || 'mongodb://127.0.0.1:27017/guacamoly';
-var g_db, g_things, g_tags, g_settings;
-
-function sanitize(data) {
-    data = data.replace(/##/g, data);
-    return data;
-}
-
-function facelift(data, tags, callback) {
-    var geturl = new RegExp('(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))', 'g');
-    var urls  = data.match(geturl);
-
-    async.each(urls, function (url, callback) {
-        superagent.get(url).end(function (error, result) {
-            if (error) return callback(null);
-
-            if (result.type === 'image/png') {
-                data = data.replace(url, '![' + url + '](' + url + ')');
-            }
-
-            callback(null);
-        });
-    }, function () {
-        tags.forEach(function (tag) {
-            data = data.replace(new RegExp('#' + tag, 'gmi'), '[#' + tag + '](#' + tag + ')');
-        });
-
-        callback(data);
-    });
-}
-
-function extractTags(data) {
-    var lines = data.split('\n');
-    var tags = [];
-
-    lines.forEach(function (line) {
-        var tmp = line.match(/\B#(\w+)/g);
-        if (tmp === null) return;
-
-        tags = tmp.map(function (tag) {
-            return tag.slice(1).toLowerCase();
-        }).concat(tags);
-    });
-
-    return tags;
-}
-
 function init(callback) {
-    MongoClient.connect(databaseUrl, function (error, db) {
-        if (error) return callback(error);
-
-        g_db = db;
-        g_things = db.collection('things');
-        g_tags = db.collection('tags');
-        g_settings = db.collection('settings');
-
-        g_things.createIndex({ content: 'text' });
-
-        callback(null);
-    });
+    async.series([
+        things.init,
+        tags.init,
+        settings.init
+    ], callback);
 }
 
 function getAll(req, res, next) {
@@ -92,112 +40,71 @@ function getAll(req, res, next) {
         };
     }
 
-    g_things.find(query).sort({ modifiedAt: -1 }).toArray(function (error, result) {
-        if (error || !result) return next(new HttpError(500, error));
-
-        async.each(result, function (thing, callback) {
-            var tags = extractTags(thing.content);
-            facelift(thing.content, tags, function (data) {
-                thing.richContent = data;
-
-                callback(null);
-            });
-        }, function () {
-            next(new HttpSuccess(200, { things: result }));
-        });
+    things.getAll(query, function (error, result) {
+        if (error) return next(new HttpError(500, error));
+        next(new HttpSuccess(200, { things: result }));
     });
 }
 
 function get(req, res, next) {
-    g_things.find({ _id: req.params.id }).toArray(function (error, result) {
-        if (error || !result) return next(new HttpError(500, error));
-
+    things.get(req.params.id, function (error, result) {
+        if (error) return next(new HttpError(500, error));
         next(new HttpSuccess(200, { thing: result }));
     });
 }
 
 function add(req, res, next) {
-    console.log('add', req.body);
-
-    var tags = extractTags(req.body.content);
-    var data = sanitize(req.body.content);
-
-    var doc = {
-        content: data,
-        createdAt: new Date(),
-        modifiedAt: new Date(),
-        tags: tags
-    };
-
-    async.eachSeries(tags, function (tag, callback) {
-        g_tags.update({ name: tag }, {
-            $inc: { usage: 1 },
-            $set: {
-                name: tag
-            }
-        }, { upsert:true }, callback);
-    }, function (error) {
-        if (error) return next(new HttpError(500, error));
+    if (typeof req.body.content !== 'string' || !req.body.content) return next(new HttpError(400, 'content must be a string'));
 
-        g_things.insert(doc, function (error, result) {
-            if (error || !result) return next(new HttpError(500, error));
-
-            next(new HttpSuccess(201, { id: result._id }));
-        });
+    things.add(req.body.content, function (error, id) {
+        if (error) return next(new HttpError(500, error));
+        next(new HttpSuccess(201, { id: id }));
     });
 }
 
 function put(req, res, next) {
-    console.log('put', req.body);
-
-    var tags = extractTags(req.body.content);
-    var data = sanitize(req.body.content);
-
-    async.eachSeries(tags, function (tag, callback) {
-        g_tags.update({ name: tag }, {
-            $inc: { usage: 1 },
-            $set: {
-                name: tag
-            }
-        }, { upsert:true }, callback);
-    }, function (error) {
+    things.put(req.params.id, req.body.content, function (error) {
         if (error) return next(new HttpError(500, error));
-
-        g_things.update({_id: new ObjectId(req.params.id) }, { $set: { content: data, tags: tags, modifiedAt: new Date() } }, function (error, result) {
-            if (error || !result) return next(new HttpError(500, error));
-
-            next(new HttpSuccess(201, { id: result._id }));
-        });
+        next(new HttpSuccess(201, { id: req.params.id }));
     });
 }
 
 function del(req, res, next) {
-    g_things.deleteOne({ _id: new ObjectId(req.params.id) }, function (error, result) {
-        if (error || !result) return next(new HttpError(500, error));
-
+    things.del(req.params.id, function (error) {
+        if (error) return next(new HttpError(500, error));
         next(new HttpSuccess(200, {}));
     });
 }
 
 function getTags(req, res, next) {
-    g_tags.find({}).sort({ createdAt: -1 }).toArray(function (error, result) {
-        if (error || !result) return next(new HttpError(500, error));
-
+    tags.get(function (error, result) {
+        if (error) return next(new HttpError(500, error));
         next(new HttpSuccess(200, { tags: result }));
     });
 }
 
 function settingsSave(req, res, next) {
-    g_settings.update({ type: 'frontend' }, { type: 'frontend', value: req.body.settings }, { upsert: true }, function (error) {
+    settings.put(req.body.settings, function (error) {
         if (error) return next(new HttpError(500, error));
         next(new HttpSuccess(202, {}));
     });
 }
 
 function settingsGet(req, res, next) {
-    g_settings.find({ type: 'frontend' }).toArray(function (error, result) {
-        console.log(error, result);
+    settings.get(function (error, result) {
         if (error) return next(new HttpError(500, error));
-        next(new HttpSuccess(200, { settings: result[0].value || {} }));
+        next(new HttpSuccess(200, { settings: result }));
+    });
+}
+
+function exportThings(req, res, next) {
+    things.exp(function (error, fileName) {
+        if (error) return next(new HttpError(500, error));
+
+        res.download(fileName, 'things.json', function (error) {
+            if (error) console.error(error);
+
+            fs.unlink(fileName);
+        });
     });
 }

+ 39 - 0
src/settings.js

@@ -0,0 +1,39 @@
+/* jslint node:true */
+
+'use strict';
+
+var MongoClient = require('mongodb').MongoClient,
+    config = require('./config.js');
+
+exports = module.exports = {
+    init: init,
+    get: get,
+    put: put
+};
+
+var g_db, g_settings;
+
+function init(callback) {
+    MongoClient.connect(config.databaseUrl, function (error, db) {
+        if (error) return callback(error);
+
+        g_db = db;
+        g_settings = db.collection('settings');
+
+        callback(null);
+    });
+}
+
+function put(settings, callback) {
+    g_settings.update({ type: 'frontend' }, { type: 'frontend', value: settings }, { upsert: true }, function (error) {
+        if (error) return callback(error);
+        callback(null);
+    });
+}
+
+function get(callback) {
+    g_settings.find({ type: 'frontend' }).toArray(function (error, result) {
+        if (error) return callback(error);
+        callback(null, result[0].value || {});
+    });
+}

+ 44 - 0
src/tags.js

@@ -0,0 +1,44 @@
+/* jslint node:true */
+
+'use strict';
+
+var MongoClient = require('mongodb').MongoClient,
+    config = require('./config.js');
+
+exports = module.exports = {
+    init: init,
+    get: get,
+    update: update
+};
+
+var g_db, g_tags;
+
+function init(callback) {
+    MongoClient.connect(config.databaseUrl, function (error, db) {
+        if (error) return callback(error);
+
+        g_db = db;
+        g_tags = db.collection('tags');
+
+        callback(null);
+    });
+}
+
+function get(callback) {
+    g_tags.find({}).sort({ createdAt: -1 }).toArray(function (error, result) {
+        if (error) return callback(error);
+        callback(null, result || []);
+    });
+}
+
+function update(name, callback) {
+    g_tags.update({ name: name }, {
+        $inc: { usage: 1 },
+        $set: {
+            name: name
+        }
+    }, { upsert:true }, function (error) {
+        if (error) return callback(error);
+        callback(null);
+    });
+}

+ 211 - 0
src/things.js

@@ -0,0 +1,211 @@
+/* jslint node:true */
+
+'use strict';
+
+var MongoClient = require('mongodb').MongoClient,
+    ObjectId = require('mongodb').ObjectID,
+    async = require('async'),
+    fs = require('fs'),
+    os = require('os'),
+    config = require('./config.js'),
+    tags = require('./tags.js'),
+    path = require('path'),
+    superagent = require('superagent');
+
+exports = module.exports = {
+    init: init,
+    getAll: getAll,
+    get: get,
+    add: add,
+    put: put,
+    del: del,
+    exp: exp,
+    imp: imp
+};
+
+var g_db, g_things;
+
+function init(callback) {
+    MongoClient.connect(config.databaseUrl, function (error, db) {
+        if (error) return callback(error);
+
+        g_db = db;
+        g_things = db.collection('things');
+
+        g_things.createIndex({ content: 'text' }, { default_language: 'none' });
+
+        callback(null);
+    });
+}
+
+function sanitize(data) {
+    data = data.replace(/##/g, data);
+    return data;
+}
+
+function facelift(data, tagObjects, callback) {
+    var geturl = new RegExp('(^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))', 'g');
+
+    var lines = data.split('\n');
+    var urls = [];
+
+    lines.forEach(function (line) {
+        var tmp = line.match(geturl);
+        if (tmp === null) return;
+
+        urls = tmp.map(function (url) {
+            return url.trim();
+        }).concat(urls);
+    });
+
+    async.each(urls, function (url, callback) {
+        url = url.trim();
+
+        superagent.get(url).end(function (error, result) {
+            if (error) return callback(null);
+
+            if (result.type.indexOf('image/') === 0) {
+                data = data.replace(url, '![' + url + '](' + url + ')');
+            }
+
+            callback(null);
+        });
+    }, function () {
+        tagObjects.forEach(function (tag) {
+            data = data.replace(new RegExp('#' + tag, 'gmi'), '[#' + tag + '](#search?#' + tag + ')');
+        });
+
+        callback(data);
+    });
+}
+
+function extractTags(data) {
+    var lines = data.split('\n');
+    var tagObjects = [];
+
+    lines.forEach(function (line) {
+        var tmp = line.match(/\B#(\w+)/g);
+        if (tmp === null) return;
+
+        tagObjects = tmp.map(function (tag) {
+            return tag.slice(1).toLowerCase();
+        }).concat(tagObjects);
+    });
+
+    return tagObjects;
+}
+
+function getAll(query, callback) {
+    g_things.find(query).sort({ modifiedAt: -1 }).toArray(function (error, result) {
+        if (error) return callback(error);
+        if (!result) return callback(null, []);
+
+        async.each(result, function (thing, callback) {
+            var tagObjects = extractTags(thing.content);
+            facelift(thing.content, tagObjects, function (data) {
+                thing.richContent = data;
+
+                callback(null);
+            });
+        }, function () {
+            callback(null, result);
+        });
+    });
+}
+
+function get(id, callback) {
+    g_things.find({ _id: id }).toArray(function (error, result) {
+        if (error) return callback(error);
+        if (!result) return callback(new Error('not found'));
+
+        callback(null, result);
+    });
+}
+
+function add(content, callback) {
+    var tagObjects = extractTags(content);
+    var data = sanitize(content);
+
+    var doc = {
+        content: data,
+        createdAt: new Date(),
+        modifiedAt: new Date(),
+        tags: tagObjects
+    };
+
+    async.eachSeries(tagObjects, tags.update, function (error) {
+        if (error) return callback(error);
+
+        g_things.insert(doc, function (error, result) {
+            if (error) return callback(error);
+            if (!result) return callback(new Error('no result returned'));
+
+            callback(null, result._id);
+        });
+    });
+}
+
+function put(id, content, callback) {
+    var tagObjects = extractTags(content);
+    var data = sanitize(content);
+
+    async.eachSeries(tagObjects, tags.update, function (error) {
+        if (error) return callback(error);
+
+        g_things.update({_id: new ObjectId(id) }, { $set: { content: data, tags: tagObjects, modifiedAt: new Date() } }, function (error) {
+            if (error) return callback(error);
+            callback(null);
+        });
+    });
+}
+
+function del(id, callback) {
+    g_things.deleteOne({ _id: new ObjectId(id) }, function (error) {
+        if (error) return callback(error);
+        callback(null);
+    });
+}
+
+function exp(callback) {
+    g_things.find({}).toArray(function (error, result) {
+        if (error) return callback(error);
+        if (!result) return (null, '');
+
+        var fileName = path.join(os.tmpdir(), Date.now() + '.json');
+        var out = result.map(function (thing) {
+            return {
+                createdAt: thing.createdAt,
+                modifiedAt: thing.modifiedAt,
+                content: thing.content
+            };
+        });
+        fs.writeFileSync(fileName, JSON.stringify({ things : out }, null, 4));
+
+        callback(null, fileName);
+    });
+}
+
+function imp(data, callback) {
+    async.eachSeries(data.things, function (thing, next) {
+        var tagObjects = extractTags(thing.content);
+        var data = sanitize(thing.content);
+
+        var doc = {
+            content: data,
+            createdAt: thing.createdAt,
+            modifiedAt: thing.modifiedAt || thing.createdAt,
+            tags: tagObjects
+        };
+
+        async.eachSeries(tagObjects, tags.update, function (error) {
+            if (error) return next(error);
+
+            g_things.insert(doc, function (error, result) {
+                if (error) return next(error);
+                if (!result) return next(new Error('no result returned'));
+
+                next(null, result._id);
+            });
+        });
+    }, callback);
+}

+ 28 - 0
things.json

@@ -0,0 +1,28 @@
+{
+    "things": [
+        {
+            "createdAt": "2015-12-06T18:15:10.134Z",
+            "modifiedAt": "2015-12-18T17:26:02.513Z",
+            "content": "Holiday todo\n-------------------\n\n* get up\n* celebrate\n* enjoy the good food :cake:\n* be happy :-)\n"
+        },
+        {
+            "createdAt": "2015-12-06T18:15:27.437Z",
+            "content": "*Splendid days!*"
+        },
+        {
+            "createdAt": "2015-12-06T18:16:43.469Z",
+            "modifiedAt": "2015-12-18T16:42:29.594Z",
+            "content": "![Cloudron](https://i.imgur.com/bL644zd.png)\nPictures with *text* #cloudron"
+        },
+        {
+            "createdAt": "2015-12-18T10:40:44.984Z",
+            "modifiedAt": "2015-12-18T17:18:08.919Z",
+            "content": "Twitter #emojis with a  :palm_tree: and a :rocket:"
+        },
+        {
+            "createdAt": "2015-12-18T17:43:08.448Z",
+            "modifiedAt": "2015-12-18T17:44:02.097Z",
+            "content": "All **notes** support [markdown](https://markdown-it.github.io/) to provide enhanced formatting. \n> Plugins for special rendering will get added in the future."
+        }
+    ]
+}