diff --git a/README.md b/README.md index 7afd5f0..205ce1f 100644 --- a/README.md +++ b/README.md @@ -1 +1,11 @@ -# its-background-job \ No newline at end of file +# its-background-job + +### **USAGE** +#### With only npm: + +>npm install express nodemon node-cron kue mailgun-js redis
+ +>npm start
+>npm run dev
+ +Access the website via http://localhost:3000/ diff --git a/alarm.js b/alarm.js new file mode 100644 index 0000000..57d231d --- /dev/null +++ b/alarm.js @@ -0,0 +1,4 @@ +var CronJob = require('cron').CronJob; +new CronJob('3 * * * * *', function() { + console.log('You will see this message every 3 second'); +}, null, true, 'America/Los_Angeles'); diff --git a/app.js b/app.js new file mode 100644 index 0000000..ee1f20f --- /dev/null +++ b/app.js @@ -0,0 +1,47 @@ +var express = require('express'); +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); +var Mailgun = require('mailgun-js'); + +var index = require('./routes/index'); +var users = require('./routes/users'); + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +// uncomment after placing your favicon in /public +//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', index); +app.use('/users', users); + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handler +app.use(function(err, req, res, next) { + // set locals, only providing error in development + res.locals.message = err.message; + res.locals.error = req.app.get('env') === 'development' ? err : {}; + + // render the error page + res.status(err.status || 500); + res.render('error'); +}); + +module.exports = app; diff --git a/bin/www b/bin/www new file mode 100755 index 0000000..0ba39f7 --- /dev/null +++ b/bin/www @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var app = require('../app'); +var debug = require('debug')('its-background-job:server'); +var http = require('http'); + +/** + * Get port from environment and store in Express. + */ + +var port = normalizePort(process.env.PORT || '3000'); +app.set('port', port); + +/** + * Create HTTP server. + */ + +var server = http.createServer(app); + +/** + * Listen on provided port, on all network interfaces. + */ + +server.listen(port); +server.on('error', onError); +server.on('listening', onListening); + +/** + * Normalize a port into a number, string, or false. + */ + +function normalizePort(val) { + var port = parseInt(val, 10); + + if (isNaN(port)) { + // named pipe + return val; + } + + if (port >= 0) { + // port number + return port; + } + + return false; +} + +/** + * Event listener for HTTP server "error" event. + */ + +function onError(error) { + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === 'string' + ? 'Pipe ' + port + : 'Port ' + port; + + // handle specific listen errors with friendly messages + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } +} + +/** + * Event listener for HTTP server "listening" event. + */ + +function onListening() { + var addr = server.address(); + var bind = typeof addr === 'string' + ? 'pipe ' + addr + : 'port ' + addr.port; + debug('Listening on ' + bind); +} diff --git a/email.js b/email.js new file mode 100644 index 0000000..01213bc --- /dev/null +++ b/email.js @@ -0,0 +1,18 @@ +var kue = require('kue') + , queue = kue.createQueue(); +var CronJob = require('node-cron') + + CronJob.schedule('*/12 * * * * *', function() { + var job = queue.create('email', { + from: 'Rumah Cumi ', + to: 'isumi.karina72@gmail.com', + subject: 'Hello Again', + text: 'Testing some Mailgun awesomeness!' + }).save( function(err){ + if( !err ) console.log( job.id ); + }); + }) + +// queue.process('email', function(job, done){ +// email(job.data.to, done); +// }); diff --git a/package.json b/package.json new file mode 100644 index 0000000..b153d55 --- /dev/null +++ b/package.json @@ -0,0 +1,25 @@ +{ + "name": "its-background-job", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www", + "dev": "nodemon ./bin/www" + }, + "dependencies": { + "body-parser": "~1.16.0", + "cookie-parser": "~1.4.3", + "cron": "^1.2.1", + "debug": "~2.6.0", + "ejs": "~2.5.5", + "express": "~4.14.1", + "kue": "^0.11.5", + "mailgun-js": "^0.8.2", + "morgan": "~1.7.0", + "node-cron": "^1.1.3", + "nodemailer": "^3.1.7", + "nodemon": "^1.11.0", + "redis": "^2.7.1", + "serve-favicon": "~2.3.2" + } +} diff --git a/process.js b/process.js new file mode 100644 index 0000000..f25b871 --- /dev/null +++ b/process.js @@ -0,0 +1,18 @@ +var kue = require('kue') + , queue = kue.createQueue(); + +var api_key = 'key-e62dea4237cc45b2a5c968737823befc'; +var domain = 'sandbox07d92b9d748d4a2ba4b13da790c4a733.mailgun.org'; +var mailgun = require('mailgun-js')({apiKey: api_key, domain: domain}); + +queue.process('email', function(job, done){ + email(job.data, done); +}); + +function email(data, done) { + mailgun.messages().send(data, function (error, body) { + console.log(body); + }); + // email send stuff... + done(); +} diff --git a/public/javascripts/contact.js b/public/javascripts/contact.js new file mode 100644 index 0000000..e8163cc --- /dev/null +++ b/public/javascripts/contact.js @@ -0,0 +1,28 @@ +$(function () { + + $('#contact-form').validator(); + + $('#contact-form').on('submit', function (e) { + if (!e.isDefaultPrevented()) { + var url = "contact.php"; + + $.ajax({ + type: "POST", + url: url, + data: $(this).serialize(), + success: function (data) + { + var messageAlert = 'alert-' + data.type; + var messageText = data.message; + + var alertBox = '
' + messageText + '
'; + if (messageAlert && messageText) { + $('#contact-form').find('.messages').html(alertBox); + $('#contact-form')[0].reset(); + } + } + }); + return false; + } + }) +}); \ No newline at end of file diff --git a/public/javascripts/contact.php b/public/javascripts/contact.php new file mode 100644 index 0000000..5390363 --- /dev/null +++ b/public/javascripts/contact.php @@ -0,0 +1,48 @@ +'; +$sendTo = 'Demo contact form '; +$subject = 'New message from contact form'; +$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in the email +$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!'; +$errorMessage = 'There was an error while submitting the form. Please try again later'; + +// let's do the sending + +try +{ + $emailText = "You have new message from contact form\n=============================\n"; + + foreach ($_POST as $key => $value) { + + if (isset($fields[$key])) { + $emailText .= "$fields[$key]: $value\n"; + } + } + + $headers = array('Content-Type: text/plain; charset="UTF-8";', + 'From: ' . $from, + 'Reply-To: ' . $from, + 'Return-Path: ' . $from, + ); + + mail($sendTo, $subject, $emailText, implode("\n", $headers)); + + $responseArray = array('type' => 'success', 'message' => $okMessage); +} +catch (\Exception $e) +{ + $responseArray = array('type' => 'danger', 'message' => $errorMessage); +} + +if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { + $encoded = json_encode($responseArray); + + header('Content-Type: application/json'); + + echo $encoded; +} +else { + echo $responseArray['message']; +} diff --git a/public/javascripts/validator.js b/public/javascripts/validator.js new file mode 100644 index 0000000..b25e63d --- /dev/null +++ b/public/javascripts/validator.js @@ -0,0 +1,385 @@ +/*! + * Validator v0.11.5 for Bootstrap 3, by @1000hz + * Copyright 2016 Cina Saffary + * Licensed under http://opensource.org/licenses/MIT + * + * https://github.com/1000hz/bootstrap-validator + */ + ++function ($) { + 'use strict'; + + // VALIDATOR CLASS DEFINITION + // ========================== + + function getValue($el) { + return $el.is('[type="checkbox"]') ? $el.prop('checked') : + $el.is('[type="radio"]') ? !!$('[name="' + $el.attr('name') + '"]:checked').length : + $el.val() + } + + var Validator = function (element, options) { + this.options = options + this.validators = $.extend({}, Validator.VALIDATORS, options.custom) + this.$element = $(element) + this.$btn = $('button[type="submit"], input[type="submit"]') + .filter('[form="' + this.$element.attr('id') + '"]') + .add(this.$element.find('input[type="submit"], button[type="submit"]')) + + this.update() + + this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.onInput, this)) + this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this)) + this.$element.on('reset.bs.validator', $.proxy(this.reset, this)) + + this.$element.find('[data-match]').each(function () { + var $this = $(this) + var target = $this.data('match') + + $(target).on('input.bs.validator', function (e) { + getValue($this) && $this.trigger('input.bs.validator') + }) + }) + + this.$inputs.filter(function () { return getValue($(this)) }).trigger('focusout') + + this.$element.attr('novalidate', true) // disable automatic native validation + this.toggleSubmit() + } + + Validator.VERSION = '0.11.5' + + Validator.INPUT_SELECTOR = ':input:not([type="hidden"], [type="submit"], [type="reset"], button)' + + Validator.FOCUS_OFFSET = 20 + + Validator.DEFAULTS = { + delay: 500, + html: false, + disable: true, + focus: true, + custom: {}, + errors: { + match: 'Does not match', + minlength: 'Not long enough' + }, + feedback: { + success: 'glyphicon-ok', + error: 'glyphicon-remove' + } + } + + Validator.VALIDATORS = { + 'native': function ($el) { + var el = $el[0] + if (el.checkValidity) { + return !el.checkValidity() && !el.validity.valid && (el.validationMessage || "error!") + } + }, + 'match': function ($el) { + var target = $el.data('match') + return $el.val() !== $(target).val() && Validator.DEFAULTS.errors.match + }, + 'minlength': function ($el) { + var minlength = $el.data('minlength') + return $el.val().length < minlength && Validator.DEFAULTS.errors.minlength + } + } + + Validator.prototype.update = function () { + this.$inputs = this.$element.find(Validator.INPUT_SELECTOR) + .add(this.$element.find('[data-validate="true"]')) + .not(this.$element.find('[data-validate="false"]')) + + return this + } + + Validator.prototype.onInput = function (e) { + var self = this + var $el = $(e.target) + var deferErrors = e.type !== 'focusout' + + if (!this.$inputs.is($el)) return + + this.validateInput($el, deferErrors).done(function () { + self.toggleSubmit() + }) + } + + Validator.prototype.validateInput = function ($el, deferErrors) { + var value = getValue($el) + var prevErrors = $el.data('bs.validator.errors') + var errors + + if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]') + + var e = $.Event('validate.bs.validator', {relatedTarget: $el[0]}) + this.$element.trigger(e) + if (e.isDefaultPrevented()) return + + var self = this + + return this.runValidators($el).done(function (errors) { + $el.data('bs.validator.errors', errors) + + errors.length + ? deferErrors ? self.defer($el, self.showErrors) : self.showErrors($el) + : self.clearErrors($el) + + if (!prevErrors || errors.toString() !== prevErrors.toString()) { + e = errors.length + ? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors}) + : $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors}) + + self.$element.trigger(e) + } + + self.toggleSubmit() + + self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]})) + }) + } + + + Validator.prototype.runValidators = function ($el) { + var errors = [] + var deferred = $.Deferred() + + $el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject() + $el.data('bs.validator.deferred', deferred) + + function getValidatorSpecificError(key) { + return $el.data(key + '-error') + } + + function getValidityStateError() { + var validity = $el[0].validity + return validity.typeMismatch ? $el.data('type-error') + : validity.patternMismatch ? $el.data('pattern-error') + : validity.stepMismatch ? $el.data('step-error') + : validity.rangeOverflow ? $el.data('max-error') + : validity.rangeUnderflow ? $el.data('min-error') + : validity.valueMissing ? $el.data('required-error') + : null + } + + function getGenericError() { + return $el.data('error') + } + + function getErrorMessage(key) { + return getValidatorSpecificError(key) + || getValidityStateError() + || getGenericError() + } + + $.each(this.validators, $.proxy(function (key, validator) { + var error = null + if ((getValue($el) || $el.attr('required')) && + ($el.data(key) || key == 'native') && + (error = validator.call(this, $el))) { + error = getErrorMessage(key) || error + !~errors.indexOf(error) && errors.push(error) + } + }, this)) + + if (!errors.length && getValue($el) && $el.data('remote')) { + this.defer($el, function () { + var data = {} + data[$el.attr('name')] = getValue($el) + $.get($el.data('remote'), data) + .fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) }) + .always(function () { deferred.resolve(errors)}) + }) + } else deferred.resolve(errors) + + return deferred.promise() + } + + Validator.prototype.validate = function () { + var self = this + + $.when(this.$inputs.map(function (el) { + return self.validateInput($(this), false) + })).then(function () { + self.toggleSubmit() + self.focusError() + }) + + return this + } + + Validator.prototype.focusError = function () { + if (!this.options.focus) return + + var $input = this.$element.find(".has-error:first :input") + if ($input.length === 0) return + + $('html, body').animate({scrollTop: $input.offset().top - Validator.FOCUS_OFFSET}, 250) + $input.focus() + } + + Validator.prototype.showErrors = function ($el) { + var method = this.options.html ? 'html' : 'text' + var errors = $el.data('bs.validator.errors') + var $group = $el.closest('.form-group') + var $block = $group.find('.help-block.with-errors') + var $feedback = $group.find('.form-control-feedback') + + if (!errors.length) return + + errors = $('