repo
string
commit
string
message
string
diff
string
tuxsoul/wiki-httpbl
655370cec13cf0df3484ce9743a127b814f62a14
* Fix bug #1: "wiki-httpbl stop others extensions using the same wgHook ...." * Change $wgHook['ParserBeforeTidy'] to $wgHook['ParserAfterTidy'] * Change version to v0.1.1
diff --git a/CHANGELOG b/CHANGELOG index 92f0257..0478535 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,15 +1,22 @@ -=============================================================================== +================================================================================ CHANGELOG -=============================================================================== +================================================================================ -------------------------------------------------------------------------------- -2008-01-20 - 0.1 +2008-01-31 - v0.1.1 +-------------------------------------------------------------------------------- +* Fix bug #1: "wiki-httpbl stop others extensions using the same wgHook ...." +* Change $wgHook['ParserBeforeTidy'] to $wgHook['ParserAfterTidy'] +* Change version to v0.1.1 + +-------------------------------------------------------------------------------- +2008-01-20 - v0.1 -------------------------------------------------------------------------------- * Core version '0.1' * First version of this extension * Detect spammer's using http:bl from 'Project Honey Pot' * Can redirect spammer to one address trap * Use one word with address trap * Insert three or more address trap in the html code -=============================================================================== +================================================================================ diff --git a/README b/README index 0c0db9e..d0eb7c8 100644 --- a/README +++ b/README @@ -1,83 +1,83 @@ = Introduction = Please visit the following websites where you can find more information: Project Honey Pot website http://www.projecthoneypot.org/?rf=39586 Extension wiki-httpbl http://code.google.com/p/wiki-httpbl/ = Contact = Author: Mario Oyorzabal Salgado Blog: http://blog.tuxsoul.com E-mail: <tuxsoul@tuxsoul.com> = Bugs = If you find any bugs or have any idea for a feature can be usefull to this extension, you can leave it in the bugtrack: http://code.google.com/p/wiki-httpbl/issues/list = License = GNU General Public License v2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html = Requirements = - * Key from "Project Honey Pot" - * Quicklink from "Project Honey Pot" - * Mediawiki version 1.6 + - * PHP4 + + * Key from "Project Honey Pot" + * Quicklink from "Project Honey Pot" + * Mediawiki version 1.6 + + * PHP4 + = Features = - * Use Http:BL to detect spammer's - * Ability to redirect into a trap if the visitor is a spammer - * Ability to insert addresses traps in the html code of - Mediawiki + * Use Http:BL to detect spammer's + * Ability to redirect into a trap if the visitor is a spammer + * Ability to insert addresses traps in the html code of + Mediawiki = Details = - * First download and decompresses the file extension of this - * Rename the directory the this extension to "wiki-httpbl" - * Inside the directory "wiki-httpbl" there is a file named - "config.httpbl.php", which is necessary to change the following: + * First download and decompresses the file extension of this + * Rename the directory the this extension to "wiki-httpbl" + * Inside the directory "wiki-httpbl" there is a file named + "config.httpbl.php", which is necessary to change the following: - * Enter your "key" from Project Honey Pot - * Enter a QuickLink or trap, to redirect the spammer's - * Enter a word random, to anything, is only to show the Links to spammer's - traps + * Enter your "key" from Project Honey Pot + * Enter a QuickLink or trap, to redirect the spammer's + * Enter a word random, to anything, is only to show the Links to spammer's + traps - * Upload the "wiki-httpbl" to the directory of extensions you wiki, which is - called "extensions" - * Open the file named "LocalSettings.php" which is located in the - Root directory of your site, after adding the following two lines to - End of the file: + * Upload the "wiki-httpbl" to the directory of extensions you wiki, which is + called "extensions" + * Open the file named "LocalSettings.php" which is located in the + Root directory of your site, after adding the following two lines to + End of the file: - # Include Http:bl - include ( './extensions/wiki-httpbl/httpbl.php' ); + # Include Http:bl + include ( './extensions/wiki-httpbl/httpbl.php' ); - * Save the file and enters your website to see if it is not showing any - Error + * Save the file and enters your website to see if it is not showing any + Error Lastly and can only wait to block the spammer's coming to you Website. = Donation = Please consider helping through donations, for more information visit the following link: Donate http://tinyurl.com/2zhdhg Extension wiki-httpbl http://code.google.com/p/wiki-httpbl/ Cheers :-). diff --git a/README-ES b/README-ES index 42c4d26..eeee7bd 100644 --- a/README-ES +++ b/README-ES @@ -1,84 +1,84 @@ = Introducción = Por favor visita los siguientes sitios web, en donde encontrarás más información: Project Honey Pot website http://www.projecthoneypot.org/?rf=39586 Extension wiki-httpbl http://code.google.com/p/wiki-httpbl/ = Contacto = Autor: Mario Oyorzabal Salgado Blog: http://blog.tuxsoul.com E-mail: <tuxsoul@tuxsoul.com> = Bugs = Si encuentras algún bug o tienes alguna idea para una característica que creas que le puede ser útil a esta extensión, puedes dejarla en el bugtrack: http://code.google.com/p/wiki-httpbl/issues/list = Licencia = GNU General Public License v2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html = Requerimientos = - * Key de "Project Honey Pot" - * Quicklink de "Project Honey Pot" - * Mediawiki versión 1.6 + - * PHP4 + + * Key de "Project Honey Pot" + * Quicklink de "Project Honey Pot" + * Mediawiki versión 1.6 + + * PHP4 + = Características = - * Usa Http:BL para detectar spammer's - * Posibilidad de redireccionar hacia una trampa si el visitante es un spammer - * Posibilidad de insertar direcciones de trampas en el código html de - mediawiki + * Usa Http:BL para detectar spammer's + * Posibilidad de redireccionar hacia una trampa si el visitante es un spammer + * Posibilidad de insertar direcciones de trampas en el código html de + mediawiki = Detalles = - * Primero descarga y descomprime el archivo de esta extensión - * Renombra el directorio de la extensión a "wiki-httpbl" - * Dentro del directorio de "wiki-httpbl" hay un archivo nombrado - "config.httpbl.php", en el cual es necesario cambiar lo siguiente: + * Primero descarga y descomprime el archivo de esta extensión + * Renombra el directorio de la extensión a "wiki-httpbl" + * Dentro del directorio de "wiki-httpbl" hay un archivo nombrado + "config.httpbl.php", en el cual es necesario cambiar lo siguiente: - * Ingresa tú "key" de Project Honey Pot - * Ingresa un QuickLink o trampa, para redireccionar a los spammer's - * Ingresa una palabra aleatoria, la que sea, solo es para mostrar los - enlaces que llevan a trampas para spammer's + * Ingresa tú "key" de Project Honey Pot + * Ingresa un QuickLink o trampa, para redireccionar a los spammer's + * Ingresa una palabra aleatoria, la que sea, solo es para mostrar los + enlaces que llevan a trampas para spammer's - * Sube el directorio "wiki-httpbl" al directorio de extensiones de tú wiki, el - cual tiene el nombre de "extensions" - * Abre el archivo nombrado "LocalSettings.php" el cual esta ubicado en el - directorio raíz de tú sitio web, despúes agrega las siguientes dos lineas al - final del archivo: + * Sube el directorio "wiki-httpbl" al directorio de extensiones de tú wiki, el + cual tiene el nombre de "extensions" + * Abre el archivo nombrado "LocalSettings.php" el cual esta ubicado en el + directorio raíz de tú sitio web, despúes agrega las siguientes dos lineas al + final del archivo: - # Include Http:bl - include ( './extensions/wiki-httpbl/httpbl.php' ); + # Include Http:bl + include ( './extensions/wiki-httpbl/httpbl.php' ); - * Salva el archivo y entra a tú sitio web para ver si no se muestra algún - error + * Salva el archivo y entra a tú sitio web para ver si no se muestra algún + error Por último ya solo queda esperar para bloquear a los spammer's que lleguen a tú sitio web. = Donaciones = Por favor considera el ayudar mediante donaciones, para más información visita el siguiente enlace: Donación http://tinyurl.com/2zhdhg Extension wiki-httpbl http://code.google.com/p/wiki-httpbl/ Saludos :-). diff --git a/httpbl.php b/httpbl.php index 01dd0fe..e4899af 100644 --- a/httpbl.php +++ b/httpbl.php @@ -1,65 +1,69 @@ <?php /* Implementation of API from "Project Honey Pot" http://www.projecthoneypot.org/httpbl_api Author: Mario Oyorzabal Salgado Blog: http://blog.tuxsoul.com/ E-mail: <tuxsoul@tuxsoul.com> Web: http://code.google.com/p/wiki-httpbl/ Donate: http://tinyurl.com/2zhdhg This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // Check to run with mediawiki if (!defined('MEDIAWIKI')) { die ('You are lost ?'); } +// Extension version, not core version, is other stuff +$httpblExtensionVersion = "1"; + // Define path of extension define('HTTPBL_CWD', dirname(__FILE__)); // Include class to work dnsbl of httpbl include(HTTPBL_CWD . '/object.httpbl.php'); // Instance object $httpbl = new objectHttpBL(); // Execute httpbl filter function httpbl_mediawiki_start () { global $httpbl; $httpbl->httpblStart(); } // Execute httpbl text function httpbl_mediawiki_text (&$parser, &$text) { global $httpbl; $text = $httpbl->httpblGetUrlTrap() . $text; + return true; } // Extension info $wgExtensionCredits['other'][] = array( 'name' => $httpbl->httpblInfo('name'), - 'version' => $httpbl->httpblInfo('version'), + 'version' => $httpbl->httpblInfo('version') . '.' . $httpblExtensionVersion, 'author' => $httpbl->httpblInfo('author'), 'description' => $httpbl->httpblInfo('description'), 'url' => $httpbl->httpblInfo('url'), ); -$wgHooks['ParserBeforeTidy'][] = 'httpbl_mediawiki_text'; +$wgHooks['ParserAfterTidy'][] = 'httpbl_mediawiki_text'; $wgExtensionFunctions[] = 'httpbl_mediawiki_start'; ?> diff --git a/index.html b/index.html new file mode 100644 index 0000000..e69de29
tuxsoul/wiki-httpbl
7fbb34f82c463770fef666441c439989b21433b6
* Core version v0.1 * First version of this extension * Detect spammer's using http:bl from 'Project Honey Pot' * Can redirect spammer to one address trap * Use one word with address trap * Insert three or more address trap in the html code
diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..92f0257 --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,15 @@ +=============================================================================== +CHANGELOG +=============================================================================== + +-------------------------------------------------------------------------------- +2008-01-20 - 0.1 +-------------------------------------------------------------------------------- +* Core version '0.1' +* First version of this extension +* Detect spammer's using http:bl from 'Project Honey Pot' +* Can redirect spammer to one address trap +* Use one word with address trap +* Insert three or more address trap in the html code + +=============================================================================== diff --git a/README b/README new file mode 100644 index 0000000..0c0db9e --- /dev/null +++ b/README @@ -0,0 +1,83 @@ + += Introduction = + +Please visit the following websites where you can find more +information: + +Project Honey Pot website +http://www.projecthoneypot.org/?rf=39586 + +Extension wiki-httpbl +http://code.google.com/p/wiki-httpbl/ + += Contact = + +Author: Mario Oyorzabal Salgado +Blog: http://blog.tuxsoul.com +E-mail: <tuxsoul@tuxsoul.com> + += Bugs = + +If you find any bugs or have any idea for a feature can be usefull to this +extension, you can leave it in the bugtrack: + +http://code.google.com/p/wiki-httpbl/issues/list + += License = + +GNU General Public License v2 +http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + += Requirements = + + * Key from "Project Honey Pot" + * Quicklink from "Project Honey Pot" + * Mediawiki version 1.6 + + * PHP4 + + += Features = + + * Use Http:BL to detect spammer's + * Ability to redirect into a trap if the visitor is a spammer + * Ability to insert addresses traps in the html code of + Mediawiki + += Details = + + * First download and decompresses the file extension of this + * Rename the directory the this extension to "wiki-httpbl" + * Inside the directory "wiki-httpbl" there is a file named + "config.httpbl.php", which is necessary to change the following: + + * Enter your "key" from Project Honey Pot + * Enter a QuickLink or trap, to redirect the spammer's + * Enter a word random, to anything, is only to show the Links to spammer's + traps + + * Upload the "wiki-httpbl" to the directory of extensions you wiki, which is + called "extensions" + * Open the file named "LocalSettings.php" which is located in the + Root directory of your site, after adding the following two lines to + End of the file: + + # Include Http:bl + include ( './extensions/wiki-httpbl/httpbl.php' ); + + * Save the file and enters your website to see if it is not showing any + Error + +Lastly and can only wait to block the spammer's coming to you Website. + += Donation = + +Please consider helping through donations, for more information visit the +following link: + +Donate +http://tinyurl.com/2zhdhg + +Extension wiki-httpbl +http://code.google.com/p/wiki-httpbl/ + + +Cheers :-). diff --git a/README-ES b/README-ES new file mode 100644 index 0000000..42c4d26 --- /dev/null +++ b/README-ES @@ -0,0 +1,84 @@ + += Introducción = + +Por favor visita los siguientes sitios web, en donde encontrarás más +información: + +Project Honey Pot website +http://www.projecthoneypot.org/?rf=39586 + +Extension wiki-httpbl +http://code.google.com/p/wiki-httpbl/ + += Contacto = + +Autor: Mario Oyorzabal Salgado +Blog: http://blog.tuxsoul.com +E-mail: <tuxsoul@tuxsoul.com> + += Bugs = + +Si encuentras algún bug o tienes alguna idea para una característica que creas +que le puede ser útil a esta extensión, puedes dejarla en el bugtrack: + +http://code.google.com/p/wiki-httpbl/issues/list + += Licencia = + +GNU General Public License v2 +http://www.gnu.org/licenses/old-licenses/gpl-2.0.html + += Requerimientos = + + * Key de "Project Honey Pot" + * Quicklink de "Project Honey Pot" + * Mediawiki versión 1.6 + + * PHP4 + + += Características = + + * Usa Http:BL para detectar spammer's + * Posibilidad de redireccionar hacia una trampa si el visitante es un spammer + * Posibilidad de insertar direcciones de trampas en el código html de + mediawiki + += Detalles = + + * Primero descarga y descomprime el archivo de esta extensión + * Renombra el directorio de la extensión a "wiki-httpbl" + * Dentro del directorio de "wiki-httpbl" hay un archivo nombrado + "config.httpbl.php", en el cual es necesario cambiar lo siguiente: + + * Ingresa tú "key" de Project Honey Pot + * Ingresa un QuickLink o trampa, para redireccionar a los spammer's + * Ingresa una palabra aleatoria, la que sea, solo es para mostrar los + enlaces que llevan a trampas para spammer's + + * Sube el directorio "wiki-httpbl" al directorio de extensiones de tú wiki, el + cual tiene el nombre de "extensions" + * Abre el archivo nombrado "LocalSettings.php" el cual esta ubicado en el + directorio raíz de tú sitio web, despúes agrega las siguientes dos lineas al + final del archivo: + + # Include Http:bl + include ( './extensions/wiki-httpbl/httpbl.php' ); + + * Salva el archivo y entra a tú sitio web para ver si no se muestra algún + error + +Por último ya solo queda esperar para bloquear a los spammer's que lleguen a tú +sitio web. + += Donaciones = + +Por favor considera el ayudar mediante donaciones, para más información visita +el siguiente enlace: + +Donación +http://tinyurl.com/2zhdhg + +Extension wiki-httpbl +http://code.google.com/p/wiki-httpbl/ + + +Saludos :-). diff --git a/config.httpbl.php b/config.httpbl.php new file mode 100644 index 0000000..5c643c9 --- /dev/null +++ b/config.httpbl.php @@ -0,0 +1,49 @@ +<?php +/* +Implementation of API from "Project Honey Pot" +http://www.projecthoneypot.org/httpbl_api + +Author: Mario Oyorzabal Salgado +Blog: http://blog.tuxsoul.com/ +E-mail: <tuxsoul@tuxsoul.com> +Web: http://code.google.com/p/wiki-httpbl/ +Donate: http://tinyurl.com/2zhdhg + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +// you can't execute directly this file +// you are lost ? +if (!defined('HTTPBL_CWD')) { + die ('You are lost ?'); +} + +////////// Configuration +////////// You can edit all values ;-) + +///// Key to access dnsbl service from "Project Honey Pot" +///// All Access Keys are 12-characters in length, lower case, and contain only alpha characters (no numbers) +///// You need a key ?, register here: http://www.projecthoneypot.org?rf=39586 +define('HTTPBL_KEY', '------------'); + +////////// Url to honeypot trap for redirect malicious visitors +///// If you have install a trap or you can get this in "Project Honey Pot" -> "QuickLink" +///// This value is important to catch more spammers ;-) +define('HTTPBL_TRAP', ''); + +///// Is important change this value to any word, for have usefull url trap's +define('HTTPBL_TRAP_WORD', 'mediawiki'); + +?> diff --git a/core.httpbl.php b/core.httpbl.php new file mode 100644 index 0000000..f2b6574 --- /dev/null +++ b/core.httpbl.php @@ -0,0 +1,182 @@ +<?php +/* +Implementation of API from "Project Honey Pot" +http://www.projecthoneypot.org/httpbl_api + +Author: Mario Oyorzabal Salgado +Blog: http://blog.tuxsoul.com/ +E-mail: <tuxsoul@tuxsoul.com> +Web: http://code.google.com/p/wiki-httpbl/ +Donate: http://tinyurl.com/2zhdhg + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +// can't execute directly this file +// you are lost ? +if (!defined('HTTPBL_CWD')) { + die ('You are lost ?'); +} + +// main class object +class coreHttpBL +{ + var $coreHttpBLIp; + var $coreHttpBLError; + + var $coreHttpBLConfVersion; + var $coreHttpBLConfDnsbl; + var $coreHttpBLConfDays; + + function coreHttpBL () { + // set flag error to cero + $this->coreHttpBLError = 0; + + // config + // version of this core + $this->coreHttpBLConfVersion = '0.1'; + + // spammer days since last activity + $this->coreHttpBLConfDays = '15'; + + // define query to dnsbl + $this->coreHttpBLConfDnsbl = '{key}.{ip}.dnsbl.httpbl.org'; + } + + // return version of this core + function coreHttpBLVersion () { + return $this->coreHttpBLConfVersion; + } + + // start the search to spammer's + function coreHttpBLStart () { + // detect ip + $this->coreHttpBLDetectIp(); + + // reverse-octet ip address + // change data of query + $host = $this->coreHttpBLDnsblPrepareQuery(); + + // make query and get response + $response = $this->coreHttpBLDnsblQuery($host); + + // Is spammer ? + if($this->coreHttpBLIsSpammer($response) == 1) { + // Get the trap + $this->coreHttpBLShowTrap(); + } + } + + // try to detect the remote ip + function coreHttpBLDetectIP () { + $ip = $_SERVER['REMOTE_ADDR']; + + // only for test + // $ip = '127.1.1.1'; + + $this->coreHttpBLIp = $ip; + } + + // change data of query to dnsbl + function coreHttpBLDnsblPrepareQuery () { + // reverse-octet ip format + $reverseIp = implode('.', array_reverse(explode('.', $this->coreHttpBLIp))); + + // prepare query to dnsbl + $string = $this->coreHttpBLConfDnsbl; + $string = ereg_replace('{key}', HTTPBL_KEY, $string); + $string = ereg_replace('{ip}', $reverseIp, $string); + + return $string; + } + + // make the query to dnsbl server + function coreHttpBLDnsblQuery ($host) { + $response = gethostbyname($host); + + if($response == $host) + $this->coreHttpBLError = 1; + + return $response; + } + + // is spammer ? + function coreHttpBLIsSpammer ($response) { + if($this->coreHttpBLError == 0) { + $data = explode('.', $response); + $spammer = 0; + + // the first octect always is 127 + if((int)$data[0] == 127) { + // spammer days since last activity + if((int)$data[1] <= $this->coreHttpBLConfDays) { + // only check the type of spammer + if((int)$data[3] > 0) { + $spammer = 1; + } + } + } + else + $this->coreHttpBLError = 1; + + return $spammer; + } + + return 0; + } + + // redirect to the trap + function coreHttpBLShowTrap () { + if($this->coreHttpBLError == 0) { + // FIXME: HTTPBL_TRAP is set correctly ? + if(strlen(HTTPBL_TRAP) > 0) { + header('Location: ' . HTTPBL_TRAP); + die(); + } + } + } + + // return url to trap in html + // FIXME: Need more work here :) + function coreHttpBLGetUrlTrap () { + $text = '<!-- begin links ' . HTTPBL_TRAP_WORD . ' -->'; + + // FIXME: HTTPBL_TRAP is set correctly ? + if(strlen(HTTPBL_TRAP) > 0) { + $url = array ( + '<a href="{url}"><!-- {word} --></a>', + '<a href="{url}" style="display: none;">{word}</a>', + '<div style="display: none;"><a href="{url}">{word}</a></div>', + '<a href="{url}"></a>', + '<!-- <a href="{url}">{word}</a> -->', + '<div style="position: absolute; top: -250px; left: -250px;"><a href="{url}">{word}</a></div>', + '<a href="{url}"><span style="display: none;">{word}</span></a>', + ); + + for($x = 0; $x <= 2; $x++) { + $temp = $url[rand(0, 6)]; + $temp = ereg_replace('{url}', HTTPBL_TRAP, $temp); + $temp = ereg_replace('{word}', HTTPBL_TRAP_WORD, $temp); + + $text .= $temp; + } + + $text .= '<!-- end links '. HTTPBL_TRAP_WORD . ' -->'; + } + + return $text; + } +} +?> diff --git a/httpbl.php b/httpbl.php new file mode 100644 index 0000000..01dd0fe --- /dev/null +++ b/httpbl.php @@ -0,0 +1,65 @@ +<?php +/* +Implementation of API from "Project Honey Pot" +http://www.projecthoneypot.org/httpbl_api + +Author: Mario Oyorzabal Salgado +Blog: http://blog.tuxsoul.com/ +E-mail: <tuxsoul@tuxsoul.com> +Web: http://code.google.com/p/wiki-httpbl/ +Donate: http://tinyurl.com/2zhdhg + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +// Check to run with mediawiki +if (!defined('MEDIAWIKI')) { + die ('You are lost ?'); +} + +// Define path of extension +define('HTTPBL_CWD', dirname(__FILE__)); + +// Include class to work dnsbl of httpbl +include(HTTPBL_CWD . '/object.httpbl.php'); + +// Instance object +$httpbl = new objectHttpBL(); + +// Execute httpbl filter +function httpbl_mediawiki_start () { + global $httpbl; + $httpbl->httpblStart(); +} + +// Execute httpbl text +function httpbl_mediawiki_text (&$parser, &$text) { + global $httpbl; + $text = $httpbl->httpblGetUrlTrap() . $text; +} + +// Extension info +$wgExtensionCredits['other'][] = array( + 'name' => $httpbl->httpblInfo('name'), + 'version' => $httpbl->httpblInfo('version'), + 'author' => $httpbl->httpblInfo('author'), + 'description' => $httpbl->httpblInfo('description'), + 'url' => $httpbl->httpblInfo('url'), +); + +$wgHooks['ParserBeforeTidy'][] = 'httpbl_mediawiki_text'; +$wgExtensionFunctions[] = 'httpbl_mediawiki_start'; + +?> diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/license.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/object.httpbl.php b/object.httpbl.php new file mode 100644 index 0000000..a5cb2ea --- /dev/null +++ b/object.httpbl.php @@ -0,0 +1,76 @@ +<?php +/* +Implementation of API from "Project Honey Pot" +http://www.projecthoneypot.org/httpbl_api + +Author: Mario Oyorzabal Salgado +Blog: http://blog.tuxsoul.com/ +E-mail: <tuxsoul@tuxsoul.com> +Web: http://code.google.com/p/wiki-httpbl/ +Donate: http://tinyurl.com/2zhdhg + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +// can't execute directly this file +// you are lost ? +if (!defined('HTTPBL_CWD')) { + die('You are lost ?'); +} + +// include config file +include (HTTPBL_CWD . '/config.httpbl.php'); + +// include core file +include (HTTPBL_CWD . '/core.httpbl.php'); + +// main class object +class objectHttpBL extends coreHttpBL +{ + // load configuration + function httpbl () { + + } + + // start the search to spammer's + function httpblStart () { + $this->coreHttpBLStart(); + } + + // get url to trap + function httpblGetUrlTrap () { + return $this->coreHttpBLGetUrlTrap(); + } + + // return information from this code + function httpblInfo ($type) { + $description = 'This code implement the API from "Project Honey Pot", to detect Spammers, Harvesters'; + $description .= ' and other malicious visitors. Consider donate to this extension'; + + $values = array ( + 'name' => 'Http:BL', + 'version' => $this->coreHttpBLVersion(), + 'author' => 'Mario Oyorzabal Salgado', + 'description' => $description, + 'url' => 'http://code.google.com/p/wiki-httpbl/', + ); + + if (isset($values[$type])) + return $values[$type]; + else + return 'Null'; + } +} +?>
xeqi/blob_detector
104dd2fe70863b4f9470c5fcbe4a2856dfb12a1d
Change api and add some tests.
diff --git a/README b/README deleted file mode 100644 index 717a0af..0000000 --- a/README +++ /dev/null @@ -1,15 +0,0 @@ -# blob-detector - -FIXME: write description - -## Usage - -FIXME: write - -## Installation - -FIXME: write - -## License - -FIXME: write diff --git a/README.md b/README.md new file mode 100644 index 0000000..9a7bab2 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# blob_detector + +A simple blob detector for clojure. + +## Usage + +The useful function is `blob-detector.core/detect` which requires a predicate taking a x and y argument and determining if they are interesting, and a width and height of the 2d plane. + +For example: + + (import 'java.io.File) + (import 'java.awt.BufferedImage) + (import 'javax.imageio.ImageIO) + (import 'java.awt.Color) + + (defn greenish + [#^BufferedImage image] + (fn [x y] (let [color (Color. (.getRGB image x y)) + red (.getRed color) + green (.getGreen color) + blue (.getBlue color)] + (and (> green (+ 5 blue)) + (> green (+ 5 red)))))) + + (let [image (ImageIO/read (File. "somefile.png"))] + (blob-detector.core/detect (greenish image) (.getWidth image) (.getHeight image))) \ No newline at end of file diff --git a/src/blob_detector/core.clj b/src/blob_detector/core.clj index 6b2aa66..f014f25 100644 --- a/src/blob_detector/core.clj +++ b/src/blob_detector/core.clj @@ -1,44 +1,45 @@ (ns blob-detector.core (:use [blob-detector.label-map] [blob-detector.blob] - [blob-detector.cache.protocol])) + [blob-detector.cache.protocol] + [blob-detector.cache.vector])) (defn- label-point [x y accum] (let [label-map (:label-map accum) next-label (:next-label accum) blobs (:blobs accum) cache (:cache accum) nearby-blob-ids (distinct (filter #(not= 0 %) [(search label-map (lookup cache (dec x) (dec y))) (search label-map (lookup cache x (dec y))) (search label-map (lookup cache (inc x) (dec y))) (search label-map (lookup cache (dec x) y))]))] (if (empty? nearby-blob-ids) {:cache (insert cache x y next-label) :label-map (assoc label-map next-label next-label) :next-label (inc next-label) :blobs (assoc blobs next-label (blob-detector.blob.Blob. x y 1 1 1))} (let [label (apply min nearby-blob-ids)] {:cache (insert cache x y label) :label-map (reduce #(assoc %1 %2 label) label-map nearby-blob-ids) :next-label next-label :blobs (combine blobs nearby-blob-ids label (blob-detector.blob.Blob. x y 1 1 1))})))) (defn- label-row - [pred get-data y width accum] - (reduce #(if (pred (get-data %2 y)) + [pred y width accum] + (reduce #(if (pred %2 y) (label-point %2 y %1) (assoc %1 :cache (insert (:cache %1) %2 y 0))) accum (range width))) -(defn- label-data - [pred get-data cache width height] - (reduce #(label-row pred get-data %2 width %1) +(defn label-data + [pred cache width height] + (reduce #(label-row pred %2 width %1) {:label-map {0 0} :next-label 1 :blobs {} :cache cache} (range height))) (defn detect - [pred get-data cache] - (label-data pred get-data cache (width cache) (height cache))) \ No newline at end of file + [pred width height] + (vals (:blobs (label-data pred (blob-detector.cache.vector.Vector. [] width height) width height)))) \ No newline at end of file diff --git a/test/blob_detector/core_test.clj b/test/blob_detector/core_test.clj index b2f706a..7c70ddb 100644 --- a/test/blob_detector/core_test.clj +++ b/test/blob_detector/core_test.clj @@ -1,12 +1,26 @@ (ns blob-detector.core-test - (:use [blob-detector.core] - [blob-detector.cache.vector] :reload-all) + (:use [blob-detector.core] :reload-all) (:use [clojure.test])) -(deftest simple-detect - (let [accum (detect (fn [x] true) (fn [x y] 1) (blob-detector.cache.vector.Vector. [] 10 1))] - (is (= (count (:blobs accum)) - 1)) - (is (= (blob-detector.blob.Blob. 0 0 10 1 10) - (get (:blobs accum) 1))))) +(defn- all + [blobs expected] + (dorun (map #(is (some #{%} blobs)) expected))) +(deftest detect-line + (let [blobs (detect (fn [_ _] true) 10 1)] + (is (= (count blobs) 1)) + (is (every? (set blobs) [(blob-detector.blob.Blob. 0 0 10 1 10)])))) + +(deftest detect-multiple-lines + (let [blobs (detect (fn [x _] (not= 0 (mod x 3))) 10 1)] + (is (= (count blobs) 3)) + (all blobs [(blob-detector.blob.Blob. 1 0 2 1 2) + (blob-detector.blob.Blob. 4 0 2 1 2) + (blob-detector.blob.Blob. 7 0 2 1 2)]))) + +(deftest detect-multiple-columns + (let [blobs (detect (fn [x _] (not= 0 (mod x 3))) 9 9)] + (is (= (count blobs) 3)) + (all blobs [(blob-detector.blob.Blob. 1 0 2 9 18) + (blob-detector.blob.Blob. 4 0 2 9 18) + (blob-detector.blob.Blob. 7 0 2 9 18)]))) \ No newline at end of file
wiryadi/DynamicSQL
7e2da3a9ad6a63e3d2b172394ed8d0d62095d1d3
adding files from ALT.NET lightning talk
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12be9f6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +obj/ +bin/ +*.trx +*.suo \ No newline at end of file diff --git a/src/DynamicSQL/DynamicRow.cs b/src/DynamicSQL/DynamicRow.cs new file mode 100644 index 0000000..ea29e79 --- /dev/null +++ b/src/DynamicSQL/DynamicRow.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Dynamic; +using System.Data.SqlClient; + +namespace DynamicSQL +{ + public class DynamicRow: DynamicObject + { + SqlDataReader sqlDataReader; + + public DynamicRow(SqlDataReader sqlDataReader) + { + this.sqlDataReader = sqlDataReader; + } + + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + + try + { + var colIndex = sqlDataReader.GetOrdinal(binder.Name); + result = sqlDataReader.GetValue(colIndex); + + return true; + } + catch (IndexOutOfRangeException) + { + return base.TryGetMember(binder, out result); + } + } + + } + + public static class DynamicRowExtension + { + public static DynamicRow ToDynamicRow(this SqlDataReader target) + { + return new DynamicRow(target); + } + } +} diff --git a/src/DynamicSQL/DynamicSQL.csproj b/src/DynamicSQL/DynamicSQL.csproj new file mode 100644 index 0000000..e0c8caf --- /dev/null +++ b/src/DynamicSQL/DynamicSQL.csproj @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>8.0.30703</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{4C64F141-99FB-4B54-8D3B-7AD66EA67986}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>DynamicSQL</RootNamespace> + <AssemblyName>DynamicSQL</AssemblyName> + <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Core" /> + <Reference Include="System.Xml.Linq" /> + <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <Compile Include="DynamicRow.cs" /> + <Compile Include="DynamicSql.cs" /> + <Compile Include="ExpandoRow.cs" /> + <Compile Include="ExpandoSql.cs" /> + <Compile Include="ICoolSql.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/src/DynamicSQL/DynamicSql.cs b/src/DynamicSQL/DynamicSql.cs new file mode 100644 index 0000000..afea8b1 --- /dev/null +++ b/src/DynamicSQL/DynamicSql.cs @@ -0,0 +1,54 @@ +using System; +using System.Data.SqlClient; + +namespace DynamicSQL +{ + public class DynamicSql : IDynamicSQL + { + string connectionString; + + public DynamicSql (string connectionString) + { + this.connectionString = connectionString; + } + + public void EachRow(string queryString, Action<dynamic> act) + { + using (var connection = new SqlConnection(connectionString)) + { + var sqlCommand = new SqlCommand(queryString, connection); + connection.Open(); + + var sqlReader = sqlCommand.ExecuteReader(); + + while(sqlReader.Read()) + { + DynamicRow dynamicRow = sqlReader.ToDynamicRow(); + act(dynamicRow); + } + + sqlReader.Close(); + } + } + + public void FirstRow(string queryString, Action<dynamic> act) + { + using (var connection = new SqlConnection(connectionString)) + { + var sqlCommand = new SqlCommand(queryString, connection); + connection.Open(); + + using (var sqlReader = sqlCommand.ExecuteReader()) + { + if (sqlReader.Read()) + { + DynamicRow dynaRow = sqlReader.ToDynamicRow(); + act(dynaRow); + } + } + } + } + + + } +} diff --git a/src/DynamicSQL/ExpandoRow.cs b/src/DynamicSQL/ExpandoRow.cs new file mode 100644 index 0000000..9ae8013 --- /dev/null +++ b/src/DynamicSQL/ExpandoRow.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Dynamic; +using System.Data.SqlClient; + +namespace DynamicSQL +{ + public static class ExpandoRow + { + public static dynamic ToExpandoRow(this SqlDataReader sqlReader) + { + var expandoRow = new ExpandoObject(); + + object[] rowValues = GetRowValues(sqlReader); + + for (int i = 0; i < sqlReader.FieldCount; i++) + { + string columnName = sqlReader.GetName(i); + expandoRow.AddDynamicProperty(columnName, rowValues[i]); + } + + return expandoRow; + } + + private static object[] GetRowValues(SqlDataReader sqlReader) + { + object[] rowValues = new object[sqlReader.FieldCount]; + sqlReader.GetValues(rowValues); + return rowValues; + } + + private static void AddDynamicProperty(this ExpandoObject target, string propertyName, object value) + { + IDictionary<string, object> expandoAsDictionary = target; + expandoAsDictionary[propertyName] = value; + } + } +} diff --git a/src/DynamicSQL/ExpandoSql.cs b/src/DynamicSQL/ExpandoSql.cs new file mode 100644 index 0000000..0f02326 --- /dev/null +++ b/src/DynamicSQL/ExpandoSql.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Data.SqlClient; +using System.Dynamic; + +namespace DynamicSQL +{ + public class ExpandoSql: IDynamicSQL + { + private string connectionString; + + public ExpandoSql(string connectionString) + { + this.connectionString = connectionString; + } + + public void EachRow(string queryString, Action<dynamic> act) + { + using (var connection = new SqlConnection(connectionString)) + { + var sqlCommand = new SqlCommand(queryString, connection); + connection.Open(); + + var sqlReader = sqlCommand.ExecuteReader(); + + while(sqlReader.Read()) + { + dynamic dynaRow = sqlReader.ToExpandoRow(); + act(dynaRow); + } + + sqlReader.Close(); + } + } + + public void FirstRow(string queryString, Action<dynamic> act) + { + using (var connection = new SqlConnection(connectionString)) + { + var sqlCommand = new SqlCommand(queryString, connection); + connection.Open(); + + using (var sqlReader = sqlCommand.ExecuteReader()) + { + if (sqlReader.Read()) + { + dynamic dynaRow = sqlReader.ToExpandoRow(); + act(dynaRow); + } + } + } + } + + } + + +} diff --git a/src/DynamicSQL/ICoolSql.cs b/src/DynamicSQL/ICoolSql.cs new file mode 100644 index 0000000..b37e872 --- /dev/null +++ b/src/DynamicSQL/ICoolSql.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace DynamicSQL +{ + public interface IDynamicSQL + { + void EachRow(string queryString, Action<dynamic> act); + void FirstRow(string queryString, Action<dynamic> act); + } +} diff --git a/src/DynamicSQL/Properties/AssemblyInfo.cs b/src/DynamicSQL/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4a344ad --- /dev/null +++ b/src/DynamicSQL/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DynamicSQL")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("DynamicSQL")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b83ef6b7-310d-4066-888a-02b2e5e57761")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/DynamicSQLTests/DynamicSQLTests.csproj b/src/DynamicSQLTests/DynamicSQLTests.csproj new file mode 100644 index 0000000..ea02852 --- /dev/null +++ b/src/DynamicSQLTests/DynamicSQLTests.csproj @@ -0,0 +1,67 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion> + </ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{7DF7EB40-0D5F-4F48-B8F0-DD7A7A56BA56}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>DynamicSQLTests</RootNamespace> + <AssemblyName>DynamicSQLTests</AssemblyName> + <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> + <FileAlignment>512</FileAlignment> + <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + </PropertyGroup> + <ItemGroup> + <Reference Include="Microsoft.CSharp" /> + <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" /> + <Reference Include="System" /> + <Reference Include="System.Core"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + </ItemGroup> + <ItemGroup> + <CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies"> + <Visible>False</Visible> + </CodeAnalysisDependentAssemblyPaths> + </ItemGroup> + <ItemGroup> + <Compile Include="DynamicSqlTests.cs" /> + <Compile Include="ExpandoSqlTests.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + </ItemGroup> + <ItemGroup> + <ProjectReference Include="..\DynamicSQL\DynamicSQL.csproj"> + <Project>{4C64F141-99FB-4B54-8D3B-7AD66EA67986}</Project> + <Name>DynamicSQL</Name> + </ProjectReference> + </ItemGroup> + <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/src/DynamicSQLTests/DynamicSqlTests.cs b/src/DynamicSQLTests/DynamicSqlTests.cs new file mode 100644 index 0000000..ba3afb6 --- /dev/null +++ b/src/DynamicSQLTests/DynamicSqlTests.cs @@ -0,0 +1,59 @@ +using System; +using System.Text; +using System.Collections.Generic; +using System.Linq; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using DynamicSQL; + +namespace DynamicTest +{ + /// <summary> + /// Require installation of Northwind sample database on local sql server + /// </summary> + [TestClass] + public class DynamicSqlTests + { + private const string connectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI;"; + + + [TestMethod] + public void SmokeTest() + { + var sql = new DynamicSql(connectionString); + + sql.EachRow("select * from Customers order by CustomerID", + r => Console.WriteLine("{0} - {1}", r.CompanyName, r.ContactName)); + + } + + + [TestMethod] + public void ShouldPerformActionToEachRow() + { + var sql = new DynamicSql(connectionString); + + sql.EachRow("select * from Customers order by CustomerID", + r => Console.WriteLine("{0} - {1}", r.CompanyName, r.ContactName)); + + decimal total = 0.0m; + + sql.EachRow("select * from [Order Details] where OrderID = 10251", + r => total += r.Quantity * r.UnitPrice * (decimal)(1 - r.Discount)); + + Assert.AreEqual(654.06m, total); + } + + [TestMethod] + public void ShouldPerformActionToFirstRow() + { + var sql = new DynamicSql(connectionString); + + string firstCustomer = ""; + + sql.FirstRow("select * from Customers order by CustomerID", + r => firstCustomer = r.CustomerID); + + Assert.AreEqual("ALFKI", firstCustomer); + } + } +} diff --git a/src/DynamicSQLTests/ExpandoSqlTests.cs b/src/DynamicSQLTests/ExpandoSqlTests.cs new file mode 100644 index 0000000..557b4d7 --- /dev/null +++ b/src/DynamicSQLTests/ExpandoSqlTests.cs @@ -0,0 +1,59 @@ +using System; +using System.Text; +using System.Collections.Generic; +using System.Linq; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using DynamicSQL; + +namespace DynamicTest +{ + /// <summary> + /// Summary description for CoolSqlTests + /// </summary> + [TestClass] + public class ExpandoSqlTests + { + private const string connectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI;"; + + + [TestMethod] + public void SmokeTest() + { + var sql = new ExpandoSql(connectionString); + + sql.EachRow("select * from Customers order by CustomerID", + r => Console.WriteLine("{0} - {1}", r.CompanyName, r.ContactName)); + + } + + + [TestMethod] + public void ShouldPerformActionToEachRow() + { + var sql = new ExpandoSql(connectionString); + + sql.EachRow("select * from Customers order by CustomerID", + r => Console.WriteLine("{0} - {1}", r.CompanyName, r.ContactName)); + + decimal total = 0.0m; + + sql.EachRow("select * from [Order Details] where OrderID = 10251", + r => total += r.Quantity * r.UnitPrice * (decimal)(1 - r.Discount)); + + Assert.AreEqual(654.06m, total); + } + + [TestMethod] + public void ShouldPerformActionToFirstRow() + { + var sql = new ExpandoSql(connectionString); + + string firstCustomer = ""; + + sql.FirstRow("select * from Customers order by CustomerID", + r => firstCustomer = r.CustomerID); + + Assert.AreEqual("ALFKI", firstCustomer); + } + } +} diff --git a/src/DynamicSQLTests/Properties/AssemblyInfo.cs b/src/DynamicSQLTests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ef37c45 --- /dev/null +++ b/src/DynamicSQLTests/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DynamicSQLTests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("DynamicSQLTests")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("eed8d344-0926-4e9e-a971-4836e39446ad")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/DynamicSql.sln b/src/DynamicSql.sln new file mode 100644 index 0000000..7c25077 --- /dev/null +++ b/src/DynamicSql.sln @@ -0,0 +1,36 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DynamicSQL", "DynamicSQL\DynamicSQL.csproj", "{4C64F141-99FB-4B54-8D3B-7AD66EA67986}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DynamicSQLTests", "DynamicSQLTests\DynamicSQLTests.csproj", "{7DF7EB40-0D5F-4F48-B8F0-DD7A7A56BA56}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{374431B0-576B-4423-90DD-076E72C1C59D}" + ProjectSection(SolutionItems) = preProject + DynamicSql.vsmdi = DynamicSql.vsmdi + Local.testsettings = Local.testsettings + TraceAndTestImpact.testsettings = TraceAndTestImpact.testsettings + EndProjectSection +EndProject +Global + GlobalSection(TestCaseManagementSettings) = postSolution + CategoryFile = DynamicSql.vsmdi + EndGlobalSection + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4C64F141-99FB-4B54-8D3B-7AD66EA67986}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C64F141-99FB-4B54-8D3B-7AD66EA67986}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C64F141-99FB-4B54-8D3B-7AD66EA67986}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C64F141-99FB-4B54-8D3B-7AD66EA67986}.Release|Any CPU.Build.0 = Release|Any CPU + {7DF7EB40-0D5F-4F48-B8F0-DD7A7A56BA56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7DF7EB40-0D5F-4F48-B8F0-DD7A7A56BA56}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7DF7EB40-0D5F-4F48-B8F0-DD7A7A56BA56}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7DF7EB40-0D5F-4F48-B8F0-DD7A7A56BA56}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/src/DynamicSql.vsmdi b/src/DynamicSql.vsmdi new file mode 100644 index 0000000..21ef94c --- /dev/null +++ b/src/DynamicSql.vsmdi @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<TestLists xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"> + <TestList name="Lists of Tests" id="8c43106b-9dc1-4907-a29f-aa66a61bf5b6"> + <RunConfiguration id="956e23ad-908b-45ce-8def-ef1e400135b4" name="Local" storage="local.testsettings" type="Microsoft.VisualStudio.TestTools.Common.TestRunConfiguration, Microsoft.VisualStudio.QualityTools.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> + </TestList> +</TestLists> \ No newline at end of file diff --git a/src/Local.testsettings b/src/Local.testsettings new file mode 100644 index 0000000..7adda3c --- /dev/null +++ b/src/Local.testsettings @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="UTF-8"?> +<TestSettings name="Local" id="956e23ad-908b-45ce-8def-ef1e400135b4" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"> + <Description>These are default test settings for a local test run.</Description> + <Deployment enabled="false" /> + <Execution> + <TestTypeSpecific /> + <AgentRule name="Execution Agents"> + </AgentRule> + </Execution> +</TestSettings> \ No newline at end of file diff --git a/src/TraceAndTestImpact.testsettings b/src/TraceAndTestImpact.testsettings new file mode 100644 index 0000000..1264cf6 --- /dev/null +++ b/src/TraceAndTestImpact.testsettings @@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<TestSettings name="Trace and Test Impact" id="82ecaaff-67d9-41d1-a887-71cad732f00c" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010"> + <Description>These are test settings for Trace and Test Impact.</Description> + <Execution> + <TestTypeSpecific /> + <AgentRule name="Execution Agents"> + <DataCollectors> + <DataCollector uri="datacollector://microsoft/SystemInfo/1.0" assemblyQualifiedName="Microsoft.VisualStudio.TestTools.DataCollection.SystemInfo.SystemInfoDataCollector, Microsoft.VisualStudio.TestTools.DataCollection.SystemInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" friendlyName="System Information"> + </DataCollector> + <DataCollector uri="datacollector://microsoft/ActionLog/1.0" assemblyQualifiedName="Microsoft.VisualStudio.TestTools.ManualTest.ActionLog.ActionLogPlugin, Microsoft.VisualStudio.TestTools.ManualTest.ActionLog, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" friendlyName="Actions"> + </DataCollector> + <DataCollector uri="datacollector://microsoft/HttpProxy/1.0" assemblyQualifiedName="Microsoft.VisualStudio.TraceCollector.HttpProxyCollector, Microsoft.VisualStudio.TraceCollector, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" friendlyName="ASP.NET Client Proxy for IntelliTrace and Test Impact"> + </DataCollector> + <DataCollector uri="datacollector://microsoft/TestImpact/1.0" assemblyQualifiedName="Microsoft.VisualStudio.TraceCollector.TestImpactDataCollector, Microsoft.VisualStudio.TraceCollector, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" friendlyName="Test Impact"> + </DataCollector> + <DataCollector uri="datacollector://microsoft/TraceDebugger/1.0" assemblyQualifiedName="Microsoft.VisualStudio.TraceCollector.TraceDebuggerDataCollector, Microsoft.VisualStudio.TraceCollector, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" friendlyName="IntelliTrace"> + </DataCollector> + </DataCollectors> + </AgentRule> + </Execution> +</TestSettings> \ No newline at end of file
colinramsay/needs-fetching
456087bd4fc2269f59590d422560f77c5fb7bcbf
passing specs
diff --git a/README b/README index e69de29..964fc92 100644 --- a/README +++ b/README @@ -0,0 +1,16 @@ +Ruby mixin for open-uri to check to see if a url needs fetching based on the last time you fetched it and the last etag you got. + +WORK IN PROGRESS! + +Usage +----- + +require 'open-uri' +result = open("http://example.com") +result.needs_fetching?(last_fetched_date, last_etag) + +Todo +---- + +- create gem +- validate & improve specs \ No newline at end of file diff --git a/lib/needs_fetching.rb b/lib/needs_fetching.rb index c87efc6..333b4f6 100644 --- a/lib/needs_fetching.rb +++ b/lib/needs_fetching.rb @@ -1,7 +1,29 @@ +require 'ruby-debug' require 'open-uri' module OpenURI::Meta def needs_fetching?(last_retrieved, last_etag) - false + + expires = self.meta['expires'] + etag = self.meta['etag'] + last_modified = self.meta['last-modified'] + + if(last_modified == nil and etag == nil and expires == nil) + return true + end + + if(etag && etag == last_etag) + return false + end + + if(expires and Date.parse(expires) >= Date.today) + return false + end + + if(last_modified and Date.parse(last_modified) < last_retrieved) + return false + end + + return true end end \ No newline at end of file diff --git a/spec/lib/needs_fetching_spec.rb b/spec/lib/needs_fetching_spec.rb index fe15264..9d34cd4 100644 --- a/spec/lib/needs_fetching_spec.rb +++ b/spec/lib/needs_fetching_spec.rb @@ -1,26 +1,52 @@ require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'fakeweb' describe OpenURI::Meta do before do @url = "http://example.com/test1" - FakeWeb.register_uri(:get, @url, :body => "Hello World!") - @result = open(@url) end it "will return true if no past data provided" do - @result.needs_fetching?(nil, nil).should be_false + FakeWeb.register_uri(:get, @url, :body => "Hello World!") + @result = open(@url) + @result.needs_fetching?(nil, nil).should be_true end - it "will return true if expires has passed" + it "will return true if expires has passed" do + FakeWeb.register_uri(:get, @url, :body => "Hello World!", :expires => 'Thu, 01 Dec 1994 16:00:00 GMT') + @result = open(@url) + @result.needs_fetching?(nil, nil).should be_true + end - it "will return true if last modified is newer than last fetched" + it "will return true if last modified is newer than last fetched" do + FakeWeb.register_uri(:get, @url, :body => "Hello World!", :last_modified => 'Thu, 01 Dec 2995 16:00:00 GMT') + @result = open(@url) + @result.needs_fetching?(Date.parse('Thu, 01 Dec 1994 13:00:00 GMT'), nil).should be_true + end - it "will return false if etag matches" + it "will return true if last modified is not available" do + FakeWeb.register_uri(:get, @url, :body => "Hello World!") + @result = open(@url) + @result.needs_fetching?(Date.parse('Thu, 01 Dec 1994 13:00:00 GMT'), 'blablabla').should be_true + end - it "will return false if last modified is older than last fetched" + it "will return false if etag matches" do + FakeWeb.register_uri(:get, @url, :body => "Hello World!", :etag => 'blablabla') + @result = open(@url) + @result.needs_fetching?(Date.parse('Thu, 01 Dec 1994 13:00:00 GMT'), 'blablabla').should be_false + end - it "will return true if last modified is not provided" + it "will return false if last modified is older than last fetched" do + FakeWeb.register_uri(:get, @url, :body => "Hello World!", :last_modified => 'Thu, 01 Dec 1995 16:00:00 GMT') + @result = open(@url) + @result.needs_fetching?(Date.parse('Thu, 01 Dec 1996 13:00:00 GMT'), nil).should be_false + end + + it "will return false if expires has not passed" do + FakeWeb.register_uri(:get, @url, :body => "Hello World!", :expires => 'Thu, 01 Dec 2994 16:00:00 GMT') + @result = open(@url) + @result.needs_fetching?(Date.parse('Thu, 01 Dec 1994 13:00:00 GMT'), nil).should be_false + end end \ No newline at end of file
ralphleon/Pollinator
ea5f66d155790e1bdefb22e803cb4412137a7caa
More comments
diff --git a/admin/index.php b/admin/index.php index 6cc0d6d..a1a94ef 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,13 +1,18 @@ <? $title = "Secret Admin Section"; include("../header.php"); include("../pollinator/admin_helper.php") ?> - - <p>Respondents to the poll:</p> - <div id="tableHolder"> - <? printResultsTable() ?> - </div> +<p> Welcome to the admin section where you can get into the bolts of your poll! What are you interested in?</p> + +<ul> + <li><a href="editor.php">Editing</a> the poll's questions...</li> + <li><a href="print.php"> Viewing</a> all of the respondent answers...</li> +</ul> +<h3>Quick Summary</h3> + +<p> So far you've had <strong> <? numberOfRespondents() ?> </strong> people respond!</p> + <? include("../footer.php"); ?> \ No newline at end of file diff --git a/css/admin.css b/css/admin.css index 4659288..375ffbb 100644 --- a/css/admin.css +++ b/css/admin.css @@ -1,98 +1,101 @@ /* Table view */ #tableHolder { - overflow: scroll; - width:600px; } table.admin { border-collapse: collapse; } +table.admin thead th{ + max-height:50px; + text-align:left; +} + table.admin thead tr { padding:3px; margin:3px; border-bottom:2px solid #666; font-weight:bold; } table.admin tbody tr { padding:3px; margin:3px; border-bottom:1px solid #666; } table.admin td { padding:5px; } /* Editor controls */ #controls{ clear:both; margin-top:20px; float:right; } div.question { margin:10px; margin-top:40px; } div.question div.main{ background-color: #AAA; padding:10px; overflow: auto; } div.question div.opts { background-color: #999; padding:10px; clear:both; overflow: auto; } div.question label { color:#333; display:block; text-align:right; width:140px; float:left; } div.question .small { color:#444; display:block; font-size:11px; font-weight:normal; text-align:right; width:140px; } div.question input,textarea,select{ float:left; font-size:12px; padding:4px 2px; border:solid 1px #aacfe4; width:200px; margin:2px 0 20px 10px; } div.question textarea{ width:60%; } div.question div.delete { display:inline; float:right; margin-right:5px; background:#FF6666; clear:both; padding:5px 10px 5px 10px; } div.question div.delete:hover { background:#FF3333; } div.delete a{ font-family:sans-serif; color:#FFF; text-decoration:none; } diff --git a/css/main.css b/css/main.css index d61dd73..51e3dc4 100644 --- a/css/main.css +++ b/css/main.css @@ -1,63 +1,68 @@ body { background:#222; - font:14px Georgia; + font-family:Georgia; +} + +h3 { + margin-bottom:0px; + padding-bottom:0px; } label.header{ font:16px Georgia; display:block; margin:15px 0 4px 0; } input.submit{ float:right; } input.text{ width:200px; } form{ padding-bottom:20px; } #container{ width:500px; margin: 10px 50px 10px 50px; padding:30px; background:#EEE; overflow: auto; -moz-border-radius: 5px; -webkit-border-radius: 5px; } #header span { overflow:auto; float:left; margin-left:10px; } #header h1{ color:#333; font-size:180%; - padding-top:5px; + padding-top:0px; margin-bottom:0; } #header h2 { display:inline; color:#444; font-size:150%; margin-top:20px; } #header img{ display:inline; float:left; height:90px; width:90px; } #header { overflow:auto; clear:both; } \ No newline at end of file diff --git a/pollinator/admin_helper.php b/pollinator/admin_helper.php index 472c98d..e5950bc 100644 --- a/pollinator/admin_helper.php +++ b/pollinator/admin_helper.php @@ -1,42 +1,55 @@ <? include("../pollinator/database_helper.php"); /** * Print the results table, which stores all of the results */ function printResultsTable(){ print '<table class="admin"><thead>' . "\n"; connect(); // Print the header $q = "SELECT * FROM ". QUESTIONS_TABLE; $result = mysql_query($q) or mysql_err($q); - print "<tr><td>ID</td>"; + print "<tr><th>ID</th>"; while($row = mysql_fetch_assoc($result) ){ - print "<td>" . $row['content'] ."</td>"; + print "<th>" . $row['content'] ."</th>"; } - print '</tr></thead><tbody>'; + print '</tr></thead><tbody class="scrollContent">'; // Print the actual results $q = "SELECT * FROM " . RESULTS_TABLE; $result = mysql_query($q) or mysql_err($q); // print out the header, access questions database for short questions while($row = mysql_fetch_row($result) ){ print "<tr>"; foreach($row as $key => $attr){ print "<td>" . $attr . "</td>"; } print "</tr>"; } print '</tbody></table>' ."\n"; disconnect(); } +/** Prints the number of people that have responded to the poll */ +function numberOfRespondents(){ + connect(); + + $q = "SELECT * FROM ". RESULTS_TABLE; + $result = mysql_query($q) or mysql_err($q); + + print mysql_num_rows($result); + + disconnect(); +} + + ?> \ No newline at end of file diff --git a/pollinator/editor_helper.php b/pollinator/editor_helper.php index 31fdac1..2b9893c 100644 --- a/pollinator/editor_helper.php +++ b/pollinator/editor_helper.php @@ -1,67 +1,74 @@ <? include("database_helper.php"); + /** + * Prints out the questions editor, with all of the databases's + * current data loaded into it. + */ function printQuestionsEditor(){ $link = connect(); $q = "SELECT * FROM ". QUESTIONS_TABLE; - $result = mysql_query($q); - if (!$result) err("error with query...\n Query=$q"); + $result = mysql_query($q) or mysql_err($q); while ( $row = mysql_fetch_array($result) ) { printEditor($row); } } + /** + * Prints an individual editor, for the $row give. The row should be a key-value pair + * from the questions mysql database. + */ function printEditor($row){ $content = $row['content']; $type = $row['type']; $opts = $row['opts']; $hideOpts = "style=\"display:none;\""; if($type == Q_MULTI || $type == Q_MULTI_EXC) $hideOpts= ""; print <<< EOF <div class="question"> <div class="main"> <label>Question <span class="small">The main question</span></label> <textarea name="content">$content</textarea> <label>Type<span class="small">Type of the question</span></label> <select name="type"> EOF; // This should obviously be a list, ugly code if($type != Q_TEXT) print "<option value=\"0\">Free text</option>"; else print "<option value=\"0\" selected=\"true\">Free text</option>"; if($type != Q_YES_NO) print "<option value=\"1\">Yes / No </option>"; else print "<option value=\"1\" selected=\"true\">Yes / No </option>"; if($type != Q_MULTI) print "<option value=\"2\">List (select any)</option>"; else print "<option value=\"2\" selected=\"true\">List (select any)</option>"; if($type != Q_MULTI_EXC) print "<option value=\"3\">List (select one)</option>"; else print "<option value=\"3\" selected=\"true\">List (select one)</option>"; print <<< EOF </select> </div> <div class="opts" $hideOpts> <label>List<span class="small">Newline separated</span></label> <textarea name="opts">$opts</textarea> </div> <div class="delete"> <a href="#">Delete</a> </div> </div> EOF; } ?> \ No newline at end of file diff --git a/pollinator/editor_update.php b/pollinator/editor_update.php index da6f9e3..29f4196 100644 --- a/pollinator/editor_update.php +++ b/pollinator/editor_update.php @@ -1,46 +1,45 @@ <? /** - Callback code for the editor AJAX. This code takes the edited questions - and adds them to the questions table. Currently it drops the entire - results table (lazy) to avoid conflicts and refactoring. This could be added - later by using hash values instead of question #. - */ + * Callback code for the editor AJAX. This code takes the edited questions + * and adds them to the questions table. Currently it drops the entire + * results table (lazy) to avoid conflicts and refactoring. This could be added + * later by using hash values instead of question #. + */ include("database_helper.php"); // Unwrap the JSON results $data = $_POST['questions']; print_r($data); connect(); - // Dump all questions besides for the 2 key questions (name,email) + // Dump all questions, add the new questions to a sql query string $q = "TRUNCATE TABLE " . QUESTIONS_TABLE; $result = mysql_query($q) or mysql_err($q); $questions_sql = ""; $i = 0; foreach($data as $question){ - $content = $question["content"]; - $opts = $question["opts"]; + $content = mysql_real_escape_string($question["content"]); + $opts = mysql_real_escape_string($question["opts"]); $type = $question["type"]; $q = "INSERT into " . QUESTIONS_TABLE . "(type,content,opts) VALUES('$type','$content','$opts')"; mysql_query($q) or mysql_err($q); $questions_sql = $questions_sql . ",question" . ++$i . " TEXT"; } - // insert new records for each query // Make a mysql CREATE TABLE query for the results table $q = "DROP TABLE IF EXISTS " . RESULTS_TABLE; mysql_query($q) or mysql_err($q); $q = "CREATE TABLE " . RESULTS_TABLE . "(id INT NOT NULL AUTO_INCREMENT," . "PRIMARY KEY(id)" . $questions_sql . ")"; mysql_query($q) or mysql_err($q); - // Drop the old table and make a new results table + // We should return an error/sucess method here ?> diff --git a/pollinator/setup.php b/pollinator/setup.php index 7f7a37a..6f9a2ab 100644 --- a/pollinator/setup.php +++ b/pollinator/setup.php @@ -1,24 +1,23 @@ <? - /** Simple helper script to setupt the databases, could allow usernames, etc later */ - + /** Simple helper script to setup the databases, could allow usernames, etc later */ include("database_helper.php"); connect(); /** Very simple setup script */ $q = "DROP TABLE IF EXISTS " . RESULTS_TABLE; $r = mysql_query($q) or mysql_err($q); $q = "DROP TABLE IF EXISTS " . QUESTIONS_TABLE; $r = mysql_query($q) or mysql_err($q); $q = "CREATE TABLE " . QUESTIONS_TABLE . "(id INT NOT NULL AUTO_INCREMENT," . "PRIMARY KEY(id)," . "type INT, content TEXT, opts TEXT)"; $r = mysql_query($q) or mysql_err($q); disconnect(); ?> <h1>Databases created successfully!</h1>
ralphleon/Pollinator
f48f426155788e5a7628b1ad2a3fc75b9a7b2627
Added setup files
diff --git a/admin/editor.php b/admin/editor.php index 81a9fcd..25f449b 100644 --- a/admin/editor.php +++ b/admin/editor.php @@ -1,50 +1,50 @@ <? $title = "Question Editor"; include("../header.php") ?> <script type="text/javascript" src="/questionator/js/jquery.js"></script> <script type="text/javascript" src="/questionator/js/editor.js"></script> <script type="text/javascript" src="/questionator/js/jquery.boxy.js"></script> <form class="boxy" id="editForm" action=""> <div id="questionsBlock"> - <!-- Sample Question --> + <!-- Sample Question, cloned in js --> <div class="question" style="display:none"> <div class="main"> <label>Question <span class="small">The main question</span></label> <textarea name="content"></textarea> <label>Type<span class="small">Type of the question</span></label> <select name="type"> <option value="0" selected="true">Free text</option>"; <option value="1">Yes / No </option>"; <option value="2">List (select any)</option>"; <option value="3">List (select one)</option>"; </select> </div> <div class="opts" style="display:none"> <label>List<span class="small">Newline separated</span></label> <textarea name="opts"></textarea> </div> <div class="delete"> <a href="#">Delete</a> </div> </div> <? include("../pollinator/editor_helper.php"); printQuestionsEditor(); ?> </div> <div id="controls"> <input id="add" type="button" value="Add"> <input id="submit" type="button" value="submit"/> </div> </form> <? include("../footer.php");?> \ No newline at end of file diff --git a/pollinator/question_viewer.php b/pollinator/question_viewer.php index 80a91be..f0c5d76 100644 --- a/pollinator/question_viewer.php +++ b/pollinator/question_viewer.php @@ -1,137 +1,137 @@ <? include("database_helper.php"); /** * Prints all questions stored in the Mysql database */ function printQuestions(){ $link = connect(); $q = "SELECT * FROM ". QUESTIONS_TABLE; - $result = mysql_query($q) or mysql_err($q); + $result = mysql_query($q) or err("No database configured yet, please use the admin interface!"); while ( $row = mysql_fetch_array($result) ) { printQuestion($row); } disconnect(); } /** * Takes an array that has "type","content", and "opts" defined and prints * an html form element based on these values. This array is normally a row from * the QUESTIONS_TABLE mysql table. */ function printQuestion($row){ // All the questions have the same sort of title print '<div> <label class="header">' . $row["content"] . "</label>"; $id = $row["id"]; $name = "question". $id; // But they differ in how the user responds to them switch($row["type"]) { case Q_YES_NO: printf('<input class="validate[required] radio" value="yes" type="radio" id="%s" name="%s"><label>Yes</label><br/>',$name,$name); printf('<input class="validate[required] radio" value="no" type="radio" id="%s" name="%s"><label>No</label><br/>',$name,$name); break; case Q_MULTI: $opts = explode( "," , $row['opts']); foreach($opts as $opt){ print '<input type="checkbox" name="' . $name . $opt .'"/>'; print "<label>$opt</label><br/>"; } break; case Q_MULTI_EXC: $opts = explode( "," , $row['opts']); foreach($opts as $opt){ printf('<input class="validate[required] radio" value="%s" type="radio" id="%s" name="%s"/>',$opt,$name,$name); print "<label>$opt</label><br/>"; } break; case Q_TEXT: printf('<input class="validate[required,length[1,100]] text-input" type="text" id="%s" name="%s"/>',$name,$name); break; } print "</div>\n"; } /** * Process Questions */ function processResults(){ connect(); // Loop through the dynamic fields $q = "SELECT * FROM ". QUESTIONS_TABLE; $result = mysql_query($q) or mysql_err($q); // store the column names, and their answers $qResults = Array(); while( $row = mysql_fetch_array($result) ) { $id = $row['id']; $name = "question" . $id; $content = $row["content"]; $r = ""; switch($row["type"]){ // multiple check boxes are a pain in the ass. case Q_MULTI: $opts = explode(",", $row['opts']); foreach($opts as $opt){ //If the value is set, then it was checked if(isset($_POST[ $name . $opt])){ $r = $r . $opt . ","; } } break; // everything else can use a standard case default: // try to gather the result for the question $r = mysql_real_escape_string($_POST[$name]); break; } print "<p><strong>$content</strong><br/>$r</p>"; $qResults[$name] = $r; } // end while $cols = ""; $values = ""; foreach($qResults as $key => $val) { $cols = $cols . $key . ","; $values = $values . "'" . $val . "'" . ","; } $cols = rtrim($cols,","); $values = rtrim($values,","); // Gaurd against SQL injection atttacks $q = sprintf("INSERT into %s (%s) VALUES(%s)", RESULTS_TABLE,$cols,$values); $result = mysql_query($q) or mysql_err($q); disconnect(); } ?> \ No newline at end of file diff --git a/pollinator/setup.php b/pollinator/setup.php new file mode 100644 index 0000000..7f7a37a --- /dev/null +++ b/pollinator/setup.php @@ -0,0 +1,24 @@ +<? + /** Simple helper script to setupt the databases, could allow usernames, etc later */ + + include("database_helper.php"); + connect(); + + /** Very simple setup script */ + $q = "DROP TABLE IF EXISTS " . RESULTS_TABLE; + $r = mysql_query($q) or mysql_err($q); + + $q = "DROP TABLE IF EXISTS " . QUESTIONS_TABLE; + $r = mysql_query($q) or mysql_err($q); + + $q = "CREATE TABLE " . QUESTIONS_TABLE + . "(id INT NOT NULL AUTO_INCREMENT," + . "PRIMARY KEY(id)," + . "type INT, content TEXT, opts TEXT)"; + + $r = mysql_query($q) or mysql_err($q); + + disconnect(); +?> + +<h1>Databases created successfully!</h1> diff --git a/questionator.tmproj b/questionator.tmproj index eb3b399..819e034 100644 --- a/questionator.tmproj +++ b/questionator.tmproj @@ -1,169 +1,215 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>currentDocument</key> <string>admin/editor.php</string> <key>documents</key> <array> <dict> <key>expanded</key> <true/> <key>name</key> <string>Questionator</string> <key>regexFolderFilter</key> <string>!.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$</string> <key>sourceDirectory</key> <string></string> </dict> </array> <key>fileHierarchyDrawerWidth</key> <integer>208</integer> <key>metaData</key> <dict> <key>admin/editor.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>38</integer> <key>line</key> <integer>29</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> - <integer>0</integer> + <integer>12</integer> </dict> <key>admin/index.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>31</integer> <key>line</key> <integer>12</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> <key>css/main.css</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>16</integer> <key>line</key> <integer>46</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> <key>footer.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>14</integer> <key>line</key> <integer>1</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> <key>header.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>7</integer> + <integer>6</integer> <key>line</key> - <integer>29</integer> + <integer>14</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> <key>index.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>0</integer> <key>line</key> <integer>30</integer> </dict> <key>columnSelection</key> <false/> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> <key>selectFrom</key> <dict> <key>column</key> <integer>28</integer> <key>line</key> <integer>31</integer> </dict> <key>selectTo</key> <dict> <key>column</key> <integer>0</integer> <key>line</key> <integer>30</integer> </dict> </dict> + <key>pollinator/config.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>25</integer> + <key>line</key> + <integer>6</integer> + </dict> + <key>columnSelection</key> + <false/> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>0</integer> + <key>selectFrom</key> + <dict> + <key>column</key> + <integer>36</integer> + <key>line</key> + <integer>11</integer> + </dict> + <key>selectTo</key> + <dict> + <key>column</key> + <integer>25</integer> + <key>line</key> + <integer>6</integer> + </dict> + </dict> <key>pollinator/question_viewer.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>0</integer> + <integer>2</integer> <key>line</key> - <integer>75</integer> + <integer>15</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> - <integer>62</integer> + <integer>71</integer> + </dict> + <key>pollinator/setup.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>1</integer> + <key>line</key> + <integer>3</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>0</integer> </dict> <key>process.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>8</integer> + <integer>13</integer> <key>line</key> - <integer>4</integer> + <integer>11</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> </dict> <key>openDocuments</key> <array> <string>index.php</string> <string>process.php</string> <string>footer.php</string> <string>pollinator/question_viewer.php</string> + <string>pollinator/setup.php</string> <string>css/main.css</string> <string>admin/index.php</string> <string>header.php</string> <string>admin/editor.php</string> + <string>pollinator/config.php</string> </array> <key>showFileHierarchyDrawer</key> <true/> <key>windowFrame</key> - <string>{{833, 367}, {1072, 733}}</string> + <string>{{685, 438}, {1072, 733}}</string> </dict> </plist>
ralphleon/Pollinator
c1521f931982ea729ee41bd83ee5002509108082
Added configuration file
diff --git a/pollinator/config.php b/pollinator/config.php new file mode 100644 index 0000000..1e53be0 --- /dev/null +++ b/pollinator/config.php @@ -0,0 +1,14 @@ +<? +/** Configuration file for pollinator! */ + +// Database name +define("DB_SERVER","localhost"); +define("DB", "questionator"); +define("DB_USER","root"); +define("DB_PASS","root"); + +// Table names (these should be ok) +define("QUESTIONS_TABLE" , "questions" ); +define("RESULTS_TABLE" , "results"); + +?> \ No newline at end of file diff --git a/pollinator/database_helper.php b/pollinator/database_helper.php index f65901e..a8146d3 100644 --- a/pollinator/database_helper.php +++ b/pollinator/database_helper.php @@ -1,44 +1,42 @@ <? -// Constants -define("DATABASE", "questionator"); -define("QUESTIONS_TABLE" , "questions" ); -define("RESULTS_TABLE" , "results"); +/** This file defines functions that allow for database access. Please use "config.php" + * to setup pollster for your specific database + */ + +include("config.php"); // Differnt values for the question types define('Q_TEXT',0); define('Q_YES_NO',1); define('Q_MULTI',2); define('Q_MULTI_EXC',3); +/** Connects to a database, we don't need a link for our purposes */ function connect(){ - $link = mysql_connect('localhost', 'root', 'root'); - - if(!$link) err("failure connecting to database..."); + mysql_connect(DB_SERVER, DB_USER, DB_PASS) or err("failure connecting to database..."); - if(!@mysql_select_db(DATABASE,$link)){ - err("failure selecting the database <strong>" . DATABASE . "</strong>..."); + if(!@mysql_select_db(DB)){ + err("failure selecting the database <strong>" . DB . "</strong>..."); } - - return $link; } function disconnect(){ mysql_close(); } function err($string){ print "Error: " . $string . "<br/>"; exit(); } function mysql_err($q){ print "Error in Query: " . $q. "<br/>"; print "MySQL says: \"" . mysql_error() . "\""; exit(); } ?>
ralphleon/Pollinator
5764a23f18c0fc08b37659021ba5d066e7c0822a
Finalization
diff --git a/admin/editor.php b/admin/editor.php index 272de81..81a9fcd 100644 --- a/admin/editor.php +++ b/admin/editor.php @@ -1,55 +1,50 @@ -<? include("header.php") ?> +<? $title = "Question Editor"; include("../header.php") ?> <script type="text/javascript" src="/questionator/js/jquery.js"></script> <script type="text/javascript" src="/questionator/js/editor.js"></script> <script type="text/javascript" src="/questionator/js/jquery.boxy.js"></script> - -<div id="container"> - - <h1>Administration</h1> <form class="boxy" id="editForm" action=""> <div id="questionsBlock"> <!-- Sample Question --> <div class="question" style="display:none"> <div class="main"> <label>Question <span class="small">The main question</span></label> <textarea name="content"></textarea> <label>Type<span class="small">Type of the question</span></label> <select name="type"> <option value="0" selected="true">Free text</option>"; <option value="1">Yes / No </option>"; <option value="2">List (select any)</option>"; <option value="3">List (select one)</option>"; </select> </div> <div class="opts" style="display:none"> <label>List<span class="small">Newline separated</span></label> <textarea name="opts"></textarea> </div> <div class="delete"> <a href="#">Delete</a> </div> </div> <? include("../pollinator/editor_helper.php"); printQuestionsEditor(); ?> </div> <div id="controls"> <input id="add" type="button" value="Add"> <input id="submit" type="button" value="submit"/> </div> </form> -</div> -</body> \ No newline at end of file +<? include("../footer.php");?> \ No newline at end of file diff --git a/admin/header.php b/admin/header.php deleted file mode 100644 index bb3586c..0000000 --- a/admin/header.php +++ /dev/null @@ -1,20 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> -<head profile="http://gmpg.org/xfn/11"> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - <title>Widget Corporation(tm) Interview</title> - - <!-- Favicon --> - <link rel="icon" type="image/png" href="/images/favicon.png" /> - - <!-- stylesheets --> - <link rel="stylesheet" href="/questionator/css/main.css" type="text/css" media="screen" /> - <link rel="stylesheet" href="/questionator/css/boxy.css" type="text/css" media="screen" /> - <link rel="stylesheet" href="/questionator/css/admin.css" type="text/css" media="screen" /> -</head> -<body> - -<? - error_reporting(E_ALL); - ini_set('display_errors', '1'); -?> \ No newline at end of file diff --git a/admin/index.php b/admin/index.php index 26edca9..6cc0d6d 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,15 +1,13 @@ <? - include("header.php"); + $title = "Secret Admin Section"; + include("../header.php"); include("../pollinator/admin_helper.php") ?> -<div id="container"> - - <h1>Administration</h1> <p>Respondents to the poll:</p> <div id="tableHolder"> <? printResultsTable() ?> </div> -</div> -</html></body> \ No newline at end of file + +<? include("../footer.php"); ?> \ No newline at end of file diff --git a/css/main.css b/css/main.css index 0c483c2..d61dd73 100644 --- a/css/main.css +++ b/css/main.css @@ -1,29 +1,63 @@ body { background:#222; font:14px Georgia; } label.header{ font:16px Georgia; display:block; margin:15px 0 4px 0; } input.submit{ float:right; } input.text{ width:200px; } form{ padding-bottom:20px; } #container{ width:500px; margin: 10px 50px 10px 50px; padding:30px; background:#EEE; overflow: auto; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; } + +#header span { + overflow:auto; + float:left; + margin-left:10px; +} + +#header h1{ + color:#333; + font-size:180%; + padding-top:5px; + margin-bottom:0; + } + +#header h2 { + display:inline; + color:#444; + font-size:150%; + margin-top:20px; +} + +#header img{ + display:inline; + float:left; + height:90px; + width:90px; +} + +#header { + overflow:auto; + clear:both; +} \ No newline at end of file diff --git a/footer.php b/footer.php new file mode 100644 index 0000000..53da38f --- /dev/null +++ b/footer.php @@ -0,0 +1,2 @@ +</div> +</html></body> \ No newline at end of file diff --git a/header.php b/header.php index 9891fae..eef439e 100644 --- a/header.php +++ b/header.php @@ -1,18 +1,30 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - <title>Widget Corporation(tm) Interview</title> + <title>Widget Corporation(tm) :: <? echo $title; ?></title> <!-- Favicon --> <link rel="icon" type="image/png" href="/images/favicon.png" /> <!-- stylesheets --> <link rel="stylesheet" href="/questionator/css/main.css" type="text/css" media="screen" /> + <link rel="stylesheet" href="/questionator/css/boxy.css" type="text/css" media="screen" /> + <link rel="stylesheet" href="/questionator/css/admin.css" type="text/css" media="screen" /> </head> <body> <? error_reporting(E_ALL); ini_set('display_errors', '1'); -?> \ No newline at end of file +?> + +<div id="container"> + + <div id="header"> + <img src="/questionator/images/factory-icon.png" alt="logo icon"/> + <span> + <h1>Widget Corporation</h1> + <h2><? echo $title; ?></h2> + </span> + </div> \ No newline at end of file diff --git a/images/factory-icon.png b/images/factory-icon.png new file mode 100644 index 0000000..be115c1 Binary files /dev/null and b/images/factory-icon.png differ diff --git a/index.php b/index.php index 360d063..f5ee7d1 100644 --- a/index.php +++ b/index.php @@ -1,34 +1,32 @@ -<? include("header.php") ?> +<? + $title = "Interview Questionnaire"; + include("header.php"); +?> <script src="js/jquery.js" type="text/javascript"></script> <script src="js/jquery.validationEngine-en.js" type="text/javascript"></script> <script src="js/jquery.validationEngine.js" type="text/javascript"></script> -<div id="container"> - - <h1>Widget Corporation(tm) Interview Questions</h1> - - <p>Thank you for your interest in <strong>Widget Corporation</strong> please answer - the following questions as honestly as possibly</p> - - <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" /> - - <script> - $(document).ready(function() { - $("#questionsForm").validationEngine(); - }); - </script> +<p>Thank you for your interest in <strong>Widget Corporation</strong> please answer +the following questions as honestly as possibly</p> - <form id="questionsForm" method="post" action="process.php"> +<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" /> - <? - include("pollinator/question_viewer.php"); - printQuestions(); - ?> - - <input type="submit" class="submit" value="Submit" /> - - </form> -</div> +<script> +$(document).ready(function() { + $("#questionsForm").validationEngine(); +}); +</script> + +<form id="questionsForm" method="post" action="process.php"> -</html></body> \ No newline at end of file +<? + include("pollinator/question_viewer.php"); + printQuestions(); +?> + +<input type="submit" class="submit" value="Submit" /> + +</form> + +<? include("footer.php"); ?> \ No newline at end of file diff --git a/pollinator/question_viewer.php b/pollinator/question_viewer.php index 54366a3..80a91be 100644 --- a/pollinator/question_viewer.php +++ b/pollinator/question_viewer.php @@ -1,139 +1,137 @@ <? include("database_helper.php"); /** * Prints all questions stored in the Mysql database */ function printQuestions(){ $link = connect(); $q = "SELECT * FROM ". QUESTIONS_TABLE; $result = mysql_query($q) or mysql_err($q); while ( $row = mysql_fetch_array($result) ) { printQuestion($row); } disconnect(); } /** * Takes an array that has "type","content", and "opts" defined and prints * an html form element based on these values. This array is normally a row from * the QUESTIONS_TABLE mysql table. */ function printQuestion($row){ // All the questions have the same sort of title print '<div> <label class="header">' . $row["content"] . "</label>"; $id = $row["id"]; $name = "question". $id; // But they differ in how the user responds to them switch($row["type"]) { case Q_YES_NO: printf('<input class="validate[required] radio" value="yes" type="radio" id="%s" name="%s"><label>Yes</label><br/>',$name,$name); printf('<input class="validate[required] radio" value="no" type="radio" id="%s" name="%s"><label>No</label><br/>',$name,$name); break; case Q_MULTI: $opts = explode( "," , $row['opts']); foreach($opts as $opt){ print '<input type="checkbox" name="' . $name . $opt .'"/>'; print "<label>$opt</label><br/>"; } break; case Q_MULTI_EXC: $opts = explode( "," , $row['opts']); foreach($opts as $opt){ printf('<input class="validate[required] radio" value="%s" type="radio" id="%s" name="%s"/>',$opt,$name,$name); print "<label>$opt</label><br/>"; } break; case Q_TEXT: printf('<input class="validate[required,length[1,100]] text-input" type="text" id="%s" name="%s"/>',$name,$name); break; } print "</div>\n"; } /** * Process Questions */ function processResults(){ - print "<p>Thanks for your interest in Widget Corporation. We'll be in touch shortly!</p>"; - - $link = connect(); + connect(); // Loop through the dynamic fields $q = "SELECT * FROM ". QUESTIONS_TABLE; - $result = mysql_query($q); - if (!$result) err("error with query...\n Query=$q"); + $result = mysql_query($q) or mysql_err($q); // store the column names, and their answers $qResults = Array(); while( $row = mysql_fetch_array($result) ) { $id = $row['id']; $name = "question" . $id; $content = $row["content"]; $r = ""; switch($row["type"]){ // multiple check boxes are a pain in the ass. case Q_MULTI: $opts = explode(",", $row['opts']); foreach($opts as $opt){ //If the value is set, then it was checked if(isset($_POST[ $name . $opt])){ $r = $r . $opt . ","; } } break; // everything else can use a standard case - default: - + default: // try to gather the result for the question - $r = $_POST[$name]; + $r = mysql_real_escape_string($_POST[$name]); break; } print "<p><strong>$content</strong><br/>$r</p>"; $qResults[$name] = $r; } // end while $cols = ""; $values = ""; foreach($qResults as $key => $val) { $cols = $cols . $key . ","; $values = $values . "'" . $val . "'" . ","; } $cols = rtrim($cols,","); $values = rtrim($values,","); - $q = "INSERT into " . RESULTS_TABLE . " ($cols) VALUES($values)"; - $result = mysql_query($q); - if (!$result) err("error with query...\n Query=$q"); - + // Gaurd against SQL injection atttacks + $q = sprintf("INSERT into %s (%s) VALUES(%s)", RESULTS_TABLE,$cols,$values); + + $result = mysql_query($q) or mysql_err($q); + + disconnect(); } ?> \ No newline at end of file diff --git a/process.php b/process.php index 71b680b..492100b 100644 --- a/process.php +++ b/process.php @@ -1,13 +1,12 @@ -<? include("header.php") ?> - -<div id="container"> +<? + $title = "results"; + include("header.php") ?> - <h1>Thank You!</h1> +<p>Thanks for filling out the poll! We'll get back to you shortly. Below are your responses:</p> <? include("pollinator/question_viewer.php"); // Process the results processResults(); ?> -</div> -</html></body> \ No newline at end of file +<? include("footer.php"); ?> \ No newline at end of file diff --git a/questionator.tmproj b/questionator.tmproj index bdf6009..eb3b399 100644 --- a/questionator.tmproj +++ b/questionator.tmproj @@ -1,138 +1,169 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>currentDocument</key> - <string>admin/results.php</string> + <string>admin/editor.php</string> <key>documents</key> <array> <dict> <key>expanded</key> <true/> <key>name</key> <string>Questionator</string> <key>regexFolderFilter</key> <string>!.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$</string> <key>sourceDirectory</key> <string></string> </dict> </array> <key>fileHierarchyDrawerWidth</key> <integer>208</integer> <key>metaData</key> <dict> <key>admin/editor.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>20</integer> + <integer>38</integer> <key>line</key> - <integer>10</integer> + <integer>29</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> - <key>admin/editor_helper.php</key> + <key>admin/index.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>3</integer> + <integer>31</integer> <key>line</key> - <integer>13</integer> + <integer>12</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> - <integer>5</integer> + <integer>0</integer> </dict> - <key>admin/index.php</key> + <key>css/main.css</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>14</integer> + <integer>16</integer> <key>line</key> - <integer>6</integer> + <integer>46</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> - <key>admin/results.php</key> + <key>footer.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>0</integer> + <integer>14</integer> <key>line</key> - <integer>0</integer> + <integer>1</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> - <key>css/admin.css</key> + <key>header.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>0</integer> + <integer>7</integer> <key>line</key> - <integer>0</integer> + <integer>29</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> - <key>header.php</key> + <key>index.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>2</integer> + <integer>0</integer> <key>line</key> - <integer>17</integer> + <integer>30</integer> </dict> + <key>columnSelection</key> + <false/> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> + <key>selectFrom</key> + <dict> + <key>column</key> + <integer>28</integer> + <key>line</key> + <integer>31</integer> + </dict> + <key>selectTo</key> + <dict> + <key>column</key> + <integer>0</integer> + <key>line</key> + <integer>30</integer> + </dict> </dict> - <key>js/editor.js</key> + <key>pollinator/question_viewer.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>0</integer> <key>line</key> - <integer>82</integer> + <integer>75</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>62</integer> + </dict> + <key>process.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>8</integer> + <key>line</key> + <integer>4</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> - <integer>54</integer> + <integer>0</integer> </dict> </dict> <key>openDocuments</key> <array> - <string>admin/editor.php</string> - <string>admin/editor_helper.php</string> - <string>css/admin.css</string> - <string>js/editor.js</string> - <string>header.php</string> + <string>index.php</string> + <string>process.php</string> + <string>footer.php</string> + <string>pollinator/question_viewer.php</string> + <string>css/main.css</string> <string>admin/index.php</string> - <string>admin/results.php</string> + <string>header.php</string> + <string>admin/editor.php</string> </array> <key>showFileHierarchyDrawer</key> <true/> <key>windowFrame</key> - <string>{{264, -31}, {1032, 725}}</string> + <string>{{833, 367}, {1072, 733}}</string> </dict> </plist>
ralphleon/Pollinator
319d6c3a57d4662b205fd9ac079bb34225b02196
Major refactoring, added form validation
diff --git a/admin/editor.php b/admin/editor.php index ca4128f..272de81 100644 --- a/admin/editor.php +++ b/admin/editor.php @@ -1,54 +1,55 @@ -<? include("../header.php") ?> +<? include("header.php") ?> <script type="text/javascript" src="/questionator/js/jquery.js"></script> <script type="text/javascript" src="/questionator/js/editor.js"></script> +<script type="text/javascript" src="/questionator/js/jquery.boxy.js"></script> <div id="container"> <h1>Administration</h1> - <form id="editForm" action=""> + <form class="boxy" id="editForm" action=""> <div id="questionsBlock"> <!-- Sample Question --> <div class="question" style="display:none"> <div class="main"> <label>Question <span class="small">The main question</span></label> <textarea name="content"></textarea> <label>Type<span class="small">Type of the question</span></label> <select name="type"> <option value="0" selected="true">Free text</option>"; <option value="1">Yes / No </option>"; <option value="2">List (select any)</option>"; <option value="3">List (select one)</option>"; </select> </div> <div class="opts" style="display:none"> <label>List<span class="small">Newline separated</span></label> <textarea name="opts"></textarea> </div> <div class="delete"> <a href="#">Delete</a> </div> </div> <? - include("editor_helper.php"); + include("../pollinator/editor_helper.php"); printQuestionsEditor(); ?> </div> <div id="controls"> <input id="add" type="button" value="Add"> <input id="submit" type="button" value="submit"/> </div> </form> </div> </body> \ No newline at end of file diff --git a/admin/header.php b/admin/header.php new file mode 100644 index 0000000..bb3586c --- /dev/null +++ b/admin/header.php @@ -0,0 +1,20 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> +<head profile="http://gmpg.org/xfn/11"> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> + <title>Widget Corporation(tm) Interview</title> + + <!-- Favicon --> + <link rel="icon" type="image/png" href="/images/favicon.png" /> + + <!-- stylesheets --> + <link rel="stylesheet" href="/questionator/css/main.css" type="text/css" media="screen" /> + <link rel="stylesheet" href="/questionator/css/boxy.css" type="text/css" media="screen" /> + <link rel="stylesheet" href="/questionator/css/admin.css" type="text/css" media="screen" /> +</head> +<body> + +<? + error_reporting(E_ALL); + ini_set('display_errors', '1'); +?> \ No newline at end of file diff --git a/admin/index.php b/admin/index.php index b55757e..26edca9 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,7 +1,15 @@ -<? include("../header.php") ?> +<? + include("header.php"); + include("../pollinator/admin_helper.php") +?> <div id="container"> <h1>Administration</h1> + + <p>Respondents to the poll:</p> + <div id="tableHolder"> + <? printResultsTable() ?> + </div> </div> </html></body> \ No newline at end of file diff --git a/admin/print.php b/admin/print.php new file mode 100644 index 0000000..c321a80 --- /dev/null +++ b/admin/print.php @@ -0,0 +1,23 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> +<head profile="http://gmpg.org/xfn/11"> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> + <title>Widget Corporation(tm) Review - Printer Friendly</title> + + <!-- stylesheets --> + <link rel="stylesheet" href="/questionator/css/admin.css" type="text/css" media="screen" /> + <style> + table.admin { + width:auto; + height:auto; + } + </style> +</head> +<body> + +<? + include("../pollinator/admin_helper.php"); + printResultsTable(); +?> + +</body></html> \ No newline at end of file diff --git a/admin/results.php b/admin/results.php deleted file mode 100644 index f61667e..0000000 --- a/admin/results.php +++ /dev/null @@ -1,9 +0,0 @@ -<? include("../header.php") ?> - -<div id="container"> - - <h1>Administration</h1> - - -</div> -</html></body> \ No newline at end of file diff --git a/css/admin.css b/css/admin.css new file mode 100644 index 0000000..4659288 --- /dev/null +++ b/css/admin.css @@ -0,0 +1,98 @@ + +/* Table view */ +#tableHolder { + overflow: scroll; + width:600px; +} + +table.admin { + border-collapse: collapse; +} + +table.admin thead tr { + padding:3px; + margin:3px; + border-bottom:2px solid #666; + font-weight:bold; +} + +table.admin tbody tr { + padding:3px; + margin:3px; + border-bottom:1px solid #666; +} + +table.admin td { + padding:5px; +} + +/* Editor controls */ +#controls{ + clear:both; + margin-top:20px; + float:right; +} + +div.question { + margin:10px; + margin-top:40px; +} + +div.question div.main{ + background-color: #AAA; + padding:10px; + overflow: auto; +} + +div.question div.opts { + background-color: #999; + padding:10px; + clear:both; + overflow: auto; +} + +div.question label { + color:#333; + display:block; + text-align:right; + width:140px; + float:left; +} +div.question .small { + color:#444; + display:block; + font-size:11px; + font-weight:normal; + text-align:right; + width:140px; +} +div.question input,textarea,select{ + float:left; + font-size:12px; + padding:4px 2px; + border:solid 1px #aacfe4; + width:200px; + margin:2px 0 20px 10px; +} + +div.question textarea{ + width:60%; +} +div.question div.delete { + display:inline; + float:right; + margin-right:5px; + background:#FF6666; + clear:both; + padding:5px 10px 5px 10px; +} + +div.question div.delete:hover { + background:#FF3333; +} + +div.delete a{ + font-family:sans-serif; + color:#FFF; + text-decoration:none; +} diff --git a/css/boxy.css b/css/boxy.css new file mode 100644 index 0000000..e2ddde7 --- /dev/null +++ b/css/boxy.css @@ -0,0 +1,49 @@ +.boxy-wrapper { position: absolute; } +.boxy-wrapper.fixed { position: fixed; } + + /* Modal */ + + .boxy-modal-blackout { position: absolute; background-color: black; left: 0; top: 0; } + + /* Border */ + + .boxy-wrapper { empty-cells: show; } + .boxy-wrapper .top-left, + .boxy-wrapper .top-right, + .boxy-wrapper .bottom-right, + .boxy-wrapper .bottom-left { width: 10px; height: 10px; padding: 0 } + + .boxy-wrapper .top-left { background: url('../images/boxy-nw.png'); } + .boxy-wrapper .top-right { background: url('../images/boxy-ne.png'); } + .boxy-wrapper .bottom-right { background: url('../images/boxy-se.png'); } + .boxy-wrapper .bottom-left { background: url('../images/boxy-sw.png'); } + + /* IE6+7 hacks for the border. IE7 should support this natively but fails in conjuction with modal blackout bg. */ + /* NB: these must be absolute paths or URLs to your images */ + .boxy-wrapper .top-left { #background: none; #filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/boxy-nw.png'); } + .boxy-wrapper .top-right { #background: none; #filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/boxy-ne.png'); } + .boxy-wrapper .bottom-right { #background: none; #filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/boxy-se.png'); } + .boxy-wrapper .bottom-left { #background: none; #filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/boxy-sw.png'); } + + .boxy-wrapper .top, + .boxy-wrapper .bottom { height: 10px; background-color: black; opacity: 0.6; filter: alpha(opacity=60); padding: 0 } + + .boxy-wrapper .left, + .boxy-wrapper .right { width: 10px; background-color: black; opacity: 0.6; filter: alpha(opacity=60); padding: 0 } + + /* Title bar */ + + .boxy-wrapper .title-bar { background-color: black; padding: 6px; position: relative; } + .boxy-wrapper .title-bar.dragging { cursor: move; } + .boxy-wrapper .title-bar h2 { font-size: 12px; color: white; line-height: 1; margin: 0; padding: 0; font-weight: normal; } + .boxy-wrapper .title-bar .close { color: white; position: absolute; top: 6px; right: 6px; font-size: 90%; line-height: 1; } + + /* Content Region */ + + .boxy-inner { background-color: white; padding: 0 } + .boxy-content { padding: 15px; } + + /* Question Boxes */ + + .boxy-wrapper .question { width: 350px; min-height: 80px; } + .boxy-wrapper .answers { text-align: right; } diff --git a/css/main.css b/css/main.css index 9dc0ee2..0c483c2 100644 --- a/css/main.css +++ b/css/main.css @@ -1,85 +1,29 @@ body { background:#222; font:14px Georgia; } label.header{ font:16px Georgia; display:block; margin:15px 0 4px 0; } input.submit{ float:right; } input.text{ width:200px; } form{ padding-bottom:20px; } #container{ width:500px; margin: 10px 50px 10px 50px; padding:30px; - background:#DDD; -} - -/* Admin section */ -div.question { - margin:10px; - margin-top:40px; -} - -div.question div.main{ - background-color: #999; - padding:10px; + background:#EEE; overflow: auto; - width: 100% } - -div.question div.opts { - background-color: #777; - padding:10px; - clear:both; - overflow: auto; - width: 100% -} - -div.question label { - display:block; - font-weight:bold; - text-align:right; - width:140px; - float:left; -} -div.question .small { - color:#333; - display:block; - font-size:11px; - font-weight:normal; - text-align:right; - width:140px; -} -div.question input,textarea,select{ - float:left; - font-size:12px; - padding:4px 2px; - border:solid 1px #aacfe4; - width:200px; - margin:2px 0 20px 10px; -} - -div.question textarea{ - width:60%; -} -div.question div.delete { - display:inline; - float:right; - margin-right:5px; - background:#FF9999; - clear:both; - padding:5px 10px 5px 10px; -} \ No newline at end of file diff --git a/css/validationEngine.jquery.css b/css/validationEngine.jquery.css new file mode 100755 index 0000000..2976366 --- /dev/null +++ b/css/validationEngine.jquery.css @@ -0,0 +1,81 @@ + .formError { + position:absolute; + top:300px; left:300px; + padding-bottom:13px; + display:block; + z-index:5000; + } + #debugMode{ + background:#000; + position:fixed; + width:100%; height:200px; + top:0; left:0; + overflow:scroll; + opacity:0.8; + display:block; + padding:10px; + color:#fff; + font-size:14px; + z-index:100000; + } + + .ajaxSubmit{ padding:20px; background:#55ea55;border:1px solid #999;display:none} + .formError .formErrorContent { + width:100%; + background:#ee0101; + color:#fff; + width:150px; + font-family:tahoma; + font-size:11px; + border:2px solid #ddd; + box-shadow: 0px 0px 6px #000; + -moz-box-shadow: 0px 0px 6px #000; + -webkit-box-shadow: 0px 0px 6px #000; + padding:4px 10px 4px 10px; + border-radius: 6px; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + } + .greenPopup .formErrorContent {background:#33be40;} + + .blackPopup .formErrorContent {background:#393939;color:#FFF;} + + .formError .formErrorArrow{ + position:absolute; + bottom:0;left:20px; + width:15px; height:15px; + + z-index:5001; + } + .formError .formErrorArrowBottom{top:0;margin:-6px;} + + .formError .formErrorArrow div{ + border-left:2px solid #ddd; + border-right:2px solid #ddd; + box-shadow: 0px 2px 3px #444; + -moz-box-shadow: 0px 2px 3px #444; + -webkit-box-shadow: 0px 2px 3px #444; + font-size:0px; height:1px; background:#ee0101;margin:0 auto;line-height:0px; font-size:0px; display:block; + } + .formError .formErrorArrowBottom div{ + box-shadow: none; + -moz-box-shadow: none; + -webkit-box-shadow: none; + } + + .greenPopup .formErrorArrow div{background:#33be40;} + .blackPopup .formErrorArrow div{background:#393939;color:#FFF;} + + .formError .formErrorArrow .line10{width:15px;border:none;} + .formError .formErrorArrow .line9{width:13px;border:none;} + .formError .formErrorArrow .line8{width:11px;} + .formError .formErrorArrow .line7{width:9px;} + .formError .formErrorArrow .line6{width:7px;} + .formError .formErrorArrow .line5{width:5px;} + .formError .formErrorArrow .line4{width:3px;} + .formError .formErrorArrow .line3{width:1px; + border-left:2px solid #ddd; + border-right:2px solid #ddd; + border-bottom:0px solid #ddd;} + .formError .formErrorArrow .line2{width:3px;border:none;background:#ddd;} + .formError .formErrorArrow .line1{width:1px;border:none;background:#ddd;} \ No newline at end of file diff --git a/header.php b/header.php index 3baab7d..9891fae 100644 --- a/header.php +++ b/header.php @@ -1,18 +1,18 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Widget Corporation(tm) Interview</title> <!-- Favicon --> <link rel="icon" type="image/png" href="/images/favicon.png" /> <!-- stylesheets --> <link rel="stylesheet" href="/questionator/css/main.css" type="text/css" media="screen" /> </head> -<body><html> +<body> <? error_reporting(E_ALL); ini_set('display_errors', '1'); ?> \ No newline at end of file diff --git a/images/boxy-ne.png b/images/boxy-ne.png new file mode 100644 index 0000000..81e1e17 Binary files /dev/null and b/images/boxy-ne.png differ diff --git a/images/boxy-nw.png b/images/boxy-nw.png new file mode 100644 index 0000000..2b8016e Binary files /dev/null and b/images/boxy-nw.png differ diff --git a/images/boxy-se.png b/images/boxy-se.png new file mode 100644 index 0000000..a42bdfb Binary files /dev/null and b/images/boxy-se.png differ diff --git a/images/boxy-sw.png b/images/boxy-sw.png new file mode 100644 index 0000000..ecb504b Binary files /dev/null and b/images/boxy-sw.png differ diff --git a/index.php b/index.php index 577f818..360d063 100644 --- a/index.php +++ b/index.php @@ -1,30 +1,34 @@ -<? include("header.php") ?> +<? include("header.php") ?> + +<script src="js/jquery.js" type="text/javascript"></script> +<script src="js/jquery.validationEngine-en.js" type="text/javascript"></script> +<script src="js/jquery.validationEngine.js" type="text/javascript"></script> <div id="container"> <h1>Widget Corporation(tm) Interview Questions</h1> <p>Thank you for your interest in <strong>Widget Corporation</strong> please answer the following questions as honestly as possibly</p> - - <form method="post" action="process.php"> + <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" /> + + <script> + $(document).ready(function() { + $("#questionsForm").validationEngine(); + }); + </script> - <!-- Some questions are hard-wired --> - <label class="header">Name</label> - <input class="text" name="name" type="text"/> - - <label class="header">Email</label> - <input class="text" name="email" type="text"/> + <form id="questionsForm" method="post" action="process.php"> -<? - include("database_helper.php"); + <? + include("pollinator/question_viewer.php"); printQuestions(); -?> + ?> <input type="submit" class="submit" value="Submit" /> </form> </div> </html></body> \ No newline at end of file diff --git a/js/editor.js b/js/editor.js index e8a046c..058cba0 100644 --- a/js/editor.js +++ b/js/editor.js @@ -1,76 +1,90 @@ - $(document).ready(function(){ var Q_MULTI = 2; var Q_MULTI_EXC = 3; +/** Boxy dialog + */ +$(function() { + $('.boxy').boxy(); +}); + /** Callback for selection changes in "type" * Will hide or show the "options" box if needed */ $('select[name=type]').live("change",function(e){ // Sketchy to use 3, was having trouble with name though... this // hides and shows the extended detail block; var opts = this.parentNode.parentNode.childNodes[3]; if(this.value == Q_MULTI || this.value == Q_MULTI_EXC){ $(opts).slideDown("slow"); }else{ $(opts).slideUp("slow"); } }); /** Callback for the delete button * Removes the current block, live for newly added questions */ $('a').live("click",function(e){ var parent = this.parentNode.parentNode; - $(parent).fadeOut(1000,function(){ + $(parent).fadeOut(800,function(){ parent.parentNode.removeChild(parent); }); }); /** * Button callback for the "add" button. Adds a new question editor, based * on the first question editor */ $('#add').click(function(event){ // Clone the sample data $('div.question:first').clone().appendTo("#questionsBlock"); - $('div.question:last').fadeIn(1000); + $('div.question:last').fadeIn(800); }); /** * Callback for the submit button. * Packages up the question data in JSON and passes it to the server */ $('#submit').click(function(event){ + var questions = [ ]; + // Package up the current questions, loop through all elements except // for my first element which i use for cloaning $('#questionsBlock').find('div.question:not(div:first)').each( function( i ){ - var content = "", opts = "", type = ""; + var q = { content : "", opts : "", type : ""}; - // For the love of peet, why doesn't a dynamically added textbox work the same - // as a static one? Hence the two methods of accessing the 'value' $(this).find('textarea[name=content]:first').each( function(){ - if(this.lastChild) content = this.lastChild.nodeValue; - else if(this.value) content = this.value; + q.content = this.value; }); $(this).find('textarea[name=opts]:first').each( function(){ - if(this.lastChild) opts = this.lastChild.nodeValue; - else if(this.value) opts = this.value; + q.opts = this.value; }); $(this).find('select[name=type]').each( function(){ - type = this.value; + q.type = this.value; }); - alert("content " + content + " opts " + opts + " type " + type); + questions.push(q); + }); + + // Confirm then send off ajax call + Boxy.confirm("This will remove all previously stored results! Are you sure?", function() { + + $.post("../pollinator/editor_update.php", { questions: questions }, + function(data){ + // Parse your response code here. We're going to be lazy, so it's ALWAYS A O.K. + // because, how could it go wrong? This code is _rock_ solid. </sarcasm> + //alert(data); + }); }); }); -}); +}); \ No newline at end of file diff --git a/js/jquery.boxy.js b/js/jquery.boxy.js new file mode 100644 index 0000000..24d24a7 --- /dev/null +++ b/js/jquery.boxy.js @@ -0,0 +1,570 @@ +/** + * Boxy 0.1.4 - Facebook-style dialog, with frills + * + * (c) 2008 Jason Frame + * Licensed under the MIT License (LICENSE) + */ + +/* + * jQuery plugin + * + * Options: + * message: confirmation message for form submit hook (default: "Please confirm:") + * + * Any other options - e.g. 'clone' - will be passed onto the boxy constructor (or + * Boxy.load for AJAX operations) + */ +jQuery.fn.boxy = function(options) { + options = options || {}; + return this.each(function() { + var node = this.nodeName.toLowerCase(), self = this; + if (node == 'a') { + jQuery(this).click(function() { + var active = Boxy.linkedTo(this), + href = this.getAttribute('href'), + localOptions = jQuery.extend({actuator: this, title: this.title}, options); + + if (active) { + active.show(); + } else if (href.indexOf('#') >= 0) { + var content = jQuery(href.substr(href.indexOf('#'))), + newContent = content.clone(true); + content.remove(); + localOptions.unloadOnHide = false; + new Boxy(newContent, localOptions); + } else { // fall back to AJAX; could do with a same-origin check + if (!localOptions.cache) localOptions.unloadOnHide = true; + Boxy.load(this.href, localOptions); + } + + return false; + }); + } else if (node == 'form') { + jQuery(this).bind('submit.boxy', function() { + Boxy.confirm(options.message || 'Please confirm:', function() { + jQuery(self).unbind('submit.boxy').submit(); + }); + return false; + }); + } + }); +}; + +// +// Boxy Class + +function Boxy(element, options) { + + this.boxy = jQuery(Boxy.WRAPPER); + jQuery.data(this.boxy[0], 'boxy', this); + + this.visible = false; + this.options = jQuery.extend({}, Boxy.DEFAULTS, options || {}); + + if (this.options.modal) { + this.options = jQuery.extend(this.options, {center: true, draggable: false}); + } + + // options.actuator == DOM element that opened this boxy + // association will be automatically deleted when this boxy is remove()d + if (this.options.actuator) { + jQuery.data(this.options.actuator, 'active.boxy', this); + } + + this.setContent(element || "<div></div>"); + this._setupTitleBar(); + + this.boxy.css('display', 'none').appendTo(document.body); + this.toTop(); + + if (this.options.fixed) { + if (jQuery.browser.msie && jQuery.browser.version < 7) { + this.options.fixed = false; // IE6 doesn't support fixed positioning + } else { + this.boxy.addClass('fixed'); + } + } + + if (this.options.center && Boxy._u(this.options.x, this.options.y)) { + this.center(); + } else { + this.moveTo( + Boxy._u(this.options.x) ? this.options.x : Boxy.DEFAULT_X, + Boxy._u(this.options.y) ? this.options.y : Boxy.DEFAULT_Y + ); + } + + if (this.options.show) this.show(); + +}; + +Boxy.EF = function() {}; + +jQuery.extend(Boxy, { + + WRAPPER: "<table cellspacing='0' cellpadding='0' border='0' class='boxy-wrapper'>" + + "<tr><td class='top-left'></td><td class='top'></td><td class='top-right'></td></tr>" + + "<tr><td class='left'></td><td class='boxy-inner'></td><td class='right'></td></tr>" + + "<tr><td class='bottom-left'></td><td class='bottom'></td><td class='bottom-right'></td></tr>" + + "</table>", + + DEFAULTS: { + title: null, // titlebar text. titlebar will not be visible if not set. + closeable: true, // display close link in titlebar? + draggable: true, // can this dialog be dragged? + clone: false, // clone content prior to insertion into dialog? + actuator: null, // element which opened this dialog + center: true, // center dialog in viewport? + show: true, // show dialog immediately? + modal: false, // make dialog modal? + fixed: true, // use fixed positioning, if supported? absolute positioning used otherwise + closeText: '[close]', // text to use for default close link + unloadOnHide: false, // should this dialog be removed from the DOM after being hidden? + clickToFront: false, // bring dialog to foreground on any click (not just titlebar)? + behaviours: Boxy.EF, // function used to apply behaviours to all content embedded in dialog. + afterDrop: Boxy.EF, // callback fired after dialog is dropped. executes in context of Boxy instance. + afterShow: Boxy.EF, // callback fired after dialog becomes visible. executes in context of Boxy instance. + afterHide: Boxy.EF, // callback fired after dialog is hidden. executed in context of Boxy instance. + beforeUnload: Boxy.EF // callback fired after dialog is unloaded. executed in context of Boxy instance. + }, + + DEFAULT_X: 50, + DEFAULT_Y: 50, + zIndex: 1337, + dragConfigured: false, // only set up one drag handler for all boxys + resizeConfigured: false, + dragging: null, + + // load a URL and display in boxy + // url - url to load + // options keys (any not listed below are passed to boxy constructor) + // type: HTTP method, default: GET + // cache: cache retrieved content? default: false + // filter: jQuery selector used to filter remote content + load: function(url, options) { + + options = options || {}; + + var ajax = { + url: url, type: 'GET', dataType: 'html', cache: false, success: function(html) { + html = jQuery(html); + if (options.filter) html = jQuery(options.filter, html); + new Boxy(html, options); + } + }; + + jQuery.each(['type', 'cache'], function() { + if (this in options) { + ajax[this] = options[this]; + delete options[this]; + } + }); + + jQuery.ajax(ajax); + + }, + + // allows you to get a handle to the containing boxy instance of any element + // e.g. <a href='#' onclick='alert(Boxy.get(this));'>inspect!</a>. + // this returns the actual instance of the boxy 'class', not just a DOM element. + // Boxy.get(this).hide() would be valid, for instance. + get: function(ele) { + var p = jQuery(ele).parents('.boxy-wrapper'); + return p.length ? jQuery.data(p[0], 'boxy') : null; + }, + + // returns the boxy instance which has been linked to a given element via the + // 'actuator' constructor option. + linkedTo: function(ele) { + return jQuery.data(ele, 'active.boxy'); + }, + + // displays an alert box with a given message, calling optional callback + // after dismissal. + alert: function(message, callback, options) { + return Boxy.ask(message, ['OK'], callback, options); + }, + + // displays an alert box with a given message, calling after callback iff + // user selects OK. + confirm: function(message, after, options) { + return Boxy.ask(message, ['OK', 'Cancel'], function(response) { + if (response == 'OK') after(); + }, options); + }, + + // asks a question with multiple responses presented as buttons + // selected item is returned to a callback method. + // answers may be either an array or a hash. if it's an array, the + // the callback will received the selected value. if it's a hash, + // you'll get the corresponding key. + ask: function(question, answers, callback, options) { + + options = jQuery.extend({modal: true, closeable: false}, + options || {}, + {show: true, unloadOnHide: true}); + + var body = jQuery('<div></div>').append(jQuery('<div class="question"></div>').html(question)); + + // ick + var map = {}, answerStrings = []; + if (answers instanceof Array) { + for (var i = 0; i < answers.length; i++) { + map[answers[i]] = answers[i]; + answerStrings.push(answers[i]); + } + } else { + for (var k in answers) { + map[answers[k]] = k; + answerStrings.push(answers[k]); + } + } + + var buttons = jQuery('<form class="answers"></form>'); + buttons.html(jQuery.map(answerStrings, function(v) { + return "<input type='button' value='" + v + "' />"; + }).join(' ')); + + jQuery('input[type=button]', buttons).click(function() { + var clicked = this; + Boxy.get(this).hide(function() { + if (callback) callback(map[clicked.value]); + }); + }); + + body.append(buttons); + + new Boxy(body, options); + + }, + + // returns true if a modal boxy is visible, false otherwise + isModalVisible: function() { + return jQuery('.boxy-modal-blackout').length > 0; + }, + + _u: function() { + for (var i = 0; i < arguments.length; i++) + if (typeof arguments[i] != 'undefined') return false; + return true; + }, + + _handleResize: function(evt) { + var d = jQuery(document); + jQuery('.boxy-modal-blackout').css('display', 'none').css({ + width: d.width(), height: d.height() + }).css('display', 'block'); + }, + + _handleDrag: function(evt) { + var d; + if (d = Boxy.dragging) { + d[0].boxy.css({left: evt.pageX - d[1], top: evt.pageY - d[2]}); + } + }, + + _nextZ: function() { + return Boxy.zIndex++; + }, + + _viewport: function() { + var d = document.documentElement, b = document.body, w = window; + return jQuery.extend( + jQuery.browser.msie ? + { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop } : + { left: w.pageXOffset, top: w.pageYOffset }, + !Boxy._u(w.innerWidth) ? + { width: w.innerWidth, height: w.innerHeight } : + (!Boxy._u(d) && !Boxy._u(d.clientWidth) && d.clientWidth != 0 ? + { width: d.clientWidth, height: d.clientHeight } : + { width: b.clientWidth, height: b.clientHeight }) ); + } + +}); + +Boxy.prototype = { + + // Returns the size of this boxy instance without displaying it. + // Do not use this method if boxy is already visible, use getSize() instead. + estimateSize: function() { + this.boxy.css({visibility: 'hidden', display: 'block'}); + var dims = this.getSize(); + this.boxy.css('display', 'none').css('visibility', 'visible'); + return dims; + }, + + // Returns the dimensions of the entire boxy dialog as [width,height] + getSize: function() { + return [this.boxy.width(), this.boxy.height()]; + }, + + // Returns the dimensions of the content region as [width,height] + getContentSize: function() { + var c = this.getContent(); + return [c.width(), c.height()]; + }, + + // Returns the position of this dialog as [x,y] + getPosition: function() { + var b = this.boxy[0]; + return [b.offsetLeft, b.offsetTop]; + }, + + // Returns the center point of this dialog as [x,y] + getCenter: function() { + var p = this.getPosition(); + var s = this.getSize(); + return [Math.floor(p[0] + s[0] / 2), Math.floor(p[1] + s[1] / 2)]; + }, + + // Returns a jQuery object wrapping the inner boxy region. + // Not much reason to use this, you're probably more interested in getContent() + getInner: function() { + return jQuery('.boxy-inner', this.boxy); + }, + + // Returns a jQuery object wrapping the boxy content region. + // This is the user-editable content area (i.e. excludes titlebar) + getContent: function() { + return jQuery('.boxy-content', this.boxy); + }, + + // Replace dialog content + setContent: function(newContent) { + newContent = jQuery(newContent).css({display: 'block'}).addClass('boxy-content'); + if (this.options.clone) newContent = newContent.clone(true); + this.getContent().remove(); + this.getInner().append(newContent); + this._setupDefaultBehaviours(newContent); + this.options.behaviours.call(this, newContent); + return this; + }, + + // Move this dialog to some position, funnily enough + moveTo: function(x, y) { + this.moveToX(x).moveToY(y); + return this; + }, + + // Move this dialog (x-coord only) + moveToX: function(x) { + if (typeof x == 'number') this.boxy.css({left: x}); + else this.centerX(); + return this; + }, + + // Move this dialog (y-coord only) + moveToY: function(y) { + if (typeof y == 'number') this.boxy.css({top: y}); + else this.centerY(); + return this; + }, + + // Move this dialog so that it is centered at (x,y) + centerAt: function(x, y) { + var s = this[this.visible ? 'getSize' : 'estimateSize'](); + if (typeof x == 'number') this.moveToX(x - s[0] / 2); + if (typeof y == 'number') this.moveToY(y - s[1] / 2); + return this; + }, + + centerAtX: function(x) { + return this.centerAt(x, null); + }, + + centerAtY: function(y) { + return this.centerAt(null, y); + }, + + // Center this dialog in the viewport + // axis is optional, can be 'x', 'y'. + center: function(axis) { + var v = Boxy._viewport(); + var o = this.options.fixed ? [0, 0] : [v.left, v.top]; + if (!axis || axis == 'x') this.centerAt(o[0] + v.width / 2, null); + if (!axis || axis == 'y') this.centerAt(null, o[1] + v.height / 2); + return this; + }, + + // Center this dialog in the viewport (x-coord only) + centerX: function() { + return this.center('x'); + }, + + // Center this dialog in the viewport (y-coord only) + centerY: function() { + return this.center('y'); + }, + + // Resize the content region to a specific size + resize: function(width, height, after) { + if (!this.visible) return; + var bounds = this._getBoundsForResize(width, height); + this.boxy.css({left: bounds[0], top: bounds[1]}); + this.getContent().css({width: bounds[2], height: bounds[3]}); + if (after) after(this); + return this; + }, + + // Tween the content region to a specific size + tween: function(width, height, after) { + if (!this.visible) return; + var bounds = this._getBoundsForResize(width, height); + var self = this; + this.boxy.stop().animate({left: bounds[0], top: bounds[1]}); + this.getContent().stop().animate({width: bounds[2], height: bounds[3]}, function() { + if (after) after(self); + }); + return this; + }, + + // Returns true if this dialog is visible, false otherwise + isVisible: function() { + return this.visible; + }, + + // Make this boxy instance visible + show: function() { + if (this.visible) return; + if (this.options.modal) { + var self = this; + if (!Boxy.resizeConfigured) { + Boxy.resizeConfigured = true; + jQuery(window).resize(function() { Boxy._handleResize(); }); + } + this.modalBlackout = jQuery('<div class="boxy-modal-blackout"></div>') + .css({zIndex: Boxy._nextZ(), + opacity: 0.7, + width: jQuery(document).width(), + height: jQuery(document).height()}) + .appendTo(document.body); + this.toTop(); + if (this.options.closeable) { + jQuery(document.body).bind('keypress.boxy', function(evt) { + var key = evt.which || evt.keyCode; + if (key == 27) { + self.hide(); + jQuery(document.body).unbind('keypress.boxy'); + } + }); + } + } + this.boxy.stop().css({opacity: 1}).show(); + this.visible = true; + this._fire('afterShow'); + return this; + }, + + // Hide this boxy instance + hide: function(after) { + if (!this.visible) return; + var self = this; + if (this.options.modal) { + jQuery(document.body).unbind('keypress.boxy'); + this.modalBlackout.animate({opacity: 0}, function() { + jQuery(this).remove(); + }); + } + this.boxy.stop().animate({opacity: 0}, 300, function() { + self.boxy.css({display: 'none'}); + self.visible = false; + self._fire('afterHide'); + if (after) after(self); + if (self.options.unloadOnHide) self.unload(); + }); + return this; + }, + + toggle: function() { + this[this.visible ? 'hide' : 'show'](); + return this; + }, + + hideAndUnload: function(after) { + this.options.unloadOnHide = true; + this.hide(after); + return this; + }, + + unload: function() { + this._fire('beforeUnload'); + this.boxy.remove(); + if (this.options.actuator) { + jQuery.data(this.options.actuator, 'active.boxy', false); + } + }, + + // Move this dialog box above all other boxy instances + toTop: function() { + this.boxy.css({zIndex: Boxy._nextZ()}); + return this; + }, + + // Returns the title of this dialog + getTitle: function() { + return jQuery('> .title-bar h2', this.getInner()).html(); + }, + + // Sets the title of this dialog + setTitle: function(t) { + jQuery('> .title-bar h2', this.getInner()).html(t); + return this; + }, + + // + // Don't touch these privates + + _getBoundsForResize: function(width, height) { + var csize = this.getContentSize(); + var delta = [width - csize[0], height - csize[1]]; + var p = this.getPosition(); + return [Math.max(p[0] - delta[0] / 2, 0), + Math.max(p[1] - delta[1] / 2, 0), width, height]; + }, + + _setupTitleBar: function() { + if (this.options.title) { + var self = this; + var tb = jQuery("<div class='title-bar'></div>").html("<h2>" + this.options.title + "</h2>"); + if (this.options.closeable) { + tb.append(jQuery("<a href='#' class='close'></a>").html(this.options.closeText)); + } + if (this.options.draggable) { + tb[0].onselectstart = function() { return false; } + tb[0].unselectable = 'on'; + tb[0].style.MozUserSelect = 'none'; + if (!Boxy.dragConfigured) { + jQuery(document).mousemove(Boxy._handleDrag); + Boxy.dragConfigured = true; + } + tb.mousedown(function(evt) { + self.toTop(); + Boxy.dragging = [self, evt.pageX - self.boxy[0].offsetLeft, evt.pageY - self.boxy[0].offsetTop]; + jQuery(this).addClass('dragging'); + }).mouseup(function() { + jQuery(this).removeClass('dragging'); + Boxy.dragging = null; + self._fire('afterDrop'); + }); + } + this.getInner().prepend(tb); + this._setupDefaultBehaviours(tb); + } + }, + + _setupDefaultBehaviours: function(root) { + var self = this; + if (this.options.clickToFront) { + root.click(function() { self.toTop(); }); + } + jQuery('.close', root).click(function() { + self.hide(); + return false; + }).mousedown(function(evt) { evt.stopPropagation(); }); + }, + + _fire: function(event) { + this.options[event].call(this); + } + +}; diff --git a/js/jquery.validationEngine-en.js b/js/jquery.validationEngine-en.js new file mode 100755 index 0000000..17c1a88 --- /dev/null +++ b/js/jquery.validationEngine-en.js @@ -0,0 +1,63 @@ + + +(function($) { + $.fn.validationEngineLanguage = function() {}; + $.validationEngineLanguage = { + newLang: function() { + $.validationEngineLanguage.allRules = {"required":{ // Add your regex rules here, you can take telephone as an example + "regex":"none", + "alertText":"* This field is required", + "alertTextCheckboxMultiple":"* Please select an option", + "alertTextCheckboxe":"* This checkbox is required"}, + "length":{ + "regex":"none", + "alertText":"*Between ", + "alertText2":" and ", + "alertText3": " characters allowed"}, + "maxCheckbox":{ + "regex":"none", + "alertText":"* Checks allowed Exceeded"}, + "minCheckbox":{ + "regex":"none", + "alertText":"* Please select ", + "alertText2":" options"}, + "confirm":{ + "regex":"none", + "alertText":"* Your field is not matching"}, + "telephone":{ + "regex":"/^[0-9\-\(\)\ ]+$/", + "alertText":"* Invalid phone number"}, + "email":{ + "regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/", + "alertText":"* Invalid email address"}, + "date":{ + "regex":"/^[0-9]{4}\-\[0-9]{1,2}\-\[0-9]{1,2}$/", + "alertText":"* Invalid date, must be in YYYY-MM-DD format"}, + "onlyNumber":{ + "regex":"/^[0-9\ ]+$/", + "alertText":"* Numbers only"}, + "noSpecialCaracters":{ + "regex":"/^[0-9a-zA-Z]+$/", + "alertText":"* No special caracters allowed"}, + "ajaxUser":{ + "file":"validateUser.php", + "extraData":"name=eric", + "alertTextOk":"* This user is available", + "alertTextLoad":"* Loading, please wait", + "alertText":"* This user is already taken"}, + "ajaxName":{ + "file":"validateUser.php", + "alertText":"* This name is already taken", + "alertTextOk":"* This name is available", + "alertTextLoad":"* Loading, please wait"}, + "onlyLetter":{ + "regex":"/^[a-zA-Z\ \']+$/", + "alertText":"* Letters only"} + } + } + } +})(jQuery); + +$(document).ready(function() { + $.validationEngineLanguage.newLang() +}); \ No newline at end of file diff --git a/js/jquery.validationEngine.js b/js/jquery.validationEngine.js new file mode 100755 index 0000000..6097fb2 --- /dev/null +++ b/js/jquery.validationEngine.js @@ -0,0 +1,541 @@ +/* + * Inline Form Validation Engine 1.6.2, jQuery plugin + * + * Copyright(c) 2009, Cedric Dugas + * http://www.position-relative.net + * + * Form validation engine allowing custom regex rules to be added. + * Thanks to Francois Duquette + * Licenced under the MIT Licence + */ + +(function($) { + + $.fn.validationEngine = function(settings) { + + if($.validationEngineLanguage){ // IS THERE A LANGUAGE LOCALISATION ? + allRules = $.validationEngineLanguage.allRules; + }else{ + $.validationEngine.debug("Validation engine rules are not loaded check your external file"); + } + settings = jQuery.extend({ + allrules:allRules, + validationEventTriggers:"blur", + inlineValidation: true, + returnIsValid:false, + animateSubmit:true, + unbindEngine:true, + ajaxSubmit: false, + promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight + success : false, + failure : function() {} + }, settings); + $.validationEngine.settings = settings; + $.validationEngine.ajaxValidArray = new Array(); // ARRAY FOR AJAX: VALIDATION MEMORY + + if(settings.inlineValidation == true){ // Validating Inline ? + if(!settings.returnIsValid){ // NEEDED FOR THE SETTING returnIsValid + allowReturnIsvalid = false; + $(this).find("[class*=validate]").not("[type=checkbox]").bind(settings.validationEventTriggers, function(caller){ _inlinEvent(this); }) + $(this).find("[class*=validate][type=checkbox]").bind("click", function(caller){ _inlinEvent(this); }) + + firstvalid = false; + } + function _inlinEvent(caller){ + $.validationEngine.settings = settings; + if($.validationEngine.intercept == false || !$.validationEngine.intercept){ // STOP INLINE VALIDATION THIS TIME ONLY + $.validationEngine.onSubmitValid=false; + $.validationEngine.loadValidation(caller); + }else{ + $.validationEngine.intercept = false; + } + } + } + if (settings.returnIsValid){ // Do validation and return true or false, it bypass everything; + if ($.validationEngine.submitValidation(this,settings)){ + return false; + }else{ + return true; + } + } + $(this).bind("submit", function(caller){ // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY + $.validationEngine.onSubmitValid = true; + $.validationEngine.settings = settings; + if($.validationEngine.submitValidation(this,settings) == false){ + if($.validationEngine.submitForm(this,settings) == true) {return false;} + }else{ + settings.failure && settings.failure(); + return false; + } + }) +}; +$.validationEngine = { + defaultSetting : function(caller) { + if($.validationEngineLanguage){ // IS THERE A LANGUAGE LOCALISATION ? + allRules = $.validationEngineLanguage.allRules; + }else{ + $.validationEngine.debug("Validation engine rules are not loaded check your external file"); + } + settings = { + allrules:allRules, + validationEventTriggers:"blur", + inlineValidation: true, + returnIsValid:false, + animateSubmit:true, + unbindEngine:true, + ajaxSubmit: false, + promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight + success : false, + failure : function() {} + } + $.validationEngine.settings = settings; + }, + loadValidation : function(caller) { // GET VALIDATIONS TO BE EXECUTED + if(!$.validationEngine.settings){ + $.validationEngine.defaultSetting() + } + rulesParsing = $(caller).attr('class'); + rulesRegExp = /\[(.*)\]/; + getRules = rulesRegExp.exec(rulesParsing); + str = getRules[1]; + pattern = /\W+/; + result= str.split(pattern); + + var validateCalll = $.validationEngine.validateCall(caller,result) + return validateCalll; + }, + validateCall : function(caller,rules) { // EXECUTE VALIDATION REQUIRED BY THE USER FOR THIS FIELD + var promptText ="" + + if(!$(caller).attr("id")) { $.validationEngine.debug("This field have no ID attribut( name & class displayed): "+$(caller).attr("name")+" "+$(caller).attr("class")) } + + caller = caller; + ajaxValidate = false; + var callerName = $(caller).attr("name"); + $.validationEngine.isError = false; + $.validationEngine.showTriangle = true; + callerType = $(caller).attr("type"); + + for (i=0; i<rules.length;i++){ + switch (rules[i]){ + case "optional": + if(!$(caller).val()){ + $.validationEngine.closePrompt(caller); + return $.validationEngine.isError; + } + break; + case "required": + _required(caller,rules); + break; + case "custom": + _customRegex(caller,rules,i); + break; + case "ajax": + if(!$.validationEngine.onSubmitValid){ + _ajax(caller,rules,i); + }; + break; + case "length": + _length(caller,rules,i); + break; + case "maxCheckbox": + _maxCheckbox(caller,rules,i); + groupname = $(caller).attr("name"); + caller = $("input[name='"+groupname+"']"); + break; + case "minCheckbox": + _minCheckbox(caller,rules,i); + groupname = $(caller).attr("name"); + caller = $("input[name='"+groupname+"']"); + break; + case "confirm": + _confirm(caller,rules,i); + break; + default :; + }; + }; + radioHack(); + if ($.validationEngine.isError == true){ + linkTofield = $.validationEngine.linkTofield(caller); + + ($("div."+linkTofield).size() ==0) ? $.validationEngine.buildPrompt(caller,promptText,"error") : $.validationEngine.updatePromptText(caller,promptText); + }else{ $.validationEngine.closePrompt(caller);} + /* UNFORTUNATE RADIO AND CHECKBOX GROUP HACKS */ + /* As my validation is looping input with id's we need a hack for my validation to understand to group these inputs */ + function radioHack(){ + if($("input[name='"+callerName+"']").size()> 1 && (callerType == "radio" || callerType == "checkbox")) { // Hack for radio/checkbox group button, the validation go the first radio/checkbox of the group + caller = $("input[name='"+callerName+"'][type!=hidden]:first"); + $.validationEngine.showTriangle = false; + } + } + /* VALIDATION FUNCTIONS */ + function _required(caller,rules){ // VALIDATE BLANK FIELD + callerType = $(caller).attr("type"); + if (callerType == "text" || callerType == "password" || callerType == "textarea"){ + + if(!$(caller).val()){ + $.validationEngine.isError = true; + promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />"; + } + } + if (callerType == "radio" || callerType == "checkbox" ){ + callerName = $(caller).attr("name"); + + if($("input[name='"+callerName+"']:checked").size() == 0) { + $.validationEngine.isError = true; + if($("input[name='"+callerName+"']").size() ==1) { + promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxe+"<br />"; + }else{ + promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxMultiple+"<br />"; + } + } + } + if (callerType == "select-one") { // added by paul@kinetek.net for select boxes, Thank you + if(!$(caller).val()) { + $.validationEngine.isError = true; + promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />"; + } + } + if (callerType == "select-multiple") { // added by paul@kinetek.net for select boxes, Thank you + if(!$(caller).find("option:selected").val()) { + $.validationEngine.isError = true; + promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />"; + } + } + } + function _customRegex(caller,rules,position){ // VALIDATE REGEX RULES + customRule = rules[position+1]; + pattern = eval($.validationEngine.settings.allrules[customRule].regex); + + if(!pattern.test($(caller).attr('value'))){ + $.validationEngine.isError = true; + promptText += $.validationEngine.settings.allrules[customRule].alertText+"<br />"; + } + } + function _ajax(caller,rules,position){ // VALIDATE AJAX RULES + + customAjaxRule = rules[position+1]; + postfile = $.validationEngine.settings.allrules[customAjaxRule].file; + fieldValue = $(caller).val(); + ajaxCaller = caller; + fieldId = $(caller).attr("id"); + ajaxValidate = true; + ajaxisError = $.validationEngine.isError; + + if(!$.validationEngine.settings.allrules[customAjaxRule].extraData){ + extraData = $.validationEngine.settings.allrules[customAjaxRule].extraData; + }else{ + extraData = ""; + } + /* AJAX VALIDATION HAS ITS OWN UPDATE AND BUILD UNLIKE OTHER RULES */ + if(!ajaxisError){ + $.ajax({ + type: "POST", + url: postfile, + async: true, + data: "validateValue="+fieldValue+"&validateId="+fieldId+"&validateError="+customAjaxRule+extraData, + beforeSend: function(){ // BUILD A LOADING PROMPT IF LOAD TEXT EXIST + if($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad){ + + if(!$("div."+fieldId+"formError")[0]){ + return $.validationEngine.buildPrompt(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load"); + }else{ + $.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load"); + } + } + }, + error: function(data,transport){ $.validationEngine.debug("error in the ajax: "+data.status+" "+transport) }, + success: function(data){ // GET SUCCESS DATA RETURN JSON + data = eval( "("+data+")"); // GET JSON DATA FROM PHP AND PARSE IT + ajaxisError = data.jsonValidateReturn[2]; + customAjaxRule = data.jsonValidateReturn[1]; + ajaxCaller = $("#"+data.jsonValidateReturn[0])[0]; + fieldId = ajaxCaller; + ajaxErrorLength = $.validationEngine.ajaxValidArray.length; + existInarray = false; + + if(ajaxisError == "false"){ // DATA FALSE UPDATE PROMPT WITH ERROR; + + _checkInArray(false) // Check if ajax validation alreay used on this field + + if(!existInarray){ // Add ajax error to stop submit + $.validationEngine.ajaxValidArray[ajaxErrorLength] = new Array(2); + $.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId; + $.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false; + existInarray = false; + } + + $.validationEngine.ajaxValid = false; + promptText += $.validationEngine.settings.allrules[customAjaxRule].alertText+"<br />"; + $.validationEngine.updatePromptText(ajaxCaller,promptText,"",true); + }else{ + _checkInArray(true); + $.validationEngine.ajaxValid = true; + if($.validationEngine.settings.allrules[customAjaxRule].alertTextOk){ // NO OK TEXT MEAN CLOSE PROMPT + $.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextOk,"pass",true); + }else{ + ajaxValidate = false; + $.validationEngine.closePrompt(ajaxCaller); + } + } + function _checkInArray(validate){ + for(x=0;x<ajaxErrorLength;x++){ + if($.validationEngine.ajaxValidArray[x][0] == fieldId){ + $.validationEngine.ajaxValidArray[x][1] = validate; + existInarray = true; + + } + } + } + } + }); + } + } + function _confirm(caller,rules,position){ // VALIDATE FIELD MATCH + confirmField = rules[position+1]; + + if($(caller).attr('value') != $("#"+confirmField).attr('value')){ + $.validationEngine.isError = true; + promptText += $.validationEngine.settings.allrules["confirm"].alertText+"<br />"; + } + } + function _length(caller,rules,position){ // VALIDATE LENGTH + + startLength = eval(rules[position+1]); + endLength = eval(rules[position+2]); + feildLength = $(caller).attr('value').length; + + if(feildLength<startLength || feildLength>endLength){ + $.validationEngine.isError = true; + promptText += $.validationEngine.settings.allrules["length"].alertText+startLength+$.validationEngine.settings.allrules["length"].alertText2+endLength+$.validationEngine.settings.allrules["length"].alertText3+"<br />" + } + } + function _maxCheckbox(caller,rules,position){ // VALIDATE CHECKBOX NUMBER + + nbCheck = eval(rules[position+1]); + groupname = $(caller).attr("name"); + groupSize = $("input[name='"+groupname+"']:checked").size(); + if(groupSize > nbCheck){ + $.validationEngine.showTriangle = false; + $.validationEngine.isError = true; + promptText += $.validationEngine.settings.allrules["maxCheckbox"].alertText+"<br />"; + } + } + function _minCheckbox(caller,rules,position){ // VALIDATE CHECKBOX NUMBER + + nbCheck = eval(rules[position+1]); + groupname = $(caller).attr("name"); + groupSize = $("input[name='"+groupname+"']:checked").size(); + if(groupSize < nbCheck){ + + $.validationEngine.isError = true; + $.validationEngine.showTriangle = false; + promptText += $.validationEngine.settings.allrules["minCheckbox"].alertText+" "+nbCheck+" "+$.validationEngine.settings.allrules["minCheckbox"].alertText2+"<br />"; + } + } + return($.validationEngine.isError) ? $.validationEngine.isError : false; + }, + submitForm : function(caller){ + if($.validationEngine.settings.ajaxSubmit){ + if($.validationEngine.settings.ajaxSubmitExtraData){ + extraData = $.validationEngine.settings.ajaxSubmitExtraData; + }else{ + extraData = ""; + } + $.ajax({ + type: "POST", + url: $.validationEngine.settings.ajaxSubmitFile, + async: true, + data: $(caller).serialize()+"&"+extraData, + error: function(data,transport){ $.validationEngine.debug("error in the ajax: "+data.status+" "+transport) }, + success: function(data){ + if(data == "true"){ // EVERYTING IS FINE, SHOW SUCCESS MESSAGE + $(caller).css("opacity",1) + $(caller).animate({opacity: 0, height: 0}, function(){ + $(caller).css("display","none"); + $(caller).before("<div class='ajaxSubmit'>"+$.validationEngine.settings.ajaxSubmitMessage+"</div>"); + $.validationEngine.closePrompt(".formError",true); + $(".ajaxSubmit").show("slow"); + if ($.validationEngine.settings.success){ // AJAX SUCCESS, STOP THE LOCATION UPDATE + $.validationEngine.settings.success && $.validationEngine.settings.success(); + return false; + } + }) + }else{ // HOUSTON WE GOT A PROBLEM (SOMETING IS NOT VALIDATING) + data = eval( "("+data+")"); + if(!data.jsonValidateReturn){ + $.validationEngine.debug("you are not going into the success fonction and jsonValidateReturn return nothing"); + } + errorNumber = data.jsonValidateReturn.length + for(index=0; index<errorNumber; index++){ + fieldId = data.jsonValidateReturn[index][0]; + promptError = data.jsonValidateReturn[index][1]; + type = data.jsonValidateReturn[index][2]; + $.validationEngine.buildPrompt(fieldId,promptError,type); + } + } + } + }) + return true; + } + if ($.validationEngine.settings.success){ // AJAX SUCCESS, STOP THE LOCATION UPDATE + if($.validationEngine.settings.unbindEngine){ $(caller).unbind("submit") } + $.validationEngine.settings.success && $.validationEngine.settings.success(); + return true; + } + return false; + }, + buildPrompt : function(caller,promptText,type,ajaxed) { // ERROR PROMPT CREATION AND DISPLAY WHEN AN ERROR OCCUR + if(!$.validationEngine.settings){ + $.validationEngine.defaultSetting() + } + var divFormError = document.createElement('div'); + var formErrorContent = document.createElement('div'); + + linkTofield = $.validationEngine.linkTofield(caller) + $(divFormError).addClass("formError") + + if(type == "pass"){ $(divFormError).addClass("greenPopup") } + if(type == "load"){ $(divFormError).addClass("blackPopup") } + if(ajaxed){ $(divFormError).addClass("ajaxed") } + + $(divFormError).addClass(linkTofield); + $(formErrorContent).addClass("formErrorContent"); + + $("body").append(divFormError); + $(divFormError).append(formErrorContent); + + if($.validationEngine.showTriangle != false){ // NO TRIANGLE ON MAX CHECKBOX AND RADIO + var arrow = document.createElement('div'); + $(arrow).addClass("formErrorArrow"); + $(divFormError).append(arrow); + if($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight"){ + $(arrow).addClass("formErrorArrowBottom") + $(arrow).html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>'); + } + if($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight"){ + $(divFormError).append(arrow); + $(arrow).html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>'); + } + } + $(formErrorContent).html(promptText) + + callerTopPosition = $(caller).offset().top; + callerleftPosition = $(caller).offset().left; + callerWidth = $(caller).width(); + inputHeight = $(divFormError).height(); + + /* POSITIONNING */ + if($.validationEngine.settings.promptPosition == "topRight"){callerleftPosition += callerWidth -30; callerTopPosition += -inputHeight -10; } + if($.validationEngine.settings.promptPosition == "topLeft"){ callerTopPosition += -inputHeight -10; } + + if($.validationEngine.settings.promptPosition == "centerRight"){ callerleftPosition += callerWidth +13; } + + if($.validationEngine.settings.promptPosition == "bottomLeft"){ + callerHeight = $(caller).height(); + callerleftPosition = callerleftPosition; + callerTopPosition = callerTopPosition + callerHeight + 15; + } + if($.validationEngine.settings.promptPosition == "bottomRight"){ + callerHeight = $(caller).height(); + callerleftPosition += callerWidth -30; + callerTopPosition += callerHeight + 15; + } + $(divFormError).css({ + top:callerTopPosition, + left:callerleftPosition, + opacity:0 + }) + return $(divFormError).animate({"opacity":0.87},function(){return true;}); + }, + updatePromptText : function(caller,promptText,type,ajaxed) { // UPDATE TEXT ERROR IF AN ERROR IS ALREADY DISPLAYED + + linkTofield = $.validationEngine.linkTofield(caller); + var updateThisPrompt = "."+linkTofield; + + if(type == "pass") { $(updateThisPrompt).addClass("greenPopup") }else{ $(updateThisPrompt).removeClass("greenPopup")}; + if(type == "load") { $(updateThisPrompt).addClass("blackPopup") }else{ $(updateThisPrompt).removeClass("blackPopup")}; + if(ajaxed) { $(updateThisPrompt).addClass("ajaxed") }else{ $(updateThisPrompt).removeClass("ajaxed")}; + + $(updateThisPrompt).find(".formErrorContent").html(promptText); + callerTopPosition = $(caller).offset().top; + inputHeight = $(updateThisPrompt).height(); + + if($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight"){ + callerHeight = $(caller).height(); + callerTopPosition = callerTopPosition + callerHeight + 15; + } + if($.validationEngine.settings.promptPosition == "centerRight"){ callerleftPosition += callerWidth +13;} + if($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight"){ + callerTopPosition = callerTopPosition -inputHeight -10; + } + $(updateThisPrompt).animate({ top:callerTopPosition }); + }, + linkTofield : function(caller){ + linkTofield = $(caller).attr("id") + "formError"; + linkTofield = linkTofield.replace(/\[/g,""); + linkTofield = linkTofield.replace(/\]/g,""); + return linkTofield; + }, + closePrompt : function(caller,outside) { // CLOSE PROMPT WHEN ERROR CORRECTED + if(!$.validationEngine.settings){ + $.validationEngine.defaultSetting() + } + if(outside){ + $(caller).fadeTo("fast",0,function(){ + $(caller).remove(); + }); + return false; + } + if(!ajaxValidate){ + linkTofield = $.validationEngine.linkTofield(caller); + closingPrompt = "."+linkTofield; + $(closingPrompt).fadeTo("fast",0,function(){ + $(closingPrompt).remove(); + }); + } + }, + debug : function(error) { + if(!$("#debugMode")[0]){ + $("body").append("<div id='debugMode'><div class='debugError'><strong>This is a debug mode, you got a problem with your form, it will try to help you, refresh when you think you nailed down the problem</strong></div></div>"); + } + $(".debugError").append("<div class='debugerror'>"+error+"</div>"); + }, + submitValidation : function(caller) { // FORM SUBMIT VALIDATION LOOPING INLINE VALIDATION + var stopForm = false; + $.validationEngine.ajaxValid = true; + $(caller).find(".formError").remove(); + var toValidateSize = $(caller).find("[class*=validate]").size(); + + $(caller).find("[class*=validate]").each(function(){ + linkTofield = $.validationEngine.linkTofield(this); + + if(!$("."+linkTofield).hasClass("ajaxed")){ // DO NOT UPDATE ALREADY AJAXED FIELDS (only happen if no normal errors, don't worry) + var validationPass = $.validationEngine.loadValidation(this); + return(validationPass) ? stopForm = true : ""; + }; + }); + ajaxErrorLength = $.validationEngine.ajaxValidArray.length; // LOOK IF SOME AJAX IS NOT VALIDATE + for(x=0;x<ajaxErrorLength;x++){ + if($.validationEngine.ajaxValidArray[x][1] == false){ + $.validationEngine.ajaxValid = false; + } + } + if(stopForm || !$.validationEngine.ajaxValid){ // GET IF THERE IS AN ERROR OR NOT FROM THIS VALIDATION FUNCTIONS + if($.validationEngine.settings.animateSubmit){ + destination = $(".formError:not('.greenPopup'):first").offset().top; + $(".formError:not('.greenPopup')").each(function(){ + testDestination = $(this).offset().top; + if(destination>testDestination){ + destination = $(this).offset().top; + } + }) + $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100); + } + return true; + }else{ + return false; + } + } +} +})(jQuery); \ No newline at end of file diff --git a/pollinator/admin_helper.php b/pollinator/admin_helper.php new file mode 100644 index 0000000..472c98d --- /dev/null +++ b/pollinator/admin_helper.php @@ -0,0 +1,42 @@ +<? + include("../pollinator/database_helper.php"); + +/** + * Print the results table, which stores all of the results + */ +function printResultsTable(){ + + print '<table class="admin"><thead>' . "\n"; + + connect(); + + // Print the header + $q = "SELECT * FROM ". QUESTIONS_TABLE; + $result = mysql_query($q) or mysql_err($q); + + print "<tr><td>ID</td>"; + while($row = mysql_fetch_assoc($result) ){ + print "<td>" . $row['content'] ."</td>"; + } + print '</tr></thead><tbody>'; + + // Print the actual results + $q = "SELECT * FROM " . RESULTS_TABLE; + $result = mysql_query($q) or mysql_err($q); + + // print out the header, access questions database for short questions + while($row = mysql_fetch_row($result) ){ + + print "<tr>"; + foreach($row as $key => $attr){ + print "<td>" . $attr . "</td>"; + } + print "</tr>"; + } + + print '</tbody></table>' ."\n"; + + disconnect(); +} + +?> \ No newline at end of file diff --git a/pollinator/database_helper.php b/pollinator/database_helper.php new file mode 100644 index 0000000..f65901e --- /dev/null +++ b/pollinator/database_helper.php @@ -0,0 +1,44 @@ +<? +// Constants +define("DATABASE", "questionator"); +define("QUESTIONS_TABLE" , "questions" ); +define("RESULTS_TABLE" , "results"); + +// Differnt values for the question types +define('Q_TEXT',0); +define('Q_YES_NO',1); +define('Q_MULTI',2); +define('Q_MULTI_EXC',3); + +function connect(){ + + $link = mysql_connect('localhost', 'root', 'root'); + + if(!$link) err("failure connecting to database..."); + + if(!@mysql_select_db(DATABASE,$link)){ + err("failure selecting the database <strong>" . DATABASE . "</strong>..."); + } + + return $link; +} + +function disconnect(){ + mysql_close(); +} + +function err($string){ + + print "Error: " . $string . "<br/>"; + exit(); +} + +function mysql_err($q){ + + print "Error in Query: " . $q. "<br/>"; + print "MySQL says: \"" . mysql_error() . "\""; + exit(); +} + + +?> diff --git a/admin/editor_helper.php b/pollinator/editor_helper.php similarity index 97% rename from admin/editor_helper.php rename to pollinator/editor_helper.php index 692ec8f..31fdac1 100644 --- a/admin/editor_helper.php +++ b/pollinator/editor_helper.php @@ -1,67 +1,67 @@ <? - include("../database_helper.php"); + include("database_helper.php"); function printQuestionsEditor(){ $link = connect(); $q = "SELECT * FROM ". QUESTIONS_TABLE; $result = mysql_query($q); if (!$result) err("error with query...\n Query=$q"); while ( $row = mysql_fetch_array($result) ) { printEditor($row); } } function printEditor($row){ $content = $row['content']; $type = $row['type']; $opts = $row['opts']; $hideOpts = "style=\"display:none;\""; if($type == Q_MULTI || $type == Q_MULTI_EXC) $hideOpts= ""; print <<< EOF <div class="question"> <div class="main"> <label>Question <span class="small">The main question</span></label> <textarea name="content">$content</textarea> <label>Type<span class="small">Type of the question</span></label> <select name="type"> EOF; // This should obviously be a list, ugly code if($type != Q_TEXT) print "<option value=\"0\">Free text</option>"; else print "<option value=\"0\" selected=\"true\">Free text</option>"; if($type != Q_YES_NO) print "<option value=\"1\">Yes / No </option>"; else print "<option value=\"1\" selected=\"true\">Yes / No </option>"; if($type != Q_MULTI) print "<option value=\"2\">List (select any)</option>"; else print "<option value=\"2\" selected=\"true\">List (select any)</option>"; if($type != Q_MULTI_EXC) print "<option value=\"3\">List (select one)</option>"; else print "<option value=\"3\" selected=\"true\">List (select one)</option>"; print <<< EOF </select> </div> <div class="opts" $hideOpts> <label>List<span class="small">Newline separated</span></label> <textarea name="opts">$opts</textarea> </div> <div class="delete"> <a href="#">Delete</a> </div> </div> EOF; } ?> \ No newline at end of file diff --git a/pollinator/editor_update.php b/pollinator/editor_update.php new file mode 100644 index 0000000..da6f9e3 --- /dev/null +++ b/pollinator/editor_update.php @@ -0,0 +1,46 @@ +<? + /** + Callback code for the editor AJAX. This code takes the edited questions + and adds them to the questions table. Currently it drops the entire + results table (lazy) to avoid conflicts and refactoring. This could be added + later by using hash values instead of question #. + */ + + include("database_helper.php"); + + // Unwrap the JSON results + $data = $_POST['questions']; + print_r($data); + connect(); + + // Dump all questions besides for the 2 key questions (name,email) + $q = "TRUNCATE TABLE " . QUESTIONS_TABLE; + $result = mysql_query($q) or mysql_err($q); + + $questions_sql = ""; $i = 0; + + foreach($data as $question){ + $content = $question["content"]; + $opts = $question["opts"]; + $type = $question["type"]; + + $q = "INSERT into " . QUESTIONS_TABLE . "(type,content,opts) VALUES('$type','$content','$opts')"; + mysql_query($q) or mysql_err($q); + + $questions_sql = $questions_sql . ",question" . ++$i . " TEXT"; + } + // insert new records for each query + + // Make a mysql CREATE TABLE query for the results table + $q = "DROP TABLE IF EXISTS " . RESULTS_TABLE; + mysql_query($q) or mysql_err($q); + + $q = "CREATE TABLE " . RESULTS_TABLE + . "(id INT NOT NULL AUTO_INCREMENT," + . "PRIMARY KEY(id)" + . $questions_sql . ")"; + + mysql_query($q) or mysql_err($q); + + // Drop the old table and make a new results table +?> diff --git a/database_helper.php b/pollinator/question_viewer.php similarity index 54% rename from database_helper.php rename to pollinator/question_viewer.php index 8361701..54366a3 100644 --- a/database_helper.php +++ b/pollinator/question_viewer.php @@ -1,172 +1,139 @@ <? - -// Constants -define("DATABASE", "questionator"); -define("QUESTIONS_TABLE" , "questions" ); -define("RESULTS_TABLE" , "results"); - -// Differnt values for the question types -define('Q_YES_NO',0); -define('Q_MULTI',1); -define('Q_TEXT',2); -define('Q_MULTI_EXC',3); - -function connect(){ - - $link = mysql_connect('localhost', 'root', 'root'); - - if(!$link) err("failure connecting to database..."); - - if(!@mysql_select_db(DATABASE,$link)){ - err("failure selecting the database <strong>" . DATABASE . "</strong>..."); - } - - return $link; -} - -function err($string){ +include("database_helper.php"); - print "Error: " . $string . "<br/>"; - print "MySQL says: \"" . mysql_error() . "\""; - exit(); -} - /** - Prints all questions stored in the Mysql database -*/ + * Prints all questions stored in the Mysql database + */ function printQuestions(){ $link = connect(); $q = "SELECT * FROM ". QUESTIONS_TABLE; - $result = mysql_query($q); - if (!$result) err("error with query...\n Query=$q"); + $result = mysql_query($q) or mysql_err($q); while ( $row = mysql_fetch_array($result) ) { printQuestion($row); } + + disconnect(); } /** - Takes an array that has "type","content", and "opts" defined and prints - an html form element based on these values. This array is normally a row from - the QUESTIONS_TABLE mysql table. -**/ + * Takes an array that has "type","content", and "opts" defined and prints + * an html form element based on these values. This array is normally a row from + * the QUESTIONS_TABLE mysql table. + */ function printQuestion($row){ // All the questions have the same sort of title print '<div> <label class="header">' . $row["content"] . "</label>"; $id = $row["id"]; $name = "question". $id; // But they differ in how the user responds to them switch($row["type"]) { case Q_YES_NO: - print '<input value="yes" type="radio" name="' . $name . '"><label>Yes</label><br/>'; - print '<input value="no" type="radio" name="' . $name . '"><label>No</label><br/>'; + printf('<input class="validate[required] radio" value="yes" type="radio" id="%s" name="%s"><label>Yes</label><br/>',$name,$name); + printf('<input class="validate[required] radio" value="no" type="radio" id="%s" name="%s"><label>No</label><br/>',$name,$name); break; case Q_MULTI: $opts = explode( "," , $row['opts']); foreach($opts as $opt){ print '<input type="checkbox" name="' . $name . $opt .'"/>'; print "<label>$opt</label><br/>"; } break; case Q_MULTI_EXC: $opts = explode( "," , $row['opts']); foreach($opts as $opt){ - print '<input value="' . $opt .'" type="radio" name="' . $name .'"/>'; + printf('<input class="validate[required] radio" value="%s" type="radio" id="%s" name="%s"/>',$opt,$name,$name); print "<label>$opt</label><br/>"; } - break; case Q_TEXT: - print '<input type="text" name="' . $name . '"/>'; + printf('<input class="validate[required,length[1,100]] text-input" type="text" id="%s" name="%s"/>',$name,$name); break; } print "</div>\n"; } -/** Process Questions -*/ -function processResults() -{ - // We can grab the name and email first, because they're not dynamic questions - $name = $_POST['name']; - $email = $_POST['email']; +/** + * Process Questions + */ +function processResults(){ - print "<p>Thanks for your interest in Widget Corporation, $name. We'll be in touch shortly!</p>"; + print "<p>Thanks for your interest in Widget Corporation. We'll be in touch shortly!</p>"; $link = connect(); // Loop through the dynamic fields $q = "SELECT * FROM ". QUESTIONS_TABLE; $result = mysql_query($q); if (!$result) err("error with query...\n Query=$q"); // store the column names, and their answers $qResults = Array(); while( $row = mysql_fetch_array($result) ) { $id = $row['id']; $name = "question" . $id; $content = $row["content"]; $r = ""; switch($row["type"]){ // multiple check boxes are a pain in the ass. case Q_MULTI: $opts = explode(",", $row['opts']); foreach($opts as $opt){ //If the value is set, then it was checked if(isset($_POST[ $name . $opt])){ $r = $r . $opt . ","; } } break; // everything else can use a standard case default: // try to gather the result for the question $r = $_POST[$name]; break; } print "<p><strong>$content</strong><br/>$r</p>"; $qResults[$name] = $r; } // end while - - // Insert a new record with the name and email filled in - $cols = "name,email"; - $values = "'$name','$email'"; + $cols = ""; $values = ""; + foreach($qResults as $key => $val) { - $cols = $cols . "," . $key; - $values = $values . ",'" . $val . "'"; + $cols = $cols . $key . ","; + $values = $values . "'" . $val . "'" . ","; } + + $cols = rtrim($cols,","); + $values = rtrim($values,","); $q = "INSERT into " . RESULTS_TABLE . " ($cols) VALUES($values)"; $result = mysql_query($q); if (!$result) err("error with query...\n Query=$q"); } - -?> +?> \ No newline at end of file diff --git a/process.php b/process.php index 92fec4f..71b680b 100644 --- a/process.php +++ b/process.php @@ -1,13 +1,13 @@ <? include("header.php") ?> <div id="container"> <h1>Thank You!</h1> <? - include("database_helper.php"); + include("pollinator/question_viewer.php"); // Process the results processResults(); ?> </div> </html></body> \ No newline at end of file diff --git a/question_parser.php b/question_parser.php deleted file mode 100644 index e69de29..0000000 diff --git a/questionator.tmproj b/questionator.tmproj index 5fc0798..bdf6009 100644 --- a/questionator.tmproj +++ b/questionator.tmproj @@ -1,215 +1,138 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>currentDocument</key> - <string>editor_node.txt</string> + <string>admin/results.php</string> <key>documents</key> <array> <dict> <key>expanded</key> <true/> <key>name</key> <string>Questionator</string> <key>regexFolderFilter</key> <string>!.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$</string> <key>sourceDirectory</key> <string></string> </dict> </array> <key>fileHierarchyDrawerWidth</key> - <integer>200</integer> + <integer>208</integer> <key>metaData</key> <dict> <key>admin/editor.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>1</integer> + <integer>20</integer> <key>line</key> - <integer>3</integer> + <integer>10</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> <key>admin/editor_helper.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>4</integer> + <integer>3</integer> <key>line</key> - <integer>63</integer> + <integer>13</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> - <integer>16</integer> + <integer>5</integer> </dict> <key>admin/index.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>24</integer> + <integer>14</integer> <key>line</key> - <integer>4</integer> + <integer>6</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> <key>admin/results.php</key> <dict> <key>caret</key> <dict> <key>column</key> - <integer>1</integer> + <integer>0</integer> <key>line</key> - <integer>6</integer> + <integer>0</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> - <key>css/main.css</key> + <key>css/admin.css</key> <dict> <key>caret</key> - <dict> - <key>column</key> - <integer>16</integer> - <key>line</key> - <integer>26</integer> - </dict> - <key>firstVisibleColumn</key> - <integer>0</integer> - <key>firstVisibleLine</key> - <integer>16</integer> - </dict> - <key>database_helper.php</key> - <dict> - <key>caret</key> - <dict> - <key>column</key> - <integer>2</integer> - <key>line</key> - <integer>46</integer> - </dict> - <key>columnSelection</key> - <false/> - <key>firstVisibleColumn</key> - <integer>0</integer> - <key>firstVisibleLine</key> - <integer>121</integer> - <key>selectFrom</key> <dict> <key>column</key> <integer>0</integer> <key>line</key> - <integer>38</integer> - </dict> - <key>selectTo</key> - <dict> - <key>column</key> - <integer>2</integer> - <key>line</key> - <integer>46</integer> - </dict> - </dict> - <key>editor_node.txt</key> - <dict> - <key>caret</key> - <dict> - <key>column</key> - <integer>25</integer> - <key>line</key> <integer>0</integer> </dict> - <key>columnSelection</key> - <false/> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> - <key>selectFrom</key> - <dict> - <key>column</key> - <integer>38</integer> - <key>line</key> - <integer>10</integer> - </dict> - <key>selectTo</key> - <dict> - <key>column</key> - <integer>25</integer> - <key>line</key> - <integer>0</integer> - </dict> </dict> <key>header.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>2</integer> <key>line</key> <integer>17</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> <key>js/editor.js</key> - <dict> - <key>caret</key> - <dict> - <key>column</key> - <integer>1</integer> - <key>line</key> - <integer>35</integer> - </dict> - <key>firstVisibleColumn</key> - <integer>0</integer> - <key>firstVisibleLine</key> - <integer>2</integer> - </dict> - <key>process.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>0</integer> <key>line</key> - <integer>10</integer> + <integer>82</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> - <integer>0</integer> + <integer>54</integer> </dict> </dict> <key>openDocuments</key> <array> - <string>process.php</string> <string>admin/editor.php</string> <string>admin/editor_helper.php</string> + <string>css/admin.css</string> <string>js/editor.js</string> - <string>editor_node.txt</string> - <string>database_helper.php</string> - <string>css/main.css</string> + <string>header.php</string> <string>admin/index.php</string> <string>admin/results.php</string> - <string>header.php</string> </array> <key>showFileHierarchyDrawer</key> <true/> <key>windowFrame</key> - <string>{{194, 53}, {1032, 725}}</string> + <string>{{264, -31}, {1032, 725}}</string> </dict> </plist>
ralphleon/Pollinator
57829889c0fb44fa8180beb0d512bca17edba283
Started working on the dynamic editor
diff --git a/admin/editor.php b/admin/editor.php index b8b21c1..ca4128f 100644 --- a/admin/editor.php +++ b/admin/editor.php @@ -1,44 +1,54 @@ <? include("../header.php") ?> +<script type="text/javascript" src="/questionator/js/jquery.js"></script> +<script type="text/javascript" src="/questionator/js/editor.js"></script> + <div id="container"> <h1>Administration</h1> - <!--<form> - <div class="question"> - <div class="main"> - <label>Question <span class="small">The main question</span></label> - - <textarea name="content"> </textarea> + <form id="editForm" action=""> + + <div id="questionsBlock"> - <label>Type<span class="small">Type of the question</span></label> - <select name="type"> - <option>Free text</option> - <option>Yes / No </option> - <option>List (select one)</option> - <option>List (select any)</option> - </select> + <!-- Sample Question --> + <div class="question" style="display:none"> + <div class="main"> + <label>Question <span class="small">The main question</span></label> + + <textarea name="content"></textarea> + + <label>Type<span class="small">Type of the question</span></label> + <select name="type"> + + <option value="0" selected="true">Free text</option>"; + <option value="1">Yes / No </option>"; + <option value="2">List (select any)</option>"; + <option value="3">List (select one)</option>"; + </select> + </div> + + <div class="opts" style="display:none"> + <label>List<span class="small">Newline separated</span></label> + <textarea name="opts"></textarea> + </div> + + <div class="delete"> + <a href="#">Delete</a> + </div> </div> - <div class="opts"> - <label>List<span class="small">Newline separated</span></label> - <textarea name="opts"> </textarea> - </div> - - <div class="delete"> - <a href="">Delete</a> - </div> + <? + include("editor_helper.php"); + printQuestionsEditor(); + ?> </div> - - </form>--> - - <? - - include("editor_helper.php"); - printQuestionsEditor(); - - - ?> + + <div id="controls"> + <input id="add" type="button" value="Add"> + <input id="submit" type="button" value="submit"/> + </div> + </form> </div> -</html></body> \ No newline at end of file +</body> \ No newline at end of file diff --git a/admin/editor_helper.php b/admin/editor_helper.php index 54c54b7..692ec8f 100644 --- a/admin/editor_helper.php +++ b/admin/editor_helper.php @@ -1,66 +1,67 @@ <? include("../database_helper.php"); function printQuestionsEditor(){ $link = connect(); $q = "SELECT * FROM ". QUESTIONS_TABLE; $result = mysql_query($q); if (!$result) err("error with query...\n Query=$q"); while ( $row = mysql_fetch_array($result) ) { printEditor($row); } } function printEditor($row){ $content = $row['content']; $type = $row['type']; $opts = $row['opts']; + $hideOpts = "style=\"display:none;\""; + + if($type == Q_MULTI || $type == Q_MULTI_EXC) $hideOpts= ""; + print <<< EOF - <form> - <div class="question"> - <div class="main"> - <label>Question <span class="small">The main question</span></label> + <div class="question"> + <div class="main"> + <label>Question <span class="small">The main question</span></label> - <textarea name="content">$content</textarea> + <textarea name="content">$content</textarea> - <label>Type<span class="small">Type of the question</span></label> - <select name="type"> + <label>Type<span class="small">Type of the question</span></label> + <select name="type"> EOF; // This should obviously be a list, ugly code if($type != Q_TEXT) print "<option value=\"0\">Free text</option>"; else print "<option value=\"0\" selected=\"true\">Free text</option>"; if($type != Q_YES_NO) print "<option value=\"1\">Yes / No </option>"; else print "<option value=\"1\" selected=\"true\">Yes / No </option>"; if($type != Q_MULTI) print "<option value=\"2\">List (select any)</option>"; else print "<option value=\"2\" selected=\"true\">List (select any)</option>"; if($type != Q_MULTI_EXC) print "<option value=\"3\">List (select one)</option>"; else print "<option value=\"3\" selected=\"true\">List (select one)</option>"; print <<< EOF - </select> - </div> - - <div class="opts"> - <label>List<span class="small">Newline separated</span></label> - <textarea name="opts">$opts</textarea> - </div> + </select> + </div> - <div class="delete"> - <a href="">Delete</a> - </div> - </div> + <div class="opts" $hideOpts> + <label>List<span class="small">Newline separated</span></label> + <textarea name="opts">$opts</textarea> + </div> - </form> + <div class="delete"> + <a href="#">Delete</a> + </div> + </div> EOF; } ?> \ No newline at end of file diff --git a/css/main.css b/css/main.css index 4c0947d..9dc0ee2 100644 --- a/css/main.css +++ b/css/main.css @@ -1,84 +1,85 @@ body { background:#222; font:14px Georgia; } label.header{ font:16px Georgia; display:block; margin:15px 0 4px 0; } input.submit{ float:right; } input.text{ width:200px; } form{ padding-bottom:20px; } #container{ width:500px; margin: 10px 50px 10px 50px; padding:30px; - background:#CCC; + background:#DDD; } /* Admin section */ div.question { margin:10px; + margin-top:40px; } div.question div.main{ background-color: #999; padding:10px; overflow: auto; width: 100% } div.question div.opts { background-color: #777; padding:10px; clear:both; overflow: auto; width: 100% } div.question label { display:block; font-weight:bold; text-align:right; width:140px; float:left; } div.question .small { color:#333; display:block; font-size:11px; font-weight:normal; text-align:right; width:140px; } div.question input,textarea,select{ float:left; font-size:12px; padding:4px 2px; border:solid 1px #aacfe4; width:200px; margin:2px 0 20px 10px; } div.question textarea{ width:60%; } div.question div.delete { display:inline; float:right; margin-right:5px; background:#FF9999; clear:both; padding:5px 10px 5px 10px; } \ No newline at end of file diff --git a/js/editor.js b/js/editor.js new file mode 100644 index 0000000..e8a046c --- /dev/null +++ b/js/editor.js @@ -0,0 +1,76 @@ + +$(document).ready(function(){ + +var Q_MULTI = 2; +var Q_MULTI_EXC = 3; + +/** Callback for selection changes in "type" + * Will hide or show the "options" box if needed + */ +$('select[name=type]').live("change",function(e){ + + // Sketchy to use 3, was having trouble with name though... this + // hides and shows the extended detail block; + var opts = this.parentNode.parentNode.childNodes[3]; + + if(this.value == Q_MULTI || this.value == Q_MULTI_EXC){ + $(opts).slideDown("slow"); + }else{ + $(opts).slideUp("slow"); + } +}); + +/** Callback for the delete button + * Removes the current block, live for newly added questions + */ +$('a').live("click",function(e){ + var parent = this.parentNode.parentNode; + $(parent).fadeOut(1000,function(){ + parent.parentNode.removeChild(parent); + }); +}); + +/** + * Button callback for the "add" button. Adds a new question editor, based + * on the first question editor +*/ +$('#add').click(function(event){ + // Clone the sample data + $('div.question:first').clone().appendTo("#questionsBlock"); + $('div.question:last').fadeIn(1000); +}); + +/** + * Callback for the submit button. + * Packages up the question data in JSON and passes it to the server + */ +$('#submit').click(function(event){ + + // Package up the current questions, loop through all elements except + // for my first element which i use for cloaning + $('#questionsBlock').find('div.question:not(div:first)').each( function( i ){ + + var content = "", opts = "", type = ""; + + // For the love of peet, why doesn't a dynamically added textbox work the same + // as a static one? Hence the two methods of accessing the 'value' + $(this).find('textarea[name=content]:first').each( function(){ + if(this.lastChild) content = this.lastChild.nodeValue; + else if(this.value) content = this.value; + }); + $(this).find('textarea[name=opts]:first').each( function(){ + if(this.lastChild) opts = this.lastChild.nodeValue; + else if(this.value) opts = this.value; + }); + + $(this).find('select[name=type]').each( function(){ + type = this.value; + }); + + alert("content " + content + " opts " + opts + " type " + type); + }); + +}); + + +}); diff --git a/js/jquery.js b/js/jquery.js new file mode 100644 index 0000000..5c70e4c --- /dev/null +++ b/js/jquery.js @@ -0,0 +1,151 @@ +/*! + * jQuery JavaScript Library v1.4 + * http://jquery.com/ + * + * Copyright 2010, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://docs.jquery.com/License + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2010, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Wed Jan 13 15:23:05 2010 -0500 + */ +(function(A,w){function oa(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(oa,1);return}c.ready()}}function La(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function $(a,b,d,f,e,i){var j=a.length;if(typeof b==="object"){for(var o in b)$(a,o,b[o],f,e,d);return a}if(d!==w){f=!i&&f&&c.isFunction(d);for(o=0;o<j;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,i);return a}return j? +e(a[0],b):null}function K(){return(new Date).getTime()}function aa(){return false}function ba(){return true}function pa(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function qa(a){var b=true,d=[],f=[],e=arguments,i,j,o,p,n,t=c.extend({},c.data(this,"events").live);for(p in t){j=t[p];if(j.live===a.type||j.altLive&&c.inArray(a.type,j.altLive)>-1){i=j.data;i.beforeFilter&&i.beforeFilter[a.type]&&!i.beforeFilter[a.type](a)||f.push(j.selector)}else delete t[p]}i=c(a.target).closest(f,a.currentTarget); +n=0;for(l=i.length;n<l;n++)for(p in t){j=t[p];o=i[n].elem;f=null;if(i[n].selector===j.selector){if(j.live==="mouseenter"||j.live==="mouseleave")f=c(a.relatedTarget).closest(j.selector)[0];if(!f||f!==o)d.push({elem:o,fn:j})}}n=0;for(l=d.length;n<l;n++){i=d[n];a.currentTarget=i.elem;a.data=i.fn.data;if(i.fn.apply(i.elem,e)===false){b=false;break}}return b}function ra(a,b){return["live",a,b.replace(/\./g,"`").replace(/ /g,"&")].join(".")}function sa(a){return!a||!a.parentNode||a.parentNode.nodeType=== +11}function ta(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var i in f)for(var j in f[i])c.event.add(this,i,f[i][j],f[i][j].data)}}})}function ua(a,b,d){var f,e,i;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&a[0].indexOf("<option")<0){e=true;if(i=c.fragments[a[0]])if(i!==1)f=i}if(!f){b=b&&b[0]?b[0].ownerDocument||b[0]:s;f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]= +i?f:1;return{fragment:f,cacheable:e}}function T(a){for(var b=0,d,f;(d=a[b])!=null;b++)if(!c.noData[d.nodeName.toLowerCase()]&&(f=d[H]))delete c.cache[f]}function L(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ma=A.jQuery,Na=A.$,s=A.document,U,Oa=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Pa=/^.[^:#\[\.,]*$/,Qa=/\S/, +Ra=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Sa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],M,ca=Object.prototype.toString,da=Object.prototype.hasOwnProperty,ea=Array.prototype.push,R=Array.prototype.slice,V=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(typeof a==="string")if((d=Oa.exec(a))&&(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Sa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])]; +c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=ua([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return U.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a)}else return!b||b.jquery?(b||U).find(a):c(b).find(a);else if(c.isFunction(a))return U.ready(a);if(a.selector!==w){this.selector=a.selector; +this.context=a.context}return c.isArray(a)?this.setArray(a):c.makeArray(a,this)},selector:"",jquery:"1.4",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){a=c(a||null);a.prevObject=this;a.context=this.context;if(b==="find")a.selector=this.selector+(this.selector?" ":"")+d;else if(b)a.selector=this.selector+"."+b+"("+d+")";return a},setArray:function(a){this.length= +0;ea.apply(this,a);return this},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject|| +c(null)},push:ea,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,i,j,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(i in e){j=a[i];o=e[i];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){j=j&&(c.isPlainObject(j)||c.isArray(j))?j:c.isArray(o)?[]:{};a[i]=c.extend(f,j,o)}else if(o!==w)a[i]= +o}return a};c.extend({noConflict:function(a){A.$=Na;if(a)A.jQuery=Ma;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",M,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange", +M);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&oa()}}},isFunction:function(a){return ca.call(a)==="[object Function]"},isArray:function(a){return ca.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||ca.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!da.call(a,"constructor")&&!da.call(a.constructor.prototype,"isPrototypeOf"))return false;var b;for(b in a);return b===w||da.call(a,b)}, +isEmptyObject:function(a){for(var b in a)return false;return true},noop:function(){},globalEval:function(a){if(a&&Qa.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,i=a.length,j=i===w||c.isFunction(a); +if(d)if(j)for(f in a){if(b.apply(a[f],d)===false)break}else for(;e<i;){if(b.apply(a[e++],d)===false)break}else if(j)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<i&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Ra,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ea.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d= +0,f=b.length;d<f;d++)if(b[d]===a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,i=a.length;e<i;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,i=0,j=a.length;i<j;i++){e=b(a[i],i,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b=== +"string"){d=a;a=d[b];b=w}else if(b&&!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){var b={browser:""};a=a.toLowerCase();if(/webkit/.test(a))b={browser:"webkit",version:/webkit[\/ ]([\w.]+)/};else if(/opera/.test(a))b={browser:"opera",version:/version/.test(a)?/version[\/ ]([\w.]+)/:/opera[\/ ]([\w.]+)/};else if(/msie/.test(a))b={browser:"msie",version:/msie ([\w.]+)/};else if(/mozilla/.test(a)&& +!/compatible/.test(a))b={browser:"mozilla",version:/rv:([\w.]+)/};b.version=(b.version&&b.version.exec(a)||[0,"0"])[1];return b},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=true;if(V)c.inArray=function(a,b){return V.call(b,a)};U=c(s);if(s.addEventListener)M=function(){s.removeEventListener("DOMContentLoaded",M,false);c.ready()};else if(s.attachEvent)M=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange", +M);c.ready()}};if(V)c.inArray=function(a,b){return V.call(b,a)};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+K();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=d.getElementsByTagName("*"),i=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!i)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length, +htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(i.getAttribute("style")),hrefNormalized:i.getAttribute("href")==="/a",opacity:/^0.55$/.test(i.style.opacity),cssFloat:!!i.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(j){}a.insertBefore(b, +a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function o(){c.support.noCloneEvent=false;d.detachEvent("onclick",o)});d.cloneNode(true).fireEvent("onclick")}c(function(){var o=s.createElement("div");o.style.width=o.style.paddingLeft="1px";s.body.appendChild(o);c.boxModel=c.support.boxModel=o.offsetWidth===2;s.body.removeChild(o).style.display="none"});a=function(o){var p=s.createElement("div");o="on"+o;var n=o in +p;if(!n){p.setAttribute(o,"return;");n=typeof p[o]==="function"}return n};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=i=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var H="jQuery"+K(),Ta=0,ya={},Ua={};c.extend({cache:{},expando:H,noData:{embed:true,object:true,applet:true},data:function(a, +b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?ya:a;var f=a[H],e=c.cache;if(!b&&!f)return null;f||(f=++Ta);if(typeof b==="object"){a[H]=f;e=e[f]=c.extend(true,{},b)}else e=e[f]?e[f]:typeof d==="undefined"?Ua:(e[f]={});if(d!==w){a[H]=f;e[b]=d}return typeof b==="string"?e[b]:e}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?ya:a;var d=a[H],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{try{delete a[H]}catch(i){a.removeAttribute&& +a.removeAttribute(H)}delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,a,b)})},removeData:function(a){return this.each(function(){c.removeData(this, +a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this, +a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var za=/[\n\t]/g,fa=/\s+/,Va=/\r/g,Wa=/href|src|style/,Xa=/(button|input)/i,Ya=/(button|input|object|select|textarea)/i,Za=/^(a|area)$/i,Aa=/radio|checkbox/;c.fn.extend({attr:function(a, +b){return $(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(p){var n=c(this);n.addClass(a.call(this,p,n.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(fa),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className)for(var i=" "+e.className+" ",j=0,o=b.length;j<o;j++){if(i.indexOf(" "+b[j]+" ")<0)e.className+= +" "+b[j]}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(p){var n=c(this);n.removeClass(a.call(this,p,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(fa),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var i=(" "+e.className+" ").replace(za," "),j=0,o=b.length;j<o;j++)i=i.replace(" "+b[j]+" "," ");e.className=i.substring(1,i.length-1)}else e.className=""}return this},toggleClass:function(a, +b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var i=c(this);i.toggleClass(a.call(this,e,i.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,i=0,j=c(this),o=b,p=a.split(fa);e=p[i++];){o=f?o:!j.hasClass(e);j[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a= +" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(za," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var i=b?d:0;for(d=b?d+1:e.length;i<d;i++){var j=e[i];if(j.selected){a=c(j).val();if(b)return a;f.push(a)}}return f}if(Aa.test(b.type)&& +!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Va,"")}return w}var o=c.isFunction(a);return this.each(function(p){var n=c(this),t=a;if(this.nodeType===1){if(o)t=a.call(this,p,n.val());if(typeof t==="number")t+="";if(c.isArray(t)&&Aa.test(this.type))this.checked=c.inArray(n.val(),t)>=0;else if(c.nodeName(this,"select")){var z=c.makeArray(t);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),z)>=0});if(!z.length)this.selectedIndex= +-1}else this.value=t}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var i=Wa.test(b);if(b in a&&f&&!i){if(e){if(b==="type"&&Xa.test(a.nodeName)&&a.parentNode)throw"type property can't be changed";a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue; +if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:Ya.test(a.nodeName)||Za.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&i?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var $a=function(a){return a.replace(/[^\w\s\.\|`]/g,function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType=== +3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;if(!d.guid)d.guid=c.guid++;if(f!==w){d=c.proxy(d);d.data=f}var e=c.data(a,"events")||c.data(a,"events",{}),i=c.data(a,"handle"),j;if(!i){j=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(j.elem,arguments):w};i=c.data(a,"handle",j)}if(i){i.elem=a;b=b.split(/\s+/);for(var o,p=0;o=b[p++];){var n=o.split(".");o=n.shift();d.type=n.slice(0).sort().join(".");var t=e[o],z=this.special[o]||{};if(!t){t=e[o]={}; +if(!z.setup||z.setup.call(a,f,n,d)===false)if(a.addEventListener)a.addEventListener(o,i,false);else a.attachEvent&&a.attachEvent("on"+o,i)}if(z.add)if((n=z.add.call(a,d,f,n,t))&&c.isFunction(n)){n.guid=n.guid||d.guid;d=n}t[d.guid]=d;this.global[o]=true}a=null}}},global:{},remove:function(a,b,d){if(!(a.nodeType===3||a.nodeType===8)){var f=c.data(a,"events"),e,i,j;if(f){if(b===w||typeof b==="string"&&b.charAt(0)===".")for(i in f)this.remove(a,i+(b||""));else{if(b.type){d=b.handler;b=b.type}b=b.split(/\s+/); +for(var o=0;i=b[o++];){var p=i.split(".");i=p.shift();var n=!p.length,t=c.map(p.slice(0).sort(),$a);t=new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.)?")+"(\\.|$)");var z=this.special[i]||{};if(f[i]){if(d){j=f[i][d.guid];delete f[i][d.guid]}else for(var B in f[i])if(n||t.test(f[i][B].type))delete f[i][B];z.remove&&z.remove.call(a,p,j);for(e in f[i])break;if(!e){if(!z.teardown||z.teardown.call(a,p)===false)if(a.removeEventListener)a.removeEventListener(i,c.data(a,"handle"),false);else a.detachEvent&&a.detachEvent("on"+ +i,c.data(a,"handle"));e=null;delete f[i]}}}}for(e in f)break;if(!e){if(B=c.data(a,"handle"))B.elem=null;c.removeData(a,"events");c.removeData(a,"handle")}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[H]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();this.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType=== +8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;var i=c.data(d,"handle");i&&i.apply(d,b);var j,o;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()])){j=d[e];o=d["on"+e]}}catch(p){}i=c.nodeName(d,"a")&&e==="click";if(!f&&j&&!a.isDefaultPrevented()&&!i){this.triggered=true;try{d[e]()}catch(n){}}else if(o&&d["on"+e].apply(d,b)===false)a.result=false;this.triggered=false;if(!a.isPropagationStopped())(d=d.parentNode||d.ownerDocument)&&c.event.trigger(a,b,d,true)}, +handle:function(a){var b,d;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;d=a.type.split(".");a.type=d.shift();b=!d.length&&!a.exclusive;var f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)");d=(c.data(this,"events")||{})[a.type];for(var e in d){var i=d[e];if(b||f.test(i.type)){a.handler=i;a.data=i.data;i=i.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}return a.result}, +props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[H])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement|| +s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&& +a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a,b){c.extend(a,b||{});a.guid+=b.selector+b.live;c.event.add(this,b.live,qa,b)},remove:function(a){if(a.length){var b=0,d=new RegExp("(^|\\.)"+a[0]+"(\\.|$)");c.each(c.data(this,"events").live||{},function(){d.test(this.type)&&b++});b<1&&c.event.remove(this,a[0],qa)}},special:{}},beforeunload:{setup:function(a, +b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=K();this[H]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ba;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped= +ba;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ba;this.stopPropagation()},isDefaultPrevented:aa,isPropagationStopped:aa,isImmediatePropagationStopped:aa};var Ba=function(a){for(var b=a.relatedTarget;b&&b!==this;)try{b=b.parentNode}catch(d){break}if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}},Ca=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover", +mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ca:Ba,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ca:Ba)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(a,b,d){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit."+d.guid,function(f){var e=f.target,i=e.type;if((i==="submit"||i==="image")&&c(e).closest("form").length)return pa("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit."+ +d.guid,function(f){var e=f.target,i=e.type;if((i==="text"||i==="password")&&c(e).closest("form").length&&f.keyCode===13)return pa("submit",this,arguments)})}else return false},remove:function(a,b){c.event.remove(this,"click.specialSubmit"+(b?"."+b.guid:""));c.event.remove(this,"keypress.specialSubmit"+(b?"."+b.guid:""))}};if(!c.support.changeBubbles){var ga=/textarea|input|select/i;function Da(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex> +-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d}function ha(a,b){var d=a.target,f,e;if(!(!ga.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Da(d);if(e!==f){if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",e);if(d.type!=="select"&&(f!=null||e)){a.type="change";return c.event.trigger(a,b,this)}}}}c.event.special.change={filters:{focusout:ha,click:function(a){var b=a.target,d=b.type;if(d=== +"radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return ha.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return ha.call(this,a)},beforeactivate:function(a){a=a.target;a.nodeName.toLowerCase()==="input"&&a.type==="radio"&&c.data(a,"_change_data",Da(a))}},setup:function(a,b,d){for(var f in W)c.event.add(this,f+".specialChange."+d.guid,W[f]);return ga.test(this.nodeName)}, +remove:function(a,b){for(var d in W)c.event.remove(this,d+".specialChange"+(b?"."+b.guid:""),W[d]);return ga.test(this.nodeName)}};var W=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d, +f,e){if(typeof d==="object"){for(var i in d)this[b](i,f,d[i],e);return this}if(c.isFunction(f)){thisObject=e;e=f;f=w}var j=b==="one"?c.proxy(e,function(o){c(this).unbind(o,j);return e.apply(this,arguments)}):e;return d==="unload"&&b!=="one"?this.one(d,f,e,thisObject):this.each(function(){c.event.add(this,d,j,f)})}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault){for(var d in a)this.unbind(d,a[d]);return this}return this.each(function(){c.event.remove(this,a,b)})},trigger:function(a, +b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b|| +a)},live:function(a,b,d){if(c.isFunction(b)){d=b;b=w}c(this.context).bind(ra(a,this.selector),{data:b,selector:this.selector,live:a},d);return this},die:function(a,b){c(this.context).unbind(ra(a,this.selector),b?{guid:b.guid+this.selector+a}:null);return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d){return d? +this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",k,m=0;g[m];m++){k=g[m];if(k.nodeType===3||k.nodeType===4)h+=k.nodeValue;else if(k.nodeType!==8)h+=a(k.childNodes)}return h}function b(g,h,k,m,r,q){r=0;for(var v=m.length;r<v;r++){var u=m[r];if(u){u=u[g];for(var y=false;u;){if(u.sizcache=== +k){y=m[u.sizset];break}if(u.nodeType===1&&!q){u.sizcache=k;u.sizset=r}if(u.nodeName.toLowerCase()===h){y=u;break}u=u[g]}m[r]=y}}}function d(g,h,k,m,r,q){r=0;for(var v=m.length;r<v;r++){var u=m[r];if(u){u=u[g];for(var y=false;u;){if(u.sizcache===k){y=m[u.sizset];break}if(u.nodeType===1){if(!q){u.sizcache=k;u.sizset=r}if(typeof h!=="string"){if(u===h){y=true;break}}else if(p.filter(h,[u]).length>0){y=u;break}}u=u[g]}m[r]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, +e=0,i=Object.prototype.toString,j=false,o=true;[0,0].sort(function(){o=false;return 0});var p=function(g,h,k,m){k=k||[];var r=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return k;for(var q=[],v,u,y,S,I=true,N=x(h),J=g;(f.exec(""),v=f.exec(J))!==null;){J=v[3];q.push(v[1]);if(v[2]){S=v[3];break}}if(q.length>1&&t.exec(g))if(q.length===2&&n.relative[q[0]])u=ia(q[0]+q[1],h);else for(u=n.relative[q[0]]?[h]:p(q.shift(),h);q.length;){g=q.shift();if(n.relative[g])g+=q.shift(); +u=ia(g,u)}else{if(!m&&q.length>1&&h.nodeType===9&&!N&&n.match.ID.test(q[0])&&!n.match.ID.test(q[q.length-1])){v=p.find(q.shift(),h,N);h=v.expr?p.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:q.pop(),set:B(m)}:p.find(q.pop(),q.length===1&&(q[0]==="~"||q[0]==="+")&&h.parentNode?h.parentNode:h,N);u=v.expr?p.filter(v.expr,v.set):v.set;if(q.length>0)y=B(u);else I=false;for(;q.length;){var E=q.pop();v=E;if(n.relative[E])v=q.pop();else E="";if(v==null)v=h;n.relative[E](y,v,N)}}else y=[]}y||(y=u);if(!y)throw"Syntax error, unrecognized expression: "+ +(E||g);if(i.call(y)==="[object Array]")if(I)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&F(h,y[g])))k.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&k.push(u[g]);else k.push.apply(k,y);else B(y,k);if(S){p(S,r,k,m);p.uniqueSort(k)}return k};p.uniqueSort=function(g){if(D){j=o;g.sort(D);if(j)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};p.matches=function(g,h){return p(g,null,null,h)};p.find=function(g,h,k){var m,r;if(!g)return[]; +for(var q=0,v=n.order.length;q<v;q++){var u=n.order[q];if(r=n.leftMatch[u].exec(g)){var y=r[1];r.splice(1,1);if(y.substr(y.length-1)!=="\\"){r[1]=(r[1]||"").replace(/\\/g,"");m=n.find[u](r,h,k);if(m!=null){g=g.replace(n.match[u],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};p.filter=function(g,h,k,m){for(var r=g,q=[],v=h,u,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var I in n.filter)if((u=n.leftMatch[I].exec(g))!=null&&u[2]){var N=n.filter[I],J,E;E=u[1];y=false;u.splice(1,1);if(E.substr(E.length- +1)!=="\\"){if(v===q)q=[];if(n.preFilter[I])if(u=n.preFilter[I](u,v,k,q,m,S)){if(u===true)continue}else y=J=true;if(u)for(var X=0;(E=v[X])!=null;X++)if(E){J=N(E,u,X,v);var Ea=m^!!J;if(k&&J!=null)if(Ea)y=true;else v[X]=false;else if(Ea){q.push(E);y=true}}if(J!==w){k||(v=q);g=g.replace(n.match[I],"");if(!y)return[];break}}}if(g===r)if(y==null)throw"Syntax error, unrecognized expression: "+g;else break;r=g}return v};var n=p.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, +CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}}, +relative:{"+":function(g,h){var k=typeof h==="string",m=k&&!/\W/.test(h);k=k&&!m;if(m)h=h.toLowerCase();m=0;for(var r=g.length,q;m<r;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=k||q&&q.nodeName.toLowerCase()===h?q||false:q===h}k&&p.filter(h,g,true)},">":function(g,h){var k=typeof h==="string";if(k&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,r=g.length;m<r;m++){var q=g[m];if(q){k=q.parentNode;g[m]=k.nodeName.toLowerCase()===h?k:false}}}else{m=0;for(r=g.length;m<r;m++)if(q=g[m])g[m]= +k?q.parentNode:q.parentNode===h;k&&p.filter(h,g,true)}},"":function(g,h,k){var m=e++,r=d;if(typeof h==="string"&&!/\W/.test(h)){var q=h=h.toLowerCase();r=b}r("parentNode",h,m,g,q,k)},"~":function(g,h,k){var m=e++,r=d;if(typeof h==="string"&&!/\W/.test(h)){var q=h=h.toLowerCase();r=b}r("previousSibling",h,m,g,q,k)}},find:{ID:function(g,h,k){if(typeof h.getElementById!=="undefined"&&!k)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var k=[]; +h=h.getElementsByName(g[1]);for(var m=0,r=h.length;m<r;m++)h[m].getAttribute("name")===g[1]&&k.push(h[m]);return k.length===0?null:k}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,k,m,r,q){g=" "+g[1].replace(/\\/g,"")+" ";if(q)return g;q=0;for(var v;(v=h[q])!=null;q++)if(v)if(r^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))k||m.push(v);else if(k)h[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, +CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,k,m,r,q){h=g[1].replace(/\\/g,"");if(!q&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,k,m,r){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=p(g[3],null,null,h);else{g=p.filter(g[3],h,k,true^r);k||m.push.apply(m, +g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,k){return!!p(k[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, +text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, +setFilters:{first:function(g,h){return h===0},last:function(g,h,k,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,k){return h<k[3]-0},gt:function(g,h,k){return h>k[3]-0},nth:function(g,h,k){return k[3]-0===h},eq:function(g,h,k){return k[3]-0===h}},filter:{PSEUDO:function(g,h,k,m){var r=h[1],q=n.filters[r];if(q)return q(g,k,h,m);else if(r==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(r==="not"){h= +h[3];k=0;for(m=h.length;k<m;k++)if(h[k]===g)return false;return true}else throw"Syntax error, unrecognized expression: "+r;},CHILD:function(g,h){var k=h[1],m=g;switch(k){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(k==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":k=h[2];var r=h[3];if(k===1&&r===0)return true;h=h[0];var q=g.parentNode;if(q&&(q.sizcache!==h||!g.nodeIndex)){var v=0;for(m=q.firstChild;m;m= +m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;q.sizcache=h}g=g.nodeIndex-r;return k===0?g===0:g%k===0&&g/k>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var k=h[1];g=n.attrHandle[k]?n.attrHandle[k](g):g[k]!=null?g[k]:g.getAttribute(k);k=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== +"="?k===h:m==="*="?k.indexOf(h)>=0:m==="~="?(" "+k+" ").indexOf(h)>=0:!h?k&&g!==false:m==="!="?k!==h:m==="^="?k.indexOf(h)===0:m==="$="?k.substr(k.length-h.length)===h:m==="|="?k===h||k.substr(0,h.length+1)===h+"-":false},POS:function(g,h,k,m){var r=n.setFilters[h[2]];if(r)return r(g,k,h,m)}}},t=n.match.POS;for(var z in n.match){n.match[z]=new RegExp(n.match[z].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[z]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[z].source.replace(/\\(\d+)/g,function(g, +h){return"\\"+(h-0+1)}))}var B=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){B=function(g,h){h=h||[];if(i.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var k=0,m=g.length;k<m;k++)h.push(g[k]);else for(k=0;g[k];k++)h.push(g[k]);return h}}var D;if(s.documentElement.compareDocumentPosition)D=function(g,h){if(!g.compareDocumentPosition|| +!h.compareDocumentPosition){if(g==h)j=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)j=true;return g};else if("sourceIndex"in s.documentElement)D=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)j=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)j=true;return g};else if(s.createRange)D=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)j=true;return g.ownerDocument?-1:1}var k=g.ownerDocument.createRange(),m= +h.ownerDocument.createRange();k.setStart(g,0);k.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=k.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)j=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var k=s.documentElement;k.insertBefore(g,k.firstChild);if(s.getElementById(h)){n.find.ID=function(m,r,q){if(typeof r.getElementById!=="undefined"&&!q)return(r=r.getElementById(m[1]))?r.id===m[1]||typeof r.getAttributeNode!=="undefined"&& +r.getAttributeNode("id").nodeValue===m[1]?[r]:w:[]};n.filter.ID=function(m,r){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===r}}k.removeChild(g);k=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,k){k=k.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;k[m];m++)k[m].nodeType===1&&h.push(k[m]);k=h}return k};g.innerHTML="<a href='#'></a>"; +if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=p,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){p=function(m,r,q,v){r=r||s;if(!v&&r.nodeType===9&&!x(r))try{return B(r.querySelectorAll(m),q)}catch(u){}return g(m,r,q,v)};for(var k in g)p[k]=g[k];h=null}}(); +(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,k,m){if(typeof k.getElementsByClassName!=="undefined"&&!m)return k.getElementsByClassName(h[1])};g=null}}})();var F=s.compareDocumentPosition?function(g,h){return g.compareDocumentPosition(h)&16}:function(g, +h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ia=function(g,h){var k=[],m="",r;for(h=h.nodeType?[h]:h;r=n.match.PSEUDO.exec(g);){m+=r[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;r=0;for(var q=h.length;r<q;r++)p(g,h[r],k);return p.filter(m,k)};c.find=p;c.expr=p.selectors;c.expr[":"]=c.expr.filters;c.unique=p.uniqueSort;c.getText=a;c.isXMLDoc=x;c.contains=F})();var ab=/Until$/,bb=/^(?:parents|prevUntil|prevAll)/, +cb=/,/;R=Array.prototype.slice;var Fa=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,i){return!!b.call(e,i,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Pa.test(b))return c.filter(b,f,!d);else b=c.filter(b,a)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; +c.find(a,this[f],b);if(f>0)for(var i=d;i<b.length;i++)for(var j=0;j<d;j++)if(b[j]===b[i]){b.splice(i--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Fa(this,a,false),"not",a)},filter:function(a){return this.pushStack(Fa(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,i= +{},j;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){j=a[e];i[j]||(i[j]=c.expr.match.POS.test(j)?c(j,b||this.context):j)}for(;f&&f.ownerDocument&&f!==b;){for(j in i){e=i[j];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:j,elem:f});delete i[j]}}f=f.parentNode}}return d}var p=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,t){for(;t&&t.ownerDocument&&t!==b;){if(p?p.index(t)>-1:c(t).is(a))return t;t=t.parentNode}return null})},index:function(a){if(!a||typeof a=== +"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(sa(a[0])||sa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", +d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? +a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);ab.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||cb.test(f))&&bb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||!c(a).is(d));){a.nodeType=== +1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ga=/ jQuery\d+="(?:\d+|null)"/g,Y=/^\s+/,db=/(<([\w:]+)[^>]*?)\/>/g,eb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,Ha=/<([\w:]+)/,fb=/<tbody/i,gb=/<|&\w+;/,hb=function(a,b,d){return eb.test(d)?a:b+"></"+d+">"},G={option:[1,"<select multiple='multiple'>","</select>"], +legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};G.optgroup=G.option;G.tbody=G.tfoot=G.colgroup=G.caption=G.thead;G.th=G.td;if(!c.support.htmlSerialize)G._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this); +return d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.getText(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, +wrapInner:function(a){return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&& +this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this.nextSibling)});else if(arguments.length){var a=this.pushStack(this, +"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ga,"").replace(Y,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ta(this,b);ta(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType=== +1?this[0].innerHTML.replace(Ga,""):null;else if(typeof a==="string"&&!/<script/i.test(a)&&(c.support.leadingWhitespace||!Y.test(a))&&!G[(Ha.exec(a)||["",""])[1].toLowerCase()])try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){T(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}else c.isFunction(a)?this.each(function(e){var i=c(this),j=i.html();i.empty().append(function(){return a.call(this,e,j)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& +this[0].parentNode){c.isFunction(a)||(a=c(a).detach());return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(t){return c.nodeName(t,"table")?t.getElementsByTagName("tbody")[0]||t.appendChild(t.ownerDocument.createElement("tbody")):t}var e,i,j=a[0],o=[];if(c.isFunction(j))return this.each(function(t){var z= +c(this);a[0]=j.call(this,t,b?z.html():w);return z.domManip(a,b,d)});if(this[0]){e=a[0]&&a[0].parentNode&&a[0].parentNode.nodeType===11?{fragment:a[0].parentNode}:ua(a,this,o);if(i=e.fragment.firstChild){b=b&&c.nodeName(i,"tr");for(var p=0,n=this.length;p<n;p++)d.call(b?f(this[p],i):this[p],e.cacheable||this.length>1||p>0?e.fragment.cloneNode(true):e.fragment)}o&&c.each(o,La)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"}, +function(a,b){c.fn[a]=function(d){var f=[];d=c(d);for(var e=0,i=d.length;e<i;e++){var j=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),j);f=f.concat(j)}return this.pushStack(f,a,d.selector)}});c.each({remove:function(a,b){if(!a||c.filter(a,[this]).length){if(!b&&this.nodeType===1){T(this.getElementsByTagName("*"));T([this])}this.parentNode&&this.parentNode.removeChild(this)}},empty:function(){for(this.nodeType===1&&T(this.getElementsByTagName("*"));this.firstChild;)this.removeChild(this.firstChild)}}, +function(a,b){c.fn[a]=function(){return this.each(b,arguments)}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;var e=[];c.each(a,function(i,j){if(typeof j==="number")j+="";if(j){if(typeof j==="string"&&!gb.test(j))j=b.createTextNode(j);else if(typeof j==="string"){j=j.replace(db,hb);var o=(Ha.exec(j)||["",""])[1].toLowerCase(),p=G[o]||G._default,n=p[0];i=b.createElement("div");for(i.innerHTML=p[1]+j+p[2];n--;)i=i.lastChild; +if(!c.support.tbody){n=fb.test(j);o=o==="table"&&!n?i.firstChild&&i.firstChild.childNodes:p[1]==="<table>"&&!n?i.childNodes:[];for(p=o.length-1;p>=0;--p)c.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!c.support.leadingWhitespace&&Y.test(j)&&i.insertBefore(b.createTextNode(Y.exec(j)[0]),i.firstChild);j=c.makeArray(i.childNodes)}if(j.nodeType)e.push(j);else e=c.merge(e,j)}});if(d)for(a=0;e[a];a++)if(f&&c.nodeName(e[a],"script")&&(!e[a].type||e[a].type.toLowerCase()=== +"text/javascript"))f.push(e[a].parentNode?e[a].parentNode.removeChild(e[a]):e[a]);else{e[a].nodeType===1&&e.splice.apply(e,[a+1,0].concat(c.makeArray(e[a].getElementsByTagName("script"))));d.appendChild(e[a])}return e}});var ib=/z-?index|font-?weight|opacity|zoom|line-?height/i,Ia=/alpha\([^)]*\)/,Ja=/opacity=([^)]*)/,ja=/float/i,ka=/-([a-z])/ig,jb=/([A-Z])/g,kb=/^-?\d+(?:px)?$/i,lb=/^-?\d/,mb={position:"absolute",visibility:"hidden",display:"block"},nb=["Left","Right"],ob=["Top","Bottom"],pb=s.defaultView&& +s.defaultView.getComputedStyle,Ka=c.support.cssFloat?"cssFloat":"styleFloat",la=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return $(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!ib.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""=== +"NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=Ia.test(a)?a.replace(Ia,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Ja.exec(f.filter)[1])/100+"":""}if(ja.test(b))b=Ka;b=b.replace(ka,la);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,i=b==="width"?nb:ob;function j(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(i,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+= +parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,"border"+this+"Width",true))||0})}a.offsetWidth!==0?j():c.swap(a,mb,j);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Ja.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ja.test(b))b=Ka;if(!d&&e&&e[b])f=e[b];else if(pb){if(ja.test(b))b="float";b=b.replace(jb,"-$1").toLowerCase();e= +a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ka,la);f=a.currentStyle[b]||a.currentStyle[d];if(!kb.test(f)&&lb.test(f)){b=e.left;var i=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=i}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]= +f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var qb=K(),rb=/<script(.|\s)*?\/script>/gi,sb=/select|textarea/i,tb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,O=/=\?(&|$)/,ma=/\?/,ub=/(\?|&)_=.*?(&|$)/,vb=/^(\w+:)?\/\/([^\/?#]+)/, +wb=/%20/g;c.fn.extend({_load:c.fn.load,load:function(a,b,d){if(typeof a!=="string")return this._load(a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}c.ajax({url:a,type:f,dataType:"html",data:b,context:this,complete:function(i,j){if(j==="success"||j==="notmodified")this.html(e?c("<div />").append(i.responseText.replace(rb, +"")).find(e):i.responseText);d&&this.each(d,[i.responseText,j,i])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||sb.test(this.nodeName)||tb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}}); +c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})}, +ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript", +text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&e.success.call(p,o,j,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(p,x,j);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(r,q){(e.context?c(e.context):c.event).trigger(r,q)}var e=c.extend(true,{},c.ajaxSettings,a),i,j,o,p=e.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data, +e.traditional);if(e.dataType==="jsonp"){if(n==="GET")O.test(e.url)||(e.url+=(ma.test(e.url)?"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!O.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&O.test(e.data)||O.test(e.url))){i=e.jsonpCallback||"jsonp"+qb++;if(e.data)e.data=(e.data+"").replace(O,"="+i+"$1");e.url=e.url.replace(O,"="+i+"$1");e.dataType="script";A[i]=A[i]||function(r){o=r;b();d();A[i]=w;try{delete A[i]}catch(q){}B&& +B.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===false&&n==="GET"){var t=K(),z=e.url.replace(ub,"$1_="+t+"$2");e.url=z+(z===e.url?(ma.test(e.url)?"&":"?")+"_="+t:"")}if(e.data&&n==="GET")e.url+=(ma.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");t=(t=vb.exec(e.url))&&(t[1]&&t[1]!==location.protocol||t[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&t){var B=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script"); +C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!i){var D=false;C.onload=C.onreadystatechange=function(){if(!D&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){D=true;b();d();C.onload=C.onreadystatechange=null;B&&C.parentNode&&B.removeChild(C)}}}B.insertBefore(C,B.firstChild);return w}var F=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type", +e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}t||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ia){}if(e.beforeSend&&e.beforeSend.call(p,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend", +[x,e]);var g=x.onreadystatechange=function(r){if(!x||x.readyState===0){F||d();F=true;if(x)x.onreadystatechange=c.noop}else if(!F&&x&&(x.readyState===4||r==="timeout")){F=true;x.onreadystatechange=c.noop;j=r==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";if(j==="success")try{o=c.httpData(x,e.dataType,e)}catch(q){j="parsererror"}if(j==="success"||j==="notmodified")i||b();else c.handleError(e,x,j);d();r==="timeout"&&x.abort();if(e.async)x= +null}};try{var h=x.abort;x.abort=function(){if(x){h.call(x);if(x)x.readyState=0}g()}}catch(k){}e.async&&e.timeout>0&&setTimeout(function(){x&&!F&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||A,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol=== +"file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;if(e&&a.documentElement.nodeName==="parsererror")throw"parsererror";if(d&& +d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&f.indexOf("json")>=0)if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))a=A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+a))();else throw"Invalid JSON: "+a;else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(e,i){i= +c.isFunction(i)?i():i;f[f.length]=encodeURIComponent(e)+"="+encodeURIComponent(i)}var f=[];if(b===w)b=c.ajaxSettings.traditional;c.isArray(a)||a.jquery?c.each(a,function(){d(this.name,this.value)}):c.each(a,function e(i,j){if(c.isArray(j))c.each(j,function(o,p){b?d(i,p):e(i+"["+(typeof p==="object"||c.isArray(p)?o:"")+"]",p)});else!b&&j!=null&&typeof j==="object"?c.each(j,function(o,p){e(i+"["+o+"]",p)}):d(i,j)});return f.join("&").replace(wb,"+")}});var na={},xb=/toggle|show|hide/,yb=/^([+-]=)?([\d+-.]+)(.*)$/, +Z,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a!=null)return this.animate(L("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(na[d])f=na[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove(); +na[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a!=null)return this.animate(L("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&& +c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(L("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var i=c.extend({},e),j,o=this.nodeType===1&&c(this).is(":hidden"), +p=this;for(j in a){var n=j.replace(ka,la);if(j!==n){a[n]=a[j];delete a[j];j=n}if(a[j]==="hide"&&o||a[j]==="show"&&!o)return i.complete.call(this);if((j==="height"||j==="width")&&this.style){i.display=c.css(this,"display");i.overflow=this.style.overflow}if(c.isArray(a[j])){(i.specialEasing=i.specialEasing||{})[j]=a[j][1];a[j]=a[j][0]}}if(i.overflow!=null)this.style.overflow="hidden";i.curAnim=c.extend({},a);c.each(a,function(t,z){var B=new c.fx(p,i,t);if(xb.test(z))B[z==="toggle"?o?"show":"hide":z](a); +else{var C=yb.exec(z),D=B.cur(true)||0;if(C){z=parseFloat(C[2]);var F=C[3]||"px";if(F!=="px"){p.style[t]=(z||1)+F;D=(z||1)/B.cur(true)*D;p.style[t]=D+F}if(C[1])z=(C[1]==="-="?-1:1)*z+D;B.custom(D,z,F)}else B.custom(D,z,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:L("show",1),slideUp:L("hide",1),slideToggle:L("toggle", +1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration==="number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a, +b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]== +null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(i){return e.step(i)}this.startTime=K();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!Z)Z=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop=== +"width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=K(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow= +this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos= +c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},stop:function(){clearInterval(Z);Z=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!= +null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(), +f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(t){c.offset.setOffset(this,a,t)});if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f= +b,e=b.ownerDocument,i,j=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var p=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==j;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;i=e?e.getComputedStyle(b,null):b.currentStyle;p-=b.scrollTop;n-=b.scrollLeft;if(b===d){p+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){p+=parseFloat(i.borderTopWidth)|| +0;n+=parseFloat(i.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&i.overflow!=="visible"){p+=parseFloat(i.borderTopWidth)||0;n+=parseFloat(i.borderLeftWidth)||0}f=i}if(f.position==="relative"||f.position==="static"){p+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&f.position==="fixed"){p+=Math.max(j.scrollTop,o.scrollTop);n+=Math.max(j.scrollLeft,o.scrollLeft)}return{top:p,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"), +d,f,e,i=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild); +d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i;a.removeChild(b);c.offset.initialize=c.noop}, +bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),i=parseInt(c.curCSS(a,"top",true),10)||0,j=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,d,e);d={top:b.top-e.top+i,left:b.left- +e.left+j};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a= +this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],i;if(!e)return null;if(f!==w)return this.each(function(){if(i=wa(this))i.scrollTo(!a?f:c(i).scrollLeft(),a?f:c(i).scrollTop());else this[d]=f});else return(i=wa(e))?"pageXOffset"in i?i[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&i.document.documentElement[d]||i.document.body[d]:e[d]}}); +c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+ +b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window); diff --git a/js/jquery.js.old1.3.js b/js/jquery.js.old1.3.js new file mode 100644 index 0000000..b1ae21d --- /dev/null +++ b/js/jquery.js.old1.3.js @@ -0,0 +1,19 @@ +/* + * jQuery JavaScript Library v1.3.2 + * http://jquery.com/ + * + * Copyright (c) 2009 John Resig + * Dual licensed under the MIT and GPL licenses. + * http://docs.jquery.com/License + * + * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) + * Revision: 6246 + */ +(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}}); +/* + * Sizzle CSS Selector Engine - v0.9.3 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/questionator.tmproj b/questionator.tmproj index 8bd40aa..5fc0798 100644 --- a/questionator.tmproj +++ b/questionator.tmproj @@ -1,86 +1,215 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>currentDocument</key> - <string>process.php</string> + <string>editor_node.txt</string> <key>documents</key> <array> <dict> <key>expanded</key> <true/> <key>name</key> <string>Questionator</string> <key>regexFolderFilter</key> <string>!.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$</string> <key>sourceDirectory</key> <string></string> </dict> - <dict> - <key>filename</key> - <string>process.php</string> - <key>lastUsed</key> - <date>2010-01-16T18:16:50Z</date> - <key>selected</key> - <true/> - </dict> </array> <key>fileHierarchyDrawerWidth</key> <integer>200</integer> <key>metaData</key> <dict> + <key>admin/editor.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>1</integer> + <key>line</key> + <integer>3</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>0</integer> + </dict> + <key>admin/editor_helper.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>4</integer> + <key>line</key> + <integer>63</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>16</integer> + </dict> + <key>admin/index.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>24</integer> + <key>line</key> + <integer>4</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>0</integer> + </dict> + <key>admin/results.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>1</integer> + <key>line</key> + <integer>6</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>0</integer> + </dict> + <key>css/main.css</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>16</integer> + <key>line</key> + <integer>26</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>16</integer> + </dict> <key>database_helper.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>2</integer> <key>line</key> - <integer>45</integer> + <integer>46</integer> + </dict> + <key>columnSelection</key> + <false/> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>121</integer> + <key>selectFrom</key> + <dict> + <key>column</key> + <integer>0</integer> + <key>line</key> + <integer>38</integer> + </dict> + <key>selectTo</key> + <dict> + <key>column</key> + <integer>2</integer> + <key>line</key> + <integer>46</integer> + </dict> + </dict> + <key>editor_node.txt</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>25</integer> + <key>line</key> + <integer>0</integer> + </dict> + <key>columnSelection</key> + <false/> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>0</integer> + <key>selectFrom</key> + <dict> + <key>column</key> + <integer>38</integer> + <key>line</key> + <integer>10</integer> + </dict> + <key>selectTo</key> + <dict> + <key>column</key> + <integer>25</integer> + <key>line</key> + <integer>0</integer> + </dict> + </dict> + <key>header.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>2</integer> + <key>line</key> + <integer>17</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> - <integer>15</integer> + <integer>0</integer> </dict> - <key>index.php</key> + <key>js/editor.js</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>1</integer> <key>line</key> - <integer>37</integer> + <integer>35</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> - <integer>4</integer> + <integer>2</integer> </dict> <key>process.php</key> <dict> <key>caret</key> <dict> <key>column</key> <integer>0</integer> <key>line</key> - <integer>0</integer> + <integer>10</integer> </dict> <key>firstVisibleColumn</key> <integer>0</integer> <key>firstVisibleLine</key> <integer>0</integer> </dict> </dict> <key>openDocuments</key> <array> - <string>database_helper.php</string> <string>process.php</string> - <string>index.php</string> + <string>admin/editor.php</string> + <string>admin/editor_helper.php</string> + <string>js/editor.js</string> + <string>editor_node.txt</string> + <string>database_helper.php</string> + <string>css/main.css</string> + <string>admin/index.php</string> + <string>admin/results.php</string> + <string>header.php</string> </array> <key>showFileHierarchyDrawer</key> <true/> <key>windowFrame</key> - <string>{{232, 53}, {1032, 725}}</string> + <string>{{194, 53}, {1032, 725}}</string> </dict> </plist>
ralphleon/Pollinator
003e9f3511d9425754a6670e56ca8421ca93a0d9
Started working on the editor
diff --git a/admin/editor.php b/admin/editor.php new file mode 100644 index 0000000..b8b21c1 --- /dev/null +++ b/admin/editor.php @@ -0,0 +1,44 @@ +<? include("../header.php") ?> + +<div id="container"> + + <h1>Administration</h1> + + <!--<form> + <div class="question"> + <div class="main"> + <label>Question <span class="small">The main question</span></label> + + <textarea name="content"> </textarea> + + <label>Type<span class="small">Type of the question</span></label> + <select name="type"> + <option>Free text</option> + <option>Yes / No </option> + <option>List (select one)</option> + <option>List (select any)</option> + </select> + </div> + + <div class="opts"> + <label>List<span class="small">Newline separated</span></label> + <textarea name="opts"> </textarea> + </div> + + <div class="delete"> + <a href="">Delete</a> + </div> + </div> + + </form>--> + + <? + + include("editor_helper.php"); + printQuestionsEditor(); + + + ?> + +</div> +</html></body> \ No newline at end of file diff --git a/admin/editor_helper.php b/admin/editor_helper.php new file mode 100644 index 0000000..54c54b7 --- /dev/null +++ b/admin/editor_helper.php @@ -0,0 +1,66 @@ +<? + include("../database_helper.php"); + + function printQuestionsEditor(){ + + $link = connect(); + + $q = "SELECT * FROM ". QUESTIONS_TABLE; + $result = mysql_query($q); + if (!$result) err("error with query...\n Query=$q"); + + while ( $row = mysql_fetch_array($result) ) { + printEditor($row); + } + } + + function printEditor($row){ + + $content = $row['content']; + $type = $row['type']; + $opts = $row['opts']; + + print <<< EOF + <form> + <div class="question"> + <div class="main"> + <label>Question <span class="small">The main question</span></label> + + <textarea name="content">$content</textarea> + + <label>Type<span class="small">Type of the question</span></label> + <select name="type"> +EOF; + + // This should obviously be a list, ugly code + if($type != Q_TEXT) print "<option value=\"0\">Free text</option>"; + else print "<option value=\"0\" selected=\"true\">Free text</option>"; + + if($type != Q_YES_NO) print "<option value=\"1\">Yes / No </option>"; + else print "<option value=\"1\" selected=\"true\">Yes / No </option>"; + + if($type != Q_MULTI) print "<option value=\"2\">List (select any)</option>"; + else print "<option value=\"2\" selected=\"true\">List (select any)</option>"; + + if($type != Q_MULTI_EXC) print "<option value=\"3\">List (select one)</option>"; + else print "<option value=\"3\" selected=\"true\">List (select one)</option>"; + + print <<< EOF + </select> + </div> + + <div class="opts"> + <label>List<span class="small">Newline separated</span></label> + <textarea name="opts">$opts</textarea> + </div> + + <div class="delete"> + <a href="">Delete</a> + </div> + </div> + + </form> +EOF; + } + +?> \ No newline at end of file diff --git a/admin/index.php b/admin/index.php index f06d9ac..b55757e 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,8 +1,7 @@ <? include("../header.php") ?> <div id="container"> <h1>Administration</h1> - </div> </html></body> \ No newline at end of file diff --git a/css/main.css b/css/main.css index 9be93f2..4c0947d 100644 --- a/css/main.css +++ b/css/main.css @@ -1,28 +1,84 @@ body { background:#222; font:14px Georgia; } label.header{ font:16px Georgia; display:block; margin:15px 0 4px 0; } input.submit{ float:right; } input.text{ width:200px; } form{ padding-bottom:20px; } #container{ width:500px; margin: 10px 50px 10px 50px; padding:30px; background:#CCC; } + +/* Admin section */ +div.question { + margin:10px; +} + +div.question div.main{ + background-color: #999; + padding:10px; + overflow: auto; + width: 100% +} + +div.question div.opts { + background-color: #777; + padding:10px; + clear:both; + overflow: auto; + width: 100% +} + +div.question label { + display:block; + font-weight:bold; + text-align:right; + width:140px; + float:left; +} +div.question .small { + color:#333; + display:block; + font-size:11px; + font-weight:normal; + text-align:right; + width:140px; +} +div.question input,textarea,select{ + float:left; + font-size:12px; + padding:4px 2px; + border:solid 1px #aacfe4; + width:200px; + margin:2px 0 20px 10px; +} + +div.question textarea{ + width:60%; +} +div.question div.delete { + display:inline; + float:right; + margin-right:5px; + background:#FF9999; + clear:both; + padding:5px 10px 5px 10px; +} \ No newline at end of file diff --git a/process.php b/process.php index 916a5ba..92fec4f 100644 --- a/process.php +++ b/process.php @@ -1,14 +1,13 @@ <? include("header.php") ?> <div id="container"> <h1>Thank You!</h1> - <? include("database_helper.php"); // Process the results - processResults(); + processResults(); ?> </div> </html></body> \ No newline at end of file
ralphleon/Pollinator
fc5675a3614e9a82fd4f96ce4bacfb130434ab92
Finished insertion
diff --git a/admin/index.php b/admin/index.php new file mode 100644 index 0000000..f06d9ac --- /dev/null +++ b/admin/index.php @@ -0,0 +1,8 @@ +<? include("../header.php") ?> + +<div id="container"> + + <h1>Administration</h1> + +</div> +</html></body> \ No newline at end of file diff --git a/admin/results.php b/admin/results.php new file mode 100644 index 0000000..f61667e --- /dev/null +++ b/admin/results.php @@ -0,0 +1,9 @@ +<? include("../header.php") ?> + +<div id="container"> + + <h1>Administration</h1> + + +</div> +</html></body> \ No newline at end of file diff --git a/css/main.css b/css/main.css new file mode 100644 index 0000000..9be93f2 --- /dev/null +++ b/css/main.css @@ -0,0 +1,28 @@ +body { + background:#222; + font:14px Georgia; +} + +label.header{ + font:16px Georgia; + display:block; + margin:15px 0 4px 0; +} +input.submit{ + float:right; +} + +input.text{ + width:200px; +} + +form{ + padding-bottom:20px; +} + +#container{ + width:500px; + margin: 10px 50px 10px 50px; + padding:30px; + background:#CCC; +} diff --git a/database_helper.php b/database_helper.php index e9f6708..8361701 100644 --- a/database_helper.php +++ b/database_helper.php @@ -1,100 +1,172 @@ <? // Constants define("DATABASE", "questionator"); define("QUESTIONS_TABLE" , "questions" ); +define("RESULTS_TABLE" , "results"); // Differnt values for the question types define('Q_YES_NO',0); define('Q_MULTI',1); define('Q_TEXT',2); define('Q_MULTI_EXC',3); function connect(){ $link = mysql_connect('localhost', 'root', 'root'); if(!$link) err("failure connecting to database..."); if(!@mysql_select_db(DATABASE,$link)){ err("failure selecting the database <strong>" . DATABASE . "</strong>..."); } return $link; } function err($string){ print "Error: " . $string . "<br/>"; print "MySQL says: \"" . mysql_error() . "\""; exit(); } /** Prints all questions stored in the Mysql database */ function printQuestions(){ $link = connect(); $q = "SELECT * FROM ". QUESTIONS_TABLE; $result = mysql_query($q); if (!$result) err("error with query...\n Query=$q"); while ( $row = mysql_fetch_array($result) ) { printQuestion($row); } } /** Takes an array that has "type","content", and "opts" defined and prints an html form element based on these values. This array is normally a row from the QUESTIONS_TABLE mysql table. **/ function printQuestion($row){ // All the questions have the same sort of title - print "<div> <label>" . $row["content"] . "</label>"; + print '<div> <label class="header">' . $row["content"] . "</label>"; $id = $row["id"]; $name = "question". $id; // But they differ in how the user responds to them switch($row["type"]) { case Q_YES_NO: - print '<br/><input type="radio" name="' . $name . '"><label>Yes</label>'; - print '<br/><input type="radio" name="' . $name . '"><label>No</label>'; + print '<input value="yes" type="radio" name="' . $name . '"><label>Yes</label><br/>'; + print '<input value="no" type="radio" name="' . $name . '"><label>No</label><br/>'; break; case Q_MULTI: $opts = explode( "," , $row['opts']); foreach($opts as $opt){ - print '<br/><input type="checkbox" name="' . $name .'"/>'; - print "<label>$opt</label>"; + print '<input type="checkbox" name="' . $name . $opt .'"/>'; + print "<label>$opt</label><br/>"; } break; case Q_MULTI_EXC: $opts = explode( "," , $row['opts']); foreach($opts as $opt){ - print '<br/><input type="radio" name="' . $name .'"/>'; - print "<label>$opt</label>"; + print '<input value="' . $opt .'" type="radio" name="' . $name .'"/>'; + print "<label>$opt</label><br/>"; } break; case Q_TEXT: - print '<br><input type="text" name="' . $name . '"/>'; + print '<input type="text" name="' . $name . '"/>'; break; } print "</div>\n"; } +/** Process Questions +*/ +function processResults() +{ + // We can grab the name and email first, because they're not dynamic questions + $name = $_POST['name']; + $email = $_POST['email']; + + print "<p>Thanks for your interest in Widget Corporation, $name. We'll be in touch shortly!</p>"; + + $link = connect(); + + // Loop through the dynamic fields + $q = "SELECT * FROM ". QUESTIONS_TABLE; + $result = mysql_query($q); + if (!$result) err("error with query...\n Query=$q"); + + // store the column names, and their answers + $qResults = Array(); + + while( $row = mysql_fetch_array($result) ) { + $id = $row['id']; + $name = "question" . $id; + $content = $row["content"]; + $r = ""; + + switch($row["type"]){ + + // multiple check boxes are a pain in the ass. + case Q_MULTI: + + $opts = explode(",", $row['opts']); + + foreach($opts as $opt){ + + //If the value is set, then it was checked + if(isset($_POST[ $name . $opt])){ + $r = $r . $opt . ","; + } + } + break; + + // everything else can use a standard case + default: + + // try to gather the result for the question + $r = $_POST[$name]; + break; + } + + print "<p><strong>$content</strong><br/>$r</p>"; + + $qResults[$name] = $r; + + } // end while + + // Insert a new record with the name and email filled in + $cols = "name,email"; + $values = "'$name','$email'"; + + foreach($qResults as $key => $val) { + $cols = $cols . "," . $key; + $values = $values . ",'" . $val . "'"; + } + + $q = "INSERT into " . RESULTS_TABLE . " ($cols) VALUES($values)"; + $result = mysql_query($q); + if (!$result) err("error with query...\n Query=$q"); + +} + ?> diff --git a/header.php b/header.php new file mode 100644 index 0000000..3baab7d --- /dev/null +++ b/header.php @@ -0,0 +1,18 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> +<head profile="http://gmpg.org/xfn/11"> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> + <title>Widget Corporation(tm) Interview</title> + + <!-- Favicon --> + <link rel="icon" type="image/png" href="/images/favicon.png" /> + + <!-- stylesheets --> + <link rel="stylesheet" href="/questionator/css/main.css" type="text/css" media="screen" /> +</head> +<body><html> + +<? + error_reporting(E_ALL); + ini_set('display_errors', '1'); +?> \ No newline at end of file diff --git a/index.php b/index.php index aa02989..577f818 100644 --- a/index.php +++ b/index.php @@ -1,42 +1,30 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"> -<head profile="http://gmpg.org/xfn/11"> - <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> - <title>Solid Sushi</title> - - <!-- Favicon --> - <link rel="icon" type="image/png" href="/images/favicon.png" /> - - <!-- stylesheets --> - <link rel="stylesheet" href="/css/main.css" type="text/css" media="screen" /> -</head> -<body> +<? include("header.php") ?> - <div id="container"> +<div id="container"> - <h1>Widget Corporation Interview Questions</h1> + <h1>Widget Corporation(tm) Interview Questions</h1> <p>Thank you for your interest in <strong>Widget Corporation</strong> please answer the following questions as honestly as possibly</p> - <form> + <form method="post" action="process.php"> + + <!-- Some questions are hard-wired --> + <label class="header">Name</label> + <input class="text" name="name" type="text"/> + + <label class="header">Email</label> + <input class="text" name="email" type="text"/> <? - include("database_helper.php"); - - //connect to our database - //parse through the questions - - - printQuestions(); - + include("database_helper.php"); + printQuestions(); ?> - - <input type="submit" value="Submit" /> + <input type="submit" class="submit" value="Submit" /> </form> - </div> +</div> -</body> \ No newline at end of file +</html></body> \ No newline at end of file diff --git a/process.php b/process.php new file mode 100644 index 0000000..916a5ba --- /dev/null +++ b/process.php @@ -0,0 +1,14 @@ +<? include("header.php") ?> + +<div id="container"> + + <h1>Thank You!</h1> + +<? + include("database_helper.php"); + // Process the results + processResults(); +?> + +</div> +</html></body> \ No newline at end of file diff --git a/question_parser.php b/question_parser.php new file mode 100644 index 0000000..e69de29 diff --git a/questionator.tmproj b/questionator.tmproj new file mode 100644 index 0000000..8bd40aa --- /dev/null +++ b/questionator.tmproj @@ -0,0 +1,86 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>currentDocument</key> + <string>process.php</string> + <key>documents</key> + <array> + <dict> + <key>expanded</key> + <true/> + <key>name</key> + <string>Questionator</string> + <key>regexFolderFilter</key> + <string>!.*/(\.[^/]*|CVS|_darcs|_MTN|\{arch\}|blib|.*~\.nib|.*\.(framework|app|pbproj|pbxproj|xcode(proj)?|bundle))$</string> + <key>sourceDirectory</key> + <string></string> + </dict> + <dict> + <key>filename</key> + <string>process.php</string> + <key>lastUsed</key> + <date>2010-01-16T18:16:50Z</date> + <key>selected</key> + <true/> + </dict> + </array> + <key>fileHierarchyDrawerWidth</key> + <integer>200</integer> + <key>metaData</key> + <dict> + <key>database_helper.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>2</integer> + <key>line</key> + <integer>45</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>15</integer> + </dict> + <key>index.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>1</integer> + <key>line</key> + <integer>37</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>4</integer> + </dict> + <key>process.php</key> + <dict> + <key>caret</key> + <dict> + <key>column</key> + <integer>0</integer> + <key>line</key> + <integer>0</integer> + </dict> + <key>firstVisibleColumn</key> + <integer>0</integer> + <key>firstVisibleLine</key> + <integer>0</integer> + </dict> + </dict> + <key>openDocuments</key> + <array> + <string>database_helper.php</string> + <string>process.php</string> + <string>index.php</string> + </array> + <key>showFileHierarchyDrawer</key> + <true/> + <key>windowFrame</key> + <string>{{232, 53}, {1032, 725}}</string> +</dict> +</plist>
goodxiexin/dayday3
04bb6df64346400bbf43d70fbaed7747e7e5bfa3
game suggestion
diff --git a/app/controllers/user/friend_guesses_controller.rb b/app/controllers/user/friend_guesses_controller.rb new file mode 100644 index 0000000..eccc49a --- /dev/null +++ b/app/controllers/user/friend_guesses_controller.rb @@ -0,0 +1,48 @@ +class User::FriendGuessesController < ApplicationController + layout 'friend' + + before_filter :login_required + + def index + @user = current_user + # currently friend guesses are created everytimes when user view friend guesses page + # In future, this need to be modified to release server load + @user.create_friend_guesses + @friend_suggestions = current_user.guessed_friends.sort_by{rand}[0..8] + @common_game_characters = {} + # this prevent multiple game characters in one game server + current_user.currently_playing_game_characters.each do |game_character| + @current_game_characters = {} + @current_game_characters.default = ' ' + game_character.server.game_characters.each do |other_character| + @current_game_characters[other_character.user.id] += (other_character.name + ' ') + end + @common_game_characters[game_character.server.id] = @current_game_characters + end + end + + def show_all + @server = GameServer.find(params[:server_id]) + @current_game_characters={} + @current_game_characters.default = ' ' + @server.game_characters.each do |other_character| + @current_game_characters[other_character.user.id] += (other_character.name + ' ') + end + # currently the users are shown with login order (user.id),but login name ASC order is perfered + @temp_array = @current_game_characters.sort + @user_array = @temp_array.paginate :page => params[:page], :per_page => 10 + end + + def show_all_server_characters + @user = current_user + @common_game_characters={} + current_user.game_characters.each do |game_character| + @current_game_characters = {} + @current_game_characters.default = ' ' + game_character.server.game_characters.each do |other_character| + @current_game_characters[other_character.user.id] += (other_character.name + ' ') + end + @common_game_characters[game_character.server.id] = @current_game_characters + end + end +end diff --git a/app/controllers/user/friend_guesses_controller.rb~ b/app/controllers/user/friend_guesses_controller.rb~ new file mode 100644 index 0000000..e8eca86 --- /dev/null +++ b/app/controllers/user/friend_guesses_controller.rb~ @@ -0,0 +1,109 @@ +class User::FriendGuessesController < ApplicationController + layout 'friend' + + before_filter :login_required + + def index + @user = current_user + if (@user.friend_guesses.empty? or (@user.friend_guesses.size < 50)) + self.create + end + @friend_suggestions = current_user.guessed_friends.sort_by{rand}[0..8] + @common_game_characters = {} + # this prevent multiple game characters in one game server + current_user.currently_playing_game_characters.each do |game_character| + @current_game_characters = {} + @current_game_characters.default = ' ' + game_character.server.game_characters.each do |other_character| + @current_game_characters[other_character.user.id] += (other_character.name + ' ') + end + @common_game_characters[game_character.server.id] = @current_game_characters + end + end + + def create + unless @user.friend_guesses.empty? + self.remove_all + end + @guessed_users = {} + @guessed_users.default = 0 + @stage = 0 + # go through all events find people that attending the same event as the current user + # those users are most like to be friend with current user + current_user.events.each do |event| + event.must_attenders.each do |user| + # if they are already friend or engine already searched 200 people and has not yet include that user, we ignore that user + unless (current_user.id == user.id or current_user.has_friend(user) or current_user.has_friend_request(user) or (guessed_users.size >= 200 and guessed_users[user.id] == 0 )) + @guessed_users[user.id] += 5 + end + end + end + + if (@guessed_users.size >= 200) + @stage = 1 + end + + unless (@stage == 1) + catch(:done) do + current_user.friends.each do |friend| + @n = friend.friends.size + @n.times do |i| + @user = friend.friends[rand(@n)] + unless (current_user.id == @user.id or current_user.has_friend(@user) or current_user.has_friend_request(@user) ) + @guessed_users[@user.id] += 1 + throw :done if (@guessed_users.size >= 200) + end + end + end + end + end + + if (@guessed_users.size >= 200) + @done = true + else + @done = false + end + + unless (@done) + @final_suggestions = @guessed_users.sort{|a,b| a[1] <=> b[1]}[0..50] + @final_suggestions.each do |element| + current_user.friend_guesses.create(:guess_id => element[0]) + end + #redirect_to :back + end + + return + end + + def remove_all + current_user.friend_guesses.each do |guess| + guess.destroy + end + return + end + + def show_all + @server = GameServer.find(params[:server_id]) + @current_game_characters={} + @current_game_characters.default = ' ' + @server.game_characters.each do |other_character| + @current_game_characters[other_character.user.id] += (other_character.name + ' ') + end + # currently the users are shown with login order (user.id),but login name ASC order is perfered + @temp_array = @current_game_characters.sort + @user_array = @temp_array.paginate :page => params[:page], :per_page => 10 + end + + def show_all_server_characters + @user = current_user + @common_game_characters={} + current_user.game_characters.each do |game_character| + @current_game_characters = {} + @current_game_characters.default = ' ' + game_character.server.game_characters.each do |other_character| + @current_game_characters[other_character.user.id] += (other_character.name + ' ') + end + @common_game_characters[game_character.server.id] = @current_game_characters + end + end +end diff --git a/app/controllers/user/mailboxes_controller.rb b/app/controllers/user/mailboxes_controller.rb index b8a12a7..7daaf53 100755 --- a/app/controllers/user/mailboxes_controller.rb +++ b/app/controllers/user/mailboxes_controller.rb @@ -1,169 +1,179 @@ class User::MailboxesController < ApplicationController layout 'user' before_filter :login_required before_filter :owner_required, :except => [:auto_complete_for_mail_recipients] def index @user = resource_owner if params[:type] == 'recv' @mails = Mail.paginate :page => params[:page], :per_page => 10, :conditions => {:receiver_id => @user.id, :delete_by_receiver => false}, :order => 'created_at DESC' render :action => 'recv_index' elsif params[:type] == 'sent' @mails = Mail.paginate :page => params[:page], :per_page => 10, :conditions => {:sender_id => @user.id, :delete_by_sender => false}, :order => 'created_at DESC' render :action => 'sent_index' end end def show @user = resource_owner @mail = Mail.find(params[:id]) @root_mail = @mail.parent Mail.transaction do @root_mail.children.each { |m| m.mark_as_read(@user.id) } end rescue ActiveRecord::RecordNotFound render :text => 'mail not found' rescue flash[:error] = "There was an error" redirect_to user_mails_url(@user, :type => 'recv') end def new @user = resource_owner unless params[:receiver_id].blank? @receiver = User.find(params[:receiver_id]) end rescue ActiveRecord::RecordNotFound render :text => 'recipient not found' end def create @user = resource_owner Mail.transaction do - params[:mail][:recipients].split(%r{,\s*}).each do |recipient_name| - recipient = @user.friends.find_by_login(recipient_name) + params[:recipients].each do |recipient_id| + recipient = User.find(recipient_id) if recipient mail = Mail.new(params[:mail]) mail.receiver = recipient mail.sender = @user mail.save mail.parent = mail mail.save end end end - redirect_to :action => 'index', :type => 'sent' + render :update do |page| + page.redirect_to :action => 'index', :type => 'sent' + end end def reply @user = resource_owner @root_mail = Mail.find(params[:id]).parent @mail = Mail.new(params[:mail]) @mail.title = "reply to: #{@root_mail.title}" @mail.sender_id = @user.id @mail.receiver_id = (@root_mail.sender == current_user)? @root_mail.receiver.id : @root_mail.sender.id @mail.parent_id = @root_mail.id respond_to do |format| if @mail.save format.html { render :partial => 'mail', :object => @mail } format.xml { render :xml => @mail } else format.html { render :action => 'new' } format.xml { render :xml => @mail.errors, :status => :unprocessable_entity } end end rescue ActiveRecord::RecordNotFound render :text => 'mail not found' end def destroy @user = resource_owner if params[:type] == 'recv' @mail = @user.recv_mails.find(params[:id]) @mail.mark_delete(@user.id) respond_to do |format| format.html { redirect_to :action => 'index', :type => 'recv' } format.xml { header :ok } end elsif params[:type] == 'sent' @mail = @user.sent_mails.find(params[:id]) @mail.mark_delete(@user.id) respond_to do |format| format.html { redirect_to :action => 'index', :type => 'sent' } format.xml { header :ok } end end rescue ActiveRecord::RecordNotFound render :text => 'mail not found' end def read_multiple @user = resource_owner Mail.transaction do params[:mail_ids].each do |mail_id| mail = Mail.find(mail_id) mail.mark_as_read(@user.id) end end respond_to do |format| format.html { render :text => "totally #{@user.recv_mails.count} mails | #{@user.unread_recv_mails_count} unread"} format.xml { header :ok} end rescue ActiveRecord::RecordNotFound render :text => 'mail not found' rescue flash[:error] = "There was an error marking read" redirect_to user_mails_url(@user, :type => 'recv') end def unread_multiple @user = resource_owner Mail.transaction do params[:mail_ids].each do |mail_id| mail = Mail.find(mail_id) mail.mark_as_unread(@user.id) end end respond_to do |format| format.html { render :text => "totally #{@user.recv_mails.count} mails | #{@user.unread_recv_mails_count} unread" } format.xml { header :ok } end rescue ActiveRecord::RecordNotFound render :text => 'mail not found' rescue flash[:error] = "There was an error marking unread" redirect_to user_mails_url(@user, :type => 'recv') end def destroy_multiple @user = resource_owner Mail.transaction do params[:mail_ids].each do |mail_id| mail = Mail.find(mail_id) mail.mark_delete(@user.id) end end respond_to do |format| format.html { render :text => url_for(:action => 'index', :type => params[:type]) } format.xml { header :ok } end rescue ActiveRecord::RecordNotFound render :text => 'mail not found' rescue flash[:error] = "There was an error deleting" redirect_to user_mails_url(@user, :type => 'recv') end + def new_recipient + recipients = [] + params[:recipients].each do |recipient_id| + recipients << User.find(recipient_id) + end + render :partial => "recipient", :collection => recipients, :locals => {:condition => params[:condition]} + end + def auto_complete_for_mail_recipients @user = current_user @friends = @user.friends.find_all {|f| f.login.include?(params[:mail][:recipients]) } - render :inline => "<%= auto_complete_result @friends, 'login' %>" + render :partial => 'friends' end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 62230bf..a0f83e5 100755 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,32 +1,32 @@ # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def ftime(time) time.strftime("%Y-%m-%d %H:%M") unless time.blank? end def ftime2(time) time.strftime("%Y-%m-%d") unless time.blank? end def ftime3(time) time.strftime("%m-%d") unless time.blank? end def ftime4(time) time.strftime("%H: %M") unless time.blank? end def validation_image - "<img src='/application/new_validation_image' />" + "<img name='validationImage' src='/application/new_validation_image?time=1' onclick=\"renew_validation_image()\"/>" end def privilege_select_tag(resource, privilege) select_tag "#{resource}[privilege]", options_for_select([['all', 'all'], ['friends', 'friends'], ['myself', 'myself']], privilege) end def link_to_game(game) link_to game.name end end diff --git a/app/helpers/user/friend_guesses_helper.rb b/app/helpers/user/friend_guesses_helper.rb new file mode 100644 index 0000000..2c2cfef --- /dev/null +++ b/app/helpers/user/friend_guesses_helper.rb @@ -0,0 +1,2 @@ +module User::FriendGuessesHelper +end diff --git a/app/models/friend_guess.rb b/app/models/friend_guess.rb new file mode 100644 index 0000000..d5e32ac --- /dev/null +++ b/app/models/friend_guess.rb @@ -0,0 +1,8 @@ +class FriendGuess < ActiveRecord::Base + belongs_to :user + + belongs_to :guessed_friend, + :class_name => 'User', + :foreign_key => 'guess_id' + +end diff --git a/app/models/game_server.rb b/app/models/game_server.rb index 51ba143..4033429 100755 --- a/app/models/game_server.rb +++ b/app/models/game_server.rb @@ -1,6 +1,9 @@ class GameServer < ActiveRecord::Base belongs_to :game belongs_to :area + has_many :game_characters, + :foreign_key => 'server_id' + end diff --git a/app/models/user.rb b/app/models/user.rb index f4b3c18..26d7fb3 100755 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,257 +1,416 @@ require 'digest/sha1' class User < ActiveRecord::Base has_many :friend_requests, :foreign_key => 'receiver_id', - :order => 'created_at DESC' + :order => 'created_at DESC', + :dependent => :destroy + + # users that has sent requests to this user + has_many :requested_friends, + :class_name => 'User', + :through => :friend_requests, + :source => :sender + + has_many :friend_wanted, + :class_name => 'friend_requests', + :foreign_key => 'sender_id', + :dependent => :destroy + + # users that this user want to be a friend with + has_many :wanted_friends, + :class_name => 'User', + :through => :friend_requests, + :source => :receiver + + def has_friend_request(user) + self.requested_friends.include?(user) or user.wanted_friends.include?(self) + end has_many :friend_notifications has_one :privacy_setting has_one :mail_setting has_many :visitor_records, :order => 'created_at DESC' belongs_to :city belongs_to :province belongs_to :country has_many :wall_messages, :dependent => :destroy, :finder_sql => 'select wall_messages.* from wall_messages where wall_messages.user_id = #{id} OR wall_messages.receiver_id = #{id} ORDER BY created_at DESC' has_many :sent_mails, :class_name => 'Mail', :foreign_key => 'sender_id', :conditions => { :delete_by_sender => false } has_many :recv_mails, :class_name => 'Mail', :foreign_key => 'receiver_id', :conditions => { :delete_by_receiver => false } def unread_recv_mails_count recv_mails.find_all { |m| !m.read_by_receiver? }.count end + has_many :friend_guesses, + :dependent => :destroy + + def has_enough_friend_guesses + self.friend_guesses.count > 40 + end + + has_many :guessed_friends, + :class_name => 'User', + :foreign_key => 'guess_id', + :through => :friend_guesses, + :uniq => true + + + def destroy_existing_guesses + unless self.friend_guesses.empty? + self.friend_guesses.each do |guess| + guess.destroy + end + end + end + + def collect_friend_guesses(guessed_users) + # go through all events find people that attending the same event as the current user + # those users are most like to be friend with current user + # event is not selected randomly because each new event is very likely bring people together + self.events.each do |event| + catch(:done) do + event.must_attenders.each do |user| + unless (self.id == user.id or self.has_friend(user) or self.has_friend_request(user)) + guessed_users[user.id] += 1 + throw :done if (guessed_users.size >= 200) + end + end + end + end + + # if events collect enough users then friends' friends are not collected. + # otherwise, friends' friends are collected for consideration + # friends' friends are selected randomly to avoid same users are used every time + unless (guessed_users.size >= 200) + catch(:done1) do + self.friends.each do |friend| + @n = friend.friends.size + @n.times do |i| + @user_guess = friend.friends[rand(@n)] + unless (self.id == @user_guess.id or self.has_friend(@user_guess) or self.has_friend_request(@user_guess) ) + guessed_users[@user_guess.id] += 2 + throw :done1 if (guessed_users.size >= 200) + end + end + end + end + end + + # if previous step has not get enough users, all users in same servers are considered + unless (guessed_users.size >= 200) + catch(:done2) do + self.game_characters.each do |each_character| + @current_characters = each_character.server.game_characters.sort_by{rand} + @current_characters.each do |other_character| + unless (self.id == other_character.user.id or self.has_friend(other_character.user) or self.has_friend_request(other_character.user) ) + gussed_users[other_character.user.id] += 1 + throw :done2 if (guessed_users.size >= 200) + end + end + end + end + end + + # At this stage, every user is needed for this engine + # this only occur when user does not provide enough info or we have not get enough users + unless (guessed_users.size >= 200) + catch(:done3) do + User.all.each do |each_user| + guessed_users[each_user.id] += 1 + throw :done3 if (guessed_users.size >= 200) + end + end + end + end + + def calculating_final_scores(guessed_users, suggested_users) + guessed_users.each_key do |user_id| + this_user = User.find(user_id) + this_user.friends do |each_friend| + if (self.has_friend(each_friend)) + suggested_users[user_id] += 2 + end + end + this_user.events do |each_event| + if (self.has_attended_event(each_event)) + suggested_users[user_id] += 5 + end + end + this_user.game_characters do |each_game_character| + self.game_characters do |this_game_character| + if (this_game_character.server.id == each_game_character.server.id) + suggested_users[user_id] +=2 + end + end + end + end + end + + # this method has three main part + # first part is to destroy all existing samples + # second part is to collect 200 samples + # third part is to calculate sample quality + def create_friend_guesses + self.destroy_existing_guesses + + @guessed_users = {} + @guessed_users.default = 0 + self.collect_friend_guesses(@guessed_users) + + @suggested_users = @guessed_users + @suggested_users.each_key do |user_id| + @suggested_users[user_id] = 1 + end + self.calculating_final_scores(@guessed_users, @suggested_users) + + @min_num = [50, @suggested_users.size].min + @final_suggestions = @suggested_users.sort{|a,b| a[1] <=> b[1]}[0..@min_num] + + @final_suggestions.each do |element| + self.friend_guesses.create(:guess_id => element[0]) + end + end + has_many :friendships, :dependent => :destroy has_many :friends, :class_name => 'User', :order => 'login ASC', :through => :friendships def has_friend(user) self.friends.include?(user) end has_many :game_characters, :dependent => :destroy has_many :currently_playing_game_characters, :class_name => 'GameCharacter', :conditions => { :playing => true }, :order => 'created_at DESC' has_many :games, :through => :game_characters, :uniq => true has_many :participations, :foreign_key => 'participant_id', :dependent => :destroy has_many :events, :through => :participations, :uniq => true + def has_attended_event(event) + self.events.include?(event) + end + has_many :icons, :class_name => 'Photo', :order => 'created_at DESC', :dependent => :destroy has_one :current_icon, :class_name => 'Photo', :order => 'created_at DESC', :conditions => {:current_icon => true} def next_prev_icon(cur_icon) size = self.icons.count next_icon_idx = 0 prev_icon_idx = 0 cur_icon_idx = 0 self.icons.each_with_index do |icon, i| if cur_icon == icon next_icon_idx = (i + 1) % size prev_icon_idx = (i - 1 + size) % size cur_icon_idx = i + 1 break end end [self.icons[next_icon_idx], self.icons[prev_icon_idx], cur_icon_idx] end def reset_icon(new_icon) old_icon = self.current_icon unless new_icon == old_icon old_icon.update_attribute(:current_icon, false) unless old_icon.blank? new_icon.current_icon = true new_icon.user_id = self.id end end has_many :statuses, :order => 'created_at DESC', :dependent => :destroy has_one :latest_status, :class_name => 'Status', :order => 'created_at DESC' has_many :blogs, :order => 'position DESC', :conditions => {:draft => false} has_many :drafts, :class_name => 'Blog', :order => 'updated_at DESC', :conditions => {:draft => true} has_many :albums, :order => 'updated_at DESC' has_many :videos, :order => 'position DESC' has_many :tag_notifications, :order => 'created_at DESC' has_many :comment_notifications, :order => 'created_at DESC' has_many :pokes, :foreign_key => 'receiver_id', :order => 'created_at DESC' # permissions and roles has_many :permissions has_many :roles, :through => :permissions # Virtual attribute for the unencrypted password attr_accessor :password, :password_confirmation # callbacks before_save :encrypt_password before_create :make_activation_code + # friend guesses are built after a user is created + after_create :create_friend_guesses + # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :gender, :password, :password_confirmation, :qq, :website, :mobile, :country, :city, :province, :birthday # Activates the user in the database. def activate @activated = true self.activated_at = Time.now.utc self.activation_code = nil save(false) end def active? # the existence of an activation code means they have not activated yet activation_code.nil? end # Authenticates a user by their login name and unencrypted password. Returns the user or nil. def self.authenticate(email, password) u = find :first, :conditions => ['email = ? and activated_at IS NOT NULL', email] u && u.authenticated?(password) ? u : nil end # Encrypts some data with the salt. def self.encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end # Encrypts the password with the user salt def encrypt(password) self.class.encrypt(password, salt) end def authenticated?(password) crypted_password == encrypt(password) end def remember_token? remember_token_expires_at && Time.now.utc < remember_token_expires_at end # These create and unset the fields required for remembering users between browser closes def remember_me remember_me_for 2.weeks end def remember_me_for(time) remember_me_until time.from_now.utc end def remember_me_until(time) self.remember_token_expires_at = time self.remember_token = encrypt("#{email}--#{remember_token_expires_at}") save(false) end def forget_me self.remember_token_expires_at = nil self.remember_token = nil save(false) end def forgot_password @forgotten_password = true self.make_password_reset_code end def reset_password update_attribute(:password_reset_code, nil) @reset_password = true end def has_role?(name) self.roles.find_by_name(name) ? true : false end # Returns true if the user has just been activated. def recently_activated? @activated end def recently_forgot_password? @forgotten_password end def recently_reset_password? @reset_password end protected def encrypt_password return if password.blank? self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record? self.crypted_password = encrypt(password) end def make_activation_code self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end def make_password_reset_code self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end end diff --git a/app/models/user.rb~ b/app/models/user.rb~ new file mode 100644 index 0000000..07003f4 --- /dev/null +++ b/app/models/user.rb~ @@ -0,0 +1,292 @@ +require 'digest/sha1' + +class User < ActiveRecord::Base + + has_many :friend_requests, + :foreign_key => 'receiver_id', + :order => 'created_at DESC', + :dependent => :destroy + + # users that has sent requests to this user + has_many :requested_friends, + :class_name => 'User', + :through => :friend_requests, + :source => :sender + + has_many :friend_wanted, + :class_name => 'friend_requests', + :foreign_key => 'sender_id', + :dependent => :destroy + + # users that this user want to be a friend with + has_many :wanted_friends, + :class_name => 'User', + :through => :friend_requests, + :source => :receiver + + def has_friend_request(user) + self.requested_friends.include?(user) or user.wanted_friends.include?(self) + end + + has_many :friend_notifications + + has_one :privacy_setting + + has_one :mail_setting + + has_many :visitor_records, + :order => 'created_at DESC' + + belongs_to :city + + belongs_to :province + + belongs_to :country + + has_many :wall_messages, + :dependent => :destroy, + :finder_sql => 'select wall_messages.* from wall_messages where wall_messages.user_id = #{id} OR wall_messages.receiver_id = #{id} ORDER BY created_at DESC' + + has_many :sent_mails, + :class_name => 'Mail', + :foreign_key => 'sender_id', + :conditions => { :delete_by_sender => false } + + has_many :recv_mails, + :class_name => 'Mail', + :foreign_key => 'receiver_id', + :conditions => { :delete_by_receiver => false } + + def unread_recv_mails_count + recv_mails.find_all { |m| !m.read_by_receiver? }.count + end + + has_many :friend_guesses, + :dependent => :destroy + + def has_enough_friend_guesses + self.friend_guesses.count > 40 + end + + has_many :guessed_friends, + :class_name => 'User', + :foreign_key => 'guess_id', + :through => :friend_guesses, + :uniq => true + + has_many :friendships, + :dependent => :destroy + + has_many :friends, + :class_name => 'User', + :order => 'login ASC', + :through => :friendships + + def has_friend(user) + self.friends.include?(user) + end + + has_many :game_characters, + :dependent => :destroy + + has_many :currently_playing_game_characters, + :class_name => 'GameCharacter', + :conditions => { :playing => true }, + :order => 'created_at DESC' + + has_many :games, + :through => :game_characters, + :uniq => true + + has_many :participations, + :foreign_key => 'participant_id', + :dependent => :destroy + + has_many :events, + :through => :participations, + :uniq => true + + has_many :icons, + :class_name => 'Photo', + :order => 'created_at DESC', + :dependent => :destroy + + has_one :current_icon, + :class_name => 'Photo', + :order => 'created_at DESC', + :conditions => {:current_icon => true} + + def next_prev_icon(cur_icon) + size = self.icons.count + next_icon_idx = 0 + prev_icon_idx = 0 + cur_icon_idx = 0 + self.icons.each_with_index do |icon, i| + if cur_icon == icon + next_icon_idx = (i + 1) % size + prev_icon_idx = (i - 1 + size) % size + cur_icon_idx = i + 1 + break + end + end + [self.icons[next_icon_idx], self.icons[prev_icon_idx], cur_icon_idx] + end + + def reset_icon(new_icon) + old_icon = self.current_icon + unless new_icon == old_icon + old_icon.update_attribute(:current_icon, false) unless old_icon.blank? + new_icon.current_icon = true + new_icon.user_id = self.id + end + end + + has_many :statuses, + :order => 'created_at DESC', + :dependent => :destroy + + has_one :latest_status, + :class_name => 'Status', + :order => 'created_at DESC' + + has_many :blogs, + :order => 'position DESC', + :conditions => {:draft => false} + + has_many :drafts, + :class_name => 'Blog', + :order => 'updated_at DESC', + :conditions => {:draft => true} + + has_many :albums, + :order => 'updated_at DESC' + + has_many :videos, + :order => 'position DESC' + + has_many :tag_notifications, + :order => 'created_at DESC' + + has_many :comment_notifications, + :order => 'created_at DESC' + + has_many :pokes, + :foreign_key => 'receiver_id', + :order => 'created_at DESC' + + # permissions and roles + has_many :permissions + has_many :roles, :through => :permissions + + # Virtual attribute for the unencrypted password + attr_accessor :password, :password_confirmation + + # callbacks + before_save :encrypt_password + before_create :make_activation_code + + # prevents a user from submitting a crafted form that bypasses activation + # anything else you want your user to change should be added here. + attr_accessible :login, :email, :gender, :password, :password_confirmation, :qq, :website, :mobile, :country, :city, :province, :birthday + + # Activates the user in the database. + def activate + @activated = true + self.activated_at = Time.now.utc + self.activation_code = nil + save(false) + end + + def active? + # the existence of an activation code means they have not activated yet + activation_code.nil? + end + + # Authenticates a user by their login name and unencrypted password. Returns the user or nil. + def self.authenticate(email, password) + u = find :first, :conditions => ['email = ? and activated_at IS NOT NULL', email] + u && u.authenticated?(password) ? u : nil + end + + # Encrypts some data with the salt. + def self.encrypt(password, salt) + Digest::SHA1.hexdigest("--#{salt}--#{password}--") + end + + # Encrypts the password with the user salt + def encrypt(password) + self.class.encrypt(password, salt) + end + + def authenticated?(password) + crypted_password == encrypt(password) + end + + def remember_token? + remember_token_expires_at && Time.now.utc < remember_token_expires_at + end + + # These create and unset the fields required for remembering users between browser closes + def remember_me + remember_me_for 2.weeks + end + + def remember_me_for(time) + remember_me_until time.from_now.utc + end + + def remember_me_until(time) + self.remember_token_expires_at = time + self.remember_token = encrypt("#{email}--#{remember_token_expires_at}") + save(false) + end + + def forget_me + self.remember_token_expires_at = nil + self.remember_token = nil + save(false) + end + + def forgot_password + @forgotten_password = true + self.make_password_reset_code + end + + def reset_password + update_attribute(:password_reset_code, nil) + @reset_password = true + end + + def has_role?(name) + self.roles.find_by_name(name) ? true : false + end + + # Returns true if the user has just been activated. + def recently_activated? + @activated + end + + def recently_forgot_password? + @forgotten_password + end + + def recently_reset_password? + @reset_password + end + +protected + def encrypt_password + return if password.blank? + self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record? + self.crypted_password = encrypt(password) + end + + def make_activation_code + self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) + end + + def make_password_reset_code + self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) + end + +end diff --git a/app/views/layouts/friend.html.erb b/app/views/layouts/friend.html.erb new file mode 100755 index 0000000..c434777 --- /dev/null +++ b/app/views/layouts/friend.html.erb @@ -0,0 +1,44 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html> +<head> + <%= stylesheet_link_tag "user" %> + <%= stylesheet_link_tag 'facebox' %> + <%= javascript_include_tag :defaults %> + <%= javascript_include_tag 'facebox' %> + <%= javascript_include_tag 'nicEdit' %> + <%= javascript_include_tag 'resource_feeds' %> + <%= javascript_include_tag 'video' %> + <%= javascript_include_tag 'validator' %> + <%= javascript_include_tag 'comment_notification' %> + <%= javascript_include_tag 'tag_notification' %> + <%= javascript_include_tag 'setting' %> +</head> +<body> + <div id="container"> +  <div id="header"> + <%= render :partial => 'layouts/user_menus' %> +  </div> + <div id='containter'> +   <div id="left"> + <%= render :partial => '/user/friends/friend_menu' %> + </div> +  <div id="middle"> + <% if flash[:notice] %> + <div class='yellow-info'><%= flash[:notice] %></div> + <% end -%> + <% if flash[:error] %> + <div class='red-error'><%= flash[:error] %></div> + <% end -%> + <%= yield %> +   </div> + <div id="right"> + <%= yield :right %> +   </div> + </div> +  <div id="footer"> + <!-- Dayday3 Group: xiahong gao, xin xie --> +  </div> +</div> +</body> + diff --git a/app/views/participations/_friends.html.erb b/app/views/participations/_friends.html.erb index d9fe628..a302bd0 100755 --- a/app/views/participations/_friends.html.erb +++ b/app/views/participations/_friends.html.erb @@ -1,5 +1,5 @@ <ul> <% friends.each do |friend| %> - <li style="list-style-type:none;" user_id=<%= friend.id %>><%= friend.login %> </li> + <li style="list-style-type:none;" user_id=<%= friend.id %> user_login=<%= friend.login%>> <%= friend.login %> </li> <% end %> </ul> diff --git a/app/views/user/friend_guesses/_guessed_user.html.erb b/app/views/user/friend_guesses/_guessed_user.html.erb new file mode 100644 index 0000000..15f4ab2 --- /dev/null +++ b/app/views/user/friend_guesses/_guessed_user.html.erb @@ -0,0 +1,5 @@ +<div class='friend_suggestion' id='friend_suggestion_<%= guessed_user.id%>' > +<%= user_icon guessed_user %> +<span><%= link_to_user guessed_user %></span> +<%= link_to (image_tag 'add_friend.gif', :style => "border:0px;"), new_user_friend_request_url(current_user, :receiver_id => guessed_user.id), :rel => 'facebox' %> +</div> diff --git a/app/views/user/friend_guesses/_server_character.html.erb b/app/views/user/friend_guesses/_server_character.html.erb new file mode 100644 index 0000000..fb72061 --- /dev/null +++ b/app/views/user/friend_guesses/_server_character.html.erb @@ -0,0 +1,13 @@ +<div class='friend_suggestion' id='friend_suggestion_<%= server_character[0] %>'> +<% @common_game_user = User.find(server_character[0]) %> +<%= user_icon @common_game_user %> +<%= link_to_user @common_game_user %> +player name: <%= server_character[1] %> + <% if current_user.id == @common_game_user.id %> + <% elsif current_user.has_friend(@common_game_user) %> + 已为好友 + <% elsif current_user.has_friend_request(@common_game_user)%> + 以发出邀请 + <% else %> + <%= link_to (image_tag 'add_friend.gif', :style => "border:0px;"), new_user_friend_request_url(current_user, :receiver_id => @common_game_user.id), :rel => 'facebox' %> + <% end %> diff --git a/app/views/user/friend_guesses/index.html.erb b/app/views/user/friend_guesses/index.html.erb new file mode 100644 index 0000000..a09d285 --- /dev/null +++ b/app/views/user/friend_guesses/index.html.erb @@ -0,0 +1,14 @@ +<h3> 你可能认识这些人哦! </h3> +<% if @friend_suggestions.empty? %> +请您先输入相关信息 +<% end %> +<%= render :partial => 'guessed_user', :collection => @friend_suggestions %> +<% @common_game_characters.each do |game_server_id, server_users_hash| %> +<% @server = GameServer.find(game_server_id) %> +<h3>有<%= server_users_hash.size %>个玩家在您所在的<%= @server.game.name %> <%= @server.name %>在一起玩</h3> +<% unless (server_users_hash.size <=3) %> +<%= link_to '查看全部', show_all_user_friend_guesses_path(@user, :server_id => game_server_id) %> +<% end %> +<%= render :partial => 'server_character', :collection => server_users_hash.sort_by{rand}[0..2] %> +<% end %> +<br/>要寻找所有玩过的游戏的伙伴么? <%= link_to '是的', show_all_server_characters_user_friend_guesses_path(@user)%> diff --git a/app/views/user/friend_guesses/show_all.html.erb b/app/views/user/friend_guesses/show_all.html.erb new file mode 100644 index 0000000..54442f1 --- /dev/null +++ b/app/views/user/friend_guesses/show_all.html.erb @@ -0,0 +1,23 @@ +<% @user_array.each do |user_info| %> +<% @user = User.find(user_info[0]) %> +<div class='friend' id='<%= "friend_suggestion_#{user_info[0]}"%>'> + <%= user_icon(@user) %> + <div class='user-link'> + <%= link_to_user @user%><br/> + <span class='friend-tiny'> + <%= user_info[1] %> + </span> + </div> + <div class='operation'> + <% if current_user.id == @user.id %> + <% elsif current_user.has_friend(@user) %> + 已为好友 + <% elsif current_user.has_friend_request(@user)%> + 以发出邀请 + <% else %> + <%= link_to (image_tag 'add_friend.gif', :style => "border:0px;"), new_user_friend_request_url(current_user, :receiver_id => user_info[0]), :rel => 'facebox' %> + <% end %> + </div> +</div> +<% end %> +<%= will_paginate @user_array %> diff --git a/app/views/user/friend_guesses/show_all_server_characters.html.erb b/app/views/user/friend_guesses/show_all_server_characters.html.erb new file mode 100644 index 0000000..80018b7 --- /dev/null +++ b/app/views/user/friend_guesses/show_all_server_characters.html.erb @@ -0,0 +1,10 @@ +<h3> 您一共玩了<%= @common_game_characters.size %>款以下游戏 </h3> +<% @common_game_characters.each do |game_server_id, server_users_hash| %> +<% @server = GameServer.find(game_server_id) %> +<h3>有<%= server_users_hash.size %>个玩家在您所在的<%= @server.game.name %> <%= @server.name %>在一起玩</h3> +<% unless (server_users_hash.size <=3) %> +<%= link_to '查看全部', show_all_user_friend_guesses_path(@user, :server_id => game_server_id) %> +<% end %> +<%= render :partial => 'server_character', :collection => server_users_hash.sort_by{rand}[0..2] %> +<% end %> + diff --git a/app/views/user/friends/_friend_menu.html.erb b/app/views/user/friends/_friend_menu.html.erb index 8a2e309..7b593c2 100755 --- a/app/views/user/friends/_friend_menu.html.erb +++ b/app/views/user/friends/_friend_menu.html.erb @@ -1,25 +1,25 @@ <%= text_field_tag 'search' %> <%= observe_field :search, :complete => "facebox.watchClickEvents();", :update => "friends", :frequency => 1, :url => search_user_friends_url, :with => "'key='+$('search').value", :method => :get %> <div class='fby'> <h3> Friend menu: <%= link_to_function 'fold', "$('friend_menus').toggle();if(this.innerHTML == 'fold') this.update('unfold');else this.update('fold');" %></h3> <div id='friend_menus'> <li> <%= link_to "all friends", user_friends_url(@user, :term => 'name') %> <%= link_to_function '+', "$('game_list').toggle(); if(this.innerHTML == '+') this.update('-');else this.update('+')" %> <div id="game_list" class='fby-submenu' style="display:none"> <% @user.games.each do |game| %> <li><%= link_to game.name, user_friends_url(@user, :term => 'game', :game_id => game) %></li> <% end %> </div> </li> - <li><%= link_to "friend suggestion" %></li> + <li><%= link_to "friend suggestion", user_friend_guesses_url(@user) %></li> <li><%= link_to "recently added friends", user_friends_url(@user, :term => 'time') %></li> </div> </div> diff --git a/app/views/user/mailboxes/_friends.html.erb b/app/views/user/mailboxes/_friends.html.erb new file mode 100755 index 0000000..d5b334a --- /dev/null +++ b/app/views/user/mailboxes/_friends.html.erb @@ -0,0 +1,5 @@ +<ul> + <% friends.each do |friend| %> + <li style="list-style-type:none;" user_id=<%= friend.id %> user_login=<%= friend.login%> ><%= friend.login %> </li> + <% end %> +</ul> diff --git a/app/views/user/mailboxes/_recipient.html.erb b/app/views/user/mailboxes/_recipient.html.erb new file mode 100644 index 0000000..786b286 --- /dev/null +++ b/app/views/user/mailboxes/_recipient.html.erb @@ -0,0 +1,6 @@ +<div recipient_id=<%=recipient.id%>> +<%= link_to_user recipient %> +<% if (:condition == 1)%> +<%= link_to_function 'x', "mail_builder.remove_recipient(#{recipient.id})" %> +<% end %> +</div> diff --git a/app/views/user/mailboxes/new.html.erb b/app/views/user/mailboxes/new.html.erb index 0aeb81a..46ac8f4 100755 --- a/app/views/user/mailboxes/new.html.erb +++ b/app/views/user/mailboxes/new.html.erb @@ -1,30 +1,30 @@ <%= javascript_include_tag 'mailbox' %> <%= render :partial => 'mailbox_menu' %> <ul id='mail_info'></ul> <table> -<% form_for :mail, :url => user_mails_url, :html => {:onsubmit => "return validate_mail();"} do |form| %> <tr> - <td><%= form.label 'recipient: ' %></td> - <td><%= text_field_with_auto_complete :mail, :recipients, {}, {:tokens => ','} %></td> + <td><%= label :mail, 'find recipient: ' %></td> + <td><%= text_field_with_auto_complete :mail, :recipients, {}, {:after_update_element => "after_auto_select" } %></td> </tr> + <tr><td><%= label :mail, "recipient:" %></td><td> <div id='recipients_info'></div></td></tr> +<% form_for :mail, :html => {:id => 'mail_form'} do |form| %> <tr> <td><%= form.label 'title: ' %></td> <td><%= form.text_field 'title' %></td> </tr> <tr> <td><%= form.label 'content: ' %></td> <td><%= form.text_area 'content', :rows => 8, :cols => 35 %></td> </tr> - <tr> - <td></td><td><%= form.submit 'send' %></td> - </tr> <% end %> </table> - +<%= javascript_tag "mail_builder = new MailBuilder(#{@user.id});" %> +<%= link_to_function "send", "mail_builder.validate_save()" %> <% unless @receiver.blank? %> <script type="text/javascript"> $('mail_recipients').value = '<%= @receiver.login %>'; - $('mail_recipients').disabled = true; + $('mail_recipients').disabled = true; + mail_builder.new_recipient(<%= @receiver.id %>, 0); </script> <% end %> diff --git a/app/views/user/personal/_friend_guesses.html.erb b/app/views/user/personal/_friend_guesses.html.erb new file mode 100644 index 0000000..8c66f1f --- /dev/null +++ b/app/views/user/personal/_friend_guesses.html.erb @@ -0,0 +1,23 @@ +<div class='visitors'> + <h3>Your friends suggestions: <%= link_to_function 'fold', "$('friend_suggestion_table').toggle();if(this.innerHTML == 'fold') this.update('unfold'); else this.update('fold');", :class => 'hide-all'%></h3> + <table id='friend_suggestion_table'> + <% i=0 %> + <% friend_guesses.each do |friend| %> + <% if i == 0 %> + <tr> + <% end %> + <td class='record'> + <%= user_icon friend %><br/> + <%= link_to_user friend %> + </td> + <% i = i + 1 %> + <% if i == 3 %> + </tr> + <% i = 0 %> + <% end %> + <% end %> + </table> + <div class='view-all'> + <%= link_to 'view all', user_friend_guesses_url(@user) %> + </div> +</div> diff --git a/app/views/user/personal/show.html.erb b/app/views/user/personal/show.html.erb index c7d0346..2293d2f 100644 --- a/app/views/user/personal/show.html.erb +++ b/app/views/user/personal/show.html.erb @@ -1,24 +1,25 @@ <% content_for :left do %> <%= render :partial => 'user/personal/icon_left' %><br/> <%= render :partial => 'user/personal/character_left' %><br/> <%= render :partial => 'user/personal/activity_left' %><br/> <%= render :partial => 'user/personal/album_left' %><br/> <% end %> <% content_for :right do %> <%= render :partial => 'user/personal/visitor_history', :object => @user.visitor_records[0..8] %><br/> <%= render :partial => 'user/personal/friends', :object => @user.friends[0..14] %> + <%= render :partial => 'user/personal/friend_guesses', :object => @user.guessed_friends[0..2] %> <% end %> <%= render :partial => 'user/personal/menu' %> <%= render :partial => 'user/statuses/show' %> <div id='personal_container'> <h3>Wall: <%= link_to "all wall messages", user_wall_messages_url(@user) %></h3> <%= render :partial => 'user/wall_messages/input' %> <div id='wall_messages'> <%= render :partial => 'user/wall_messages/wall_message', :collection => @wall_messages %> </div> </div> diff --git a/app/views/users/index.html.erb b/app/views/users/index.html.erb new file mode 100755 index 0000000..b9ead63 --- /dev/null +++ b/app/views/users/index.html.erb @@ -0,0 +1,34 @@ +<h1>Listing users</h1> + +<table> + <tr> + <th>id</th> + <th>Email</th> + <th>Vname</th> + <th>Gender</th> + <th>Created at</th> + <th>Activated at</th> + </tr> + +<% @users.each do |user| %> + <tr> + <td><%=h user.id %></td> + <td><%=h user.email %></td> + <td><%=h user.login %></td> + <td><%=h user.gender %></td> + <td><%=h ftime user.created_at %></td> + <td><%=h ftime user.activated_at %></td> + <% unless user == current_user %> + <% if user.enabled %> + <td>[<%= link_to 'disable', user, :method => :delete %>]</td> + <% else %> + <td>[<%= link_to 'enable', enable_user_url(user), :method => :put %>]</td> + <% end %> + <% end %> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New user', new_user_url %> diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb new file mode 100755 index 0000000..fe36102 --- /dev/null +++ b/app/views/users/new.html.erb @@ -0,0 +1,40 @@ +<%= javascript_include_tag 'validator' %> + +<% form_for :user, :html => {:id => 'register_form'} do |f| -%> +<p> + <label>Login</label><br/> + <%= f.text_field :login, :onblur => "validate_login(this.value)", :onfocus => "show_login_requirement();" %> + <a id='login_info'></a> +</p> + +<p> + <label>Email</label><br/> + <%= f.text_field :email, :onblur => "validate_email(this.value)", :onfocus => "show_email_requirement();" %> + <a id='email_info'></a> +</p> + +<p> + <%= f.radio_button 'gender', 'male' %> male + <%= f.radio_button 'gender', 'female' %> female +</p> + +<p> + <label for="password">Password</label><br/> + <%= f.password_field :password, :onblur => "validate_password(this.value)", :onfocus => "show_password_requirement();"%> + <a id='password_info'></a> +</p> + +<p> + <label for="password_confirmation">Confirm Password</label><br/> + <%= f.password_field :password_confirmation, :onblur => "validate_password_confirmation(this.value)", :onclick => "show_password_confirm_requirement()" %> + <a id='password_confirmation_info'></a> +</p> + +<p> Game Characters: </p> +<div id='character_info'></div> +<ul id='characters'></ul> +<%= link_to 'add game character', {:controller => :register, :action => 'new_character'}, :rel => 'facebox' %> + +<% end -%> + +<%= link_to_function 'submit', "validate_and_request()" %> diff --git a/config/.database.yml.swp b/config/.database.yml.swp new file mode 100644 index 0000000..e42f014 Binary files /dev/null and b/config/.database.yml.swp differ diff --git a/config/routes.rb b/config/routes.rb index 53d063c..62b8f1d 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,257 +1,261 @@ ActionController::Routing::Routes.draw do |map| map.resources :events, :member =>{:confirm_destroy => :get}, :collection => {:game_details => :get, :area_details => :get} do |events| events.resource :album, :controller => 'event/album', :member => {:confirm_destroy => :get} events.resources :photos, :controller => 'event/photos', :member => {:confirm_destroy => :get, :cover => :post}, :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} events.resources :wall_messages, :controller => 'event/wall_messages' end map.resources :participations, :collection => {:new_participation => :get, :friends_list => :get} map.resources :sessions map.root :controller => 'sessions', :action => 'new' map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate' map.forgot_password '/forgot_password', :controller => 'passwords', :action => 'new' map.reset_password '/reset_password/:password_reset_code', :controller => 'passwords', :action => 'edit' map.change_password '/change_password', :controller => 'accounts', :action => 'edit' map.upload_image '/upload_images', :controller => 'user/blog_images', :action => 'upload' map.namespace(:admin) do |admin| admin.resources :videos admin.resources :vtags admin.resources :vdigs admin.resources :vcomments admin.resources :blogs admin.resources :btags admin.resources :bdigs admin.resources :bcomments admin.resources :albums admin.resources :photos admin.resources :ptags admin.resources :pdigs admin.resources :pcomments admin.resources :pages admin.resources :statuses admin.resources :scomments admin.resources :wall_messages admin.resources :mails admin.resources :friendships admin.resources :game_characters admin.resources :game_races admin.resources :game_professions admin.resources :game_servers admin.resources :game_areas admin.resources :games end map.resources :users, :member => {:enable => :put} do |users| users.resource :password, :controller => 'user/password' users.resource :personal, :controller => 'user/personal' users.resource :profile, :controller => 'user/profile' users.resource :basic_info, :controller => 'user/basic_info' users.resource :contact_info, :controller => 'user/contact_info' users.resources :icons, :controller => 'user/icons', :member => {:confirm_destroy => :get, :set => :post} users.resources :characters, :controller => 'user/characters', :member => {:confirm_destroy => :get} users.resources :wall_messages, :controller => 'user/wall_messages' users.resources :mails, :controller => 'user/mailboxes', :member => {:reply => :post}, - :collection => {:read_multiple => :put, :unread_multiple => :put, :destroy_multiple => :delete} + :collection => {:read_multiple => :put, :unread_multiple => :put, :destroy_multiple => :delete, :new_recipient => :get} users.resources :friends, :controller => 'user/friends', :member => {:confirm_destroy => :get}, :collection => {:search => :get} + users.resources :friend_guesses, + :controller => 'user/friend_guesses', + :collection => {:show_all => :get, :show_all_server_characters => :get} + users.resources :friend_requests, :controller => 'user/friend_requests', :member => {:confirm_destroy => :get} users.resources :friend_notifications, :controller => 'user/friend_notifications' users.resources :visitor_records, :controller => 'user/visitor_records' users.resources :statuses, :controller => 'user/statuses' users.resources :status_feeds, :controller => 'user/status_feeds', :collection => {:get => :get} users.resources :blogs, :controller => 'user/blogs', :member => {:confirm_destroy => :get}, :collection => {:destroy_multiple => :delete} users.resources :blog_feeds, :controller => 'user/blog_feeds', :collection => {:get => :get} users.resources :tagged_blogs, :controller => 'user/tagged_blogs' users.resources :albums, :controller => 'user/albums', :member => {:confirm_destroy => :get} users.resources :album_feeds, :controller => 'user/album_feeds', :collection => {:get => :get} users.resources :tagged_photos, :controller => 'user/tagged_photos' users.resources :videos, :controller => 'user/videos', :member => {:confirm_destroy => :get} users.resources :video_feeds, :controller => 'user/video_feeds', :collection => {:get => :get} users.resources :tagged_videos, :controller => 'user/tagged_videos' users.resources :resource_feeds, :controller => 'user/resource_feeds', :collection => {:get => :get} users.resources :comment_notifications, :controller => 'user/comment_notifications', :collection => {:read_multiple => :post} users.resources :tag_notifications, :controller => 'user/tag_notifications', :collection => {:read_multiple => :post} users.resources :pokes, :controller => 'user/pokes', :collection => {:destroy_all => :delete} users.resource :privacy_setting, :controller => 'user/privacy_setting' users.resource :mail_setting, :controller => 'user/mail_setting' users.resource :application_setting, :controller => 'user/application_setting' end map.resources :statuses do |statuses| statuses.resources :comments, :controller => 'user/scomments' end map.resources :blogs do |blogs| blogs.resources :comments, :controller => 'user/bcomments' blogs.resources :tags, :controller => 'user/btags' blogs.resources :digs, :controller => 'user/bdigs' end map.resources :photos do |photos| photos.resources :comments, :controller => 'user/pcomments' photos.resources :tags, :controller => 'user/ptags' photos.resources :digs, :controller => 'user/pdigs' end map.resources :albums do |albums| albums.resources :photos, :controller => 'user/photos', :member => {:confirm_destroy => :get, :cover => :post}, :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} end map.resources :videos do |videos| videos.resources :comments, :controller => 'user/vcomments' videos.resources :tags, :controller => 'user/vtags' videos.resources :digs, :controller => 'user/vdigs' end map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090901162327_create_friend_guesses.rb b/db/migrate/20090901162327_create_friend_guesses.rb new file mode 100644 index 0000000..1bc352e --- /dev/null +++ b/db/migrate/20090901162327_create_friend_guesses.rb @@ -0,0 +1,13 @@ +class CreateFriendGuesses < ActiveRecord::Migration + def self.up + create_table :friend_guesses do |t| + t.integer :user_id + t.integer :guess_id + t.timestamps + end + end + + def self.down + drop_table :friend_guesses + end +end diff --git a/db/schema.rb b/db/schema.rb index 334961a..254fdca 100755 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,473 +1,480 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090830132411) do +ActiveRecord::Schema.define(:version => 20090901162327) do create_table "account_settings", :force => true do |t| t.datetime "created_at" t.datetime "updated_at" end create_table "admin_pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "albums", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "photos_count", :default => 0 t.string "title" t.text "description" t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomment_notifications", :force => true do |t| t.integer "user_id" t.integer "commentor_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomments", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "bdigs", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "blogs", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title", :limit => 64 t.text "content", :limit => 16777215 t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.boolean "draft", :default => true t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "btags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "cities", :force => true do |t| t.string "name" t.integer "city_id" t.datetime "created_at" t.datetime "updated_at" end create_table "comment_notifications", :force => true do |t| t.integer "user_id" t.integer "comment_id" t.string "comment_type" t.boolean "read", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "countries", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "event_wall_messages", :force => true do |t| t.integer "event_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.datetime "created_at" t.datetime "updated_at" end create_table "events", :force => true do |t| t.string "title" t.integer "poster_id" t.integer "game_id" t.integer "game_server_id" t.integer "game_area_id" t.integer "album_id" t.integer "participations_count", :default => 0 t.datetime "time" t.text "description" t.datetime "created_at" t.datetime "updated_at" end + create_table "friend_guesses", :force => true do |t| + t.integer "user_id" + t.integer "guess_id" + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "friend_notifications", :force => true do |t| t.integer "user_id" t.integer "sender_id" t.string "content" t.datetime "created_at" t.datetime "updated_at" end create_table "friend_requests", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.string "content" t.datetime "created_at" t.datetime "updated_at" end create_table "friendships", :force => true do |t| t.integer "user_id" t.integer "friend_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_areas", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_characters", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "server_id" t.integer "area_id" t.integer "profession_id" t.integer "race_id" t.string "name" t.integer "level" t.boolean "playing" t.datetime "created_at" t.datetime "updated_at" end create_table "game_professions", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_races", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_servers", :force => true do |t| t.string "name" t.string "ip" t.integer "game_id" t.integer "area_id" t.datetime "created_at" t.datetime "updated_at" end create_table "games", :force => true do |t| t.string "name" t.string "company" t.datetime "sale_date" t.text "description" t.boolean "no_areas", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "icons", :force => true do |t| t.integer "user_id" t.boolean "current" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "mail_settings", :force => true do |t| t.integer "user_id" t.boolean "mail_me", :default => true t.boolean "request_to_be_friend", :default => true t.boolean "confirm_friend", :default => true t.boolean "birthday", :default => false t.boolean "comment_my_status", :default => true t.boolean "comment_same_status_after_me", :default => true t.boolean "message_me", :default => true t.boolean "poke_me", :default => true t.boolean "tag_me_in_photo", :default => true t.boolean "tag_my_photo", :default => true t.boolean "comment_my_photo", :default => true t.boolean "comment_photo_contains_me", :default => true t.boolean "comment_same_photo_after_me", :default => true t.boolean "tag_me_in_blog", :default => true t.boolean "comment_my_blog", :default => true t.boolean "comment_same_blog_after_me", :default => true t.boolean "comment_blog_contains_me", :default => true t.boolean "tag_me_in_video", :default => true t.boolean "comment_my_video", :default => true t.boolean "comment_same_video_after_me", :default => true t.boolean "comment_video_contains_me", :default => true end create_table "mails", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.boolean "delete_by_sender", :default => false t.boolean "delete_by_receiver", :default => false t.boolean "read_by_sender", :default => true t.boolean "read_by_receiver", :default => false t.string "title" t.text "content" t.integer "parent_id" t.datetime "created_at" t.datetime "updated_at" end create_table "pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "participations", :force => true do |t| t.integer "inviter_id" t.integer "participant_id" t.integer "event_id" t.integer "event_status" t.datetime "created_at" t.datetime "updated_at" end create_table "pcomments", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "pdigs", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.datetime "created_at" t.datetime "updated_at" end create_table "permissions", :force => true do |t| t.string "user_id" t.string "role_id" t.datetime "created_at" t.datetime "updated_at" end create_table "photos", :force => true do |t| t.integer "digs_count", :default => 0 t.integer "tags_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "album_id" t.boolean "cover", :default => false t.integer "user_id" t.boolean "current_icon", :default => false t.text "notation" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "pokes", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.string "content", :default => "hi" t.datetime "created_at" t.datetime "updated_at" end create_table "privacy_settings", :force => true do |t| t.integer "user_id" t.integer "personal", :default => 1 t.integer "friend", :default => 0 t.boolean "search", :default => true t.datetime "created_at" t.datetime "updated_at" end create_table "provinces", :force => true do |t| t.string "name" t.integer "country_id" t.datetime "created_at" t.datetime "updated_at" end create_table "ptags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "photo_id" t.integer "x" t.integer "y" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "roles", :force => true do |t| t.string "name", :null => false t.datetime "created_at" t.datetime "updated_at" end create_table "scomments", :force => true do |t| t.integer "user_id" t.integer "status_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "statuses", :force => true do |t| t.integer "user_id" t.text "content" t.integer "comments_count", :default => 0 t.datetime "created_at" t.datetime "updated_at" end create_table "tag_notifications", :force => true do |t| t.integer "user_id" t.integer "tag_id" t.string "tag_type" t.boolean "read", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :limit => 64 t.string "email", :limit => 128 t.string "crypted_password", :limit => 64 t.string "salt", :limit => 40 t.string "gender" t.boolean "enabled", :default => true t.string "remember_token" t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "password_reset_code", :limit => 40 t.integer "country_id" t.integer "province_id" t.integer "city_id" t.integer "qq" t.integer "mobile" t.string "website" t.datetime "birthday" t.datetime "created_at" t.datetime "updated_at" end create_table "vcomments", :force => true do |t| t.integer "user_id" t.integer "video_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "vdigs", :force => true do |t| t.integer "user_id" t.integer "video_id" t.datetime "created_at" t.datetime "updated_at" end create_table "videos", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title" t.string "url" t.text "link" t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "visitor_records", :force => true do |t| t.integer "user_id" t.integer "visitor_id" t.boolean "register", :default => true t.datetime "created_at" t.datetime "updated_at" end create_table "vtags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "video_id" t.datetime "created_at" t.datetime "updated_at" end create_table "wall_messages", :force => true do |t| t.integer "user_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end end diff --git a/public/images/addfriendicons.gif b/public/images/addfriendicons.gif new file mode 100644 index 0000000..f403980 Binary files /dev/null and b/public/images/addfriendicons.gif differ diff --git a/public/javascripts/application.js b/public/javascripts/application.js index fe45776..0a68699 100755 --- a/public/javascripts/application.js +++ b/public/javascripts/application.js @@ -1,2 +1,7 @@ // Place your application-specific JavaScript functions and classes here // This file is automatically included by javascript_include_tag :defaults +function renew_validation_image(){ + now = new Date(); + var imageUrl = "/application/new_validation_image?time=" + now.getTime(); + document.validationImage.src = imageUrl; +} diff --git a/public/javascripts/mailbox.js b/public/javascripts/mailbox.js index a36a46e..5dff339 100755 --- a/public/javascripts/mailbox.js +++ b/public/javascripts/mailbox.js @@ -1,193 +1,252 @@ // the first javascript file i have written in my life function get_mail_id(checkbox){ var idx = checkbox.value.indexOf('-'); return checkbox.value.substring(0, idx); } function get_mail_read(checkbox){ var idx = checkbox.value.indexOf('-'); var len = checkbox.value.length; return checkbox.value.substring(idx + 1, len); } function url_for(checkboxes, user_id, action){ var len = checkboxes.length; var url = '/users/' + user_id + '/mails/' +action + '?'; for(var i=0;i<len;i++){ url += ('mail_ids[]=' + get_mail_id(checkboxes[i])); if(i != len - 1) url += '&'; } return url; } function get_all_mails(){ var checkboxes = []; var inputs = $$('input'); for(var i=0;i<inputs.length;i++){ if(inputs[i].type == 'checkbox'){ checkboxes.push(inputs[i]); } } return checkboxes; } function get_all_selected_mails(){ var checkboxes = []; var inputs = $$('input'); for(var i=0;i<inputs.length;i++){ if(inputs[i].type == 'checkbox' && inputs[i].checked){ checkboxes.push(inputs[i]); } } return checkboxes; } function get_all_read_mails(){ var checkboxes = []; var inputs = $$('input'); for(var i=0;i<inputs.length;i++){ if(inputs[i].type == 'checkbox' && get_mail_read(inputs[i]) == 'true'){ checkboxes.push(inputs[i]); } } return checkboxes; } function get_all_unread_mails(){ var checkboxes = []; var inputs = $$('input'); for(var i=0;i<inputs.length;i++){ if(inputs[i].type == 'checkbox' && get_mail_read(inputs[i]) == 'false'){ checkboxes.push(inputs[i]); } } return checkboxes; } function uncheck_all_checkboxes(){ var inputs = $$('input'); for(var i=0;i<inputs.length;i++){ if(inputs[i].type == 'checkbox'){ inputs[i].checked = false; } } } function selection_onchange(){ var checkboxes = get_all_selected_mails(); var len = checkboxes.length; //TODO: change CSS } function select_dropdown_onchange(selector) { uncheck_all_checkboxes(); if($F(selector) == 'all'){ var checkboxes = get_all_mails(); var len = checkboxes.length; for(var i=0;i<len;i++){ checkboxes[i].checked = true; } }else if($F(selector) == 'none'){ var checkboxes = get_all_mails(); var len = checkboxes.length; for(var i=0;i<len;i++) checkboxes[i].checked = false; }else if($F(selector) == 'read'){ var checkboxes = get_all_read_mails(); var len = checkboxes.length; for(var i=0;i<len;i++) checkboxes[i].checked = true; }else if($F(selector) == 'unread'){ var checkboxes = get_all_unread_mails(); var len = checkboxes.length; for(var i=0;i<len;i++) checkboxes[i].checked = true; } } function read_mails(user_id) { var checkboxes = get_all_selected_mails(); var url = url_for(checkboxes, user_id, 'read_multiple'); new Ajax.Request(url, { asynchronous: true, method: 'put', onSuccess: function(transport) { var checkboxes = get_all_selected_mails(); var len = checkboxes.length; for(var i=0;i<len;i++){ var mail = $('mail_' + get_mail_id(checkboxes[i]) + '_title'); mail.style.fontWeight = ''; var checkbox = $('select_mail_' + get_mail_id(checkboxes[i])); checkbox.value = get_mail_id(checkboxes[i]) + "-true"; } $('recv_mails_count').innerHTML = transport.responseText; } }); } function unread_mails(user_id){ var checkboxes = get_all_selected_mails(); var url = url_for(checkboxes, user_id, 'unread_multiple'); new Ajax.Request(url, { asynchronous: true, method: 'put', onSuccess: function(transport) { var checkboxes = get_all_selected_mails(); var len = checkboxes.length; for(var i=0;i<len;i++){ var mail = $('mail_' + get_mail_id(checkboxes[i]) + '_title'); mail.style.fontWeight = 'bold'; var checkbox = $('select_mail_' + get_mail_id(checkboxes[i])); checkbox.value = get_mail_id(checkboxes[i]) + "-false"; } $('unread_recv_mails').innerHTML = transport.responseText + " unread"; } }); } function delete_mails(user_id, type){ var checkboxes = get_all_selected_mails(); var url = url_for(checkboxes, user_id, 'destroy_multiple'); url += ('&' + 'type=' + type); new Ajax.Request(url, { asynchronous: true, method: 'delete', onSuccess: function(transport) { window.location.href = transport.responseText; } }); } -function validate_mail(){ - var recipients = $('mail_recipients'); +function after_auto_select(input_field, selected_li){ + mail_builder.new_recipient(selected_li.readAttribute('user_id'), 1); +} + +function double_check_recipient(){ + mail_builder.check_recipient($('mail_recipients').value); +} + +MailBuilder = Class.create({ + validate_mail: function(){ var title = $('mail_title'); var content = $('mail_content'); var info = $('mail_info'); var error = false; info.innerHTML = ''; - if(recipients.value == ''){ + if(this.recipients.size == 0){ error = true; info.insert('<li style="color: red">you must specify at least one recipient</li>', {position: 'bottom'}); } if(title.value == ''){ error = true; info.insert('<li style="color: red">title cannot be blank</li>', {position: 'bottom'}); } if(content.value == ''){ error =true; info.insert('<li style="color: red">content cannot be blank</li>', {position: 'bottom'}); } if(!error) $('mail_recipients').disabled = false; - return !error; -} - + return error; +}, + + initialize: function(user_id){ + this.user_id = user_id; + + this.recipients = new Hash(); + }, + + new_recipient: function(recipient_id, case_id){ + if(this.recipients.get(recipient_id)) return; + new Ajax.Request('/users/'+this.user_id+'/mails/new_recipient?recipients[]='+recipient_id + '&condition='+case_id, { + method: 'get', + onSuccess: function(transport){ + $('recipients_info').innerHTML = transport.responseText + $('recipients_info').innerHTML; + $('mail_recipients').value=''; + var children = $('recipients_info').childElements(); + var length = children.length; + for(var i=0;i<length;i++){ + this.recipients.set(children[i].readAttribute('recipient_id'), children[i]); + } + }.bind(this) + }); + }, + + remove_recipient: function(recipient_id){ + var recipient_code = this.recipients.unset(recipient_id); + recipient_code.remove(); + }, + + check_recipient: function(recipient_names){ + this.recipients.each(function(pair){ + if (recipient_names.match(pair.value) == null) + this.recipients.unset(pair.key); + }.bind(this)); + }, + + validate_save: function(){ + if (this.validate_mail()) return; + + var form = $('mail_form'); + var title = $('mail_title').value; + var content = $('mail_content').value; + var url = '/users/' + this.user_id; + url += '/mails?'; + this.recipients.each(function(pair){ + url += "recipients[]=" + pair.key + "&"; + }); + url += "mail[title]=" + title + "&"; + url += "mail[content]=" + content; + new Ajax.Request(url, {method: 'post'}); + }, + +}); diff --git a/test/fixtures/friend_guesses.yml b/test/fixtures/friend_guesses.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/friend_guesses.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/functional/user/friend_guesses_controller_test.rb b/test/functional/user/friend_guesses_controller_test.rb new file mode 100644 index 0000000..5d3c241 --- /dev/null +++ b/test/functional/user/friend_guesses_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class User::FriendGuessesControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/friend_guess_test.rb b/test/unit/friend_guess_test.rb new file mode 100644 index 0000000..4ad7e08 --- /dev/null +++ b/test/unit/friend_guess_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class FriendGuessTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/helpers/user/friend_guesses_helper_test.rb b/test/unit/helpers/user/friend_guesses_helper_test.rb new file mode 100644 index 0000000..bed53ed --- /dev/null +++ b/test/unit/helpers/user/friend_guesses_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class User::FriendGuessesHelperTest < ActionView::TestCase +end
goodxiexin/dayday3
8252f869d155709d372904934c7920d8a939ea6e
event 1st round complete
diff --git a/app/controllers/event/album_controller.rb b/app/controllers/event/album_controller.rb new file mode 100644 index 0000000..ecddcc0 --- /dev/null +++ b/app/controllers/event/album_controller.rb @@ -0,0 +1,78 @@ +class Event::AlbumController < ApplicationController + + layout 'user' + + def index + end + + def show + @event = Event.find(params[:event_id]) + @user = @event.poster + @album = @event.album + if @album.privilege == 'friends' and relationship != 'owner' and relationship != 'friend' + flash[:error] = "This album is only viewable for friends" + redirect_to new_user_friend_url(current_user, :friend_id => @user.id) + end + if @album.privilege == 'owner' and relationship != 'owner' + render :text => 'you dont have permission to view this album' + end + @photos = @album.photos.paginate :page => params[:page], :per_page => 12, :order => 'position DESC' + rescue ActiveRecord::RecordNotFound + render :text => 'album not found' + end + + def new + end + + def edit + @event = Event.find(params[:event_id]) + @album = @event.album + @user = @event.poster + rescue ActiveRecord::RecordNotFound + render :text => 'album not found' + end + + def create + end + + def update + @event = Event.find(params[:event_id]) + @user = @event.poster + @album = @event.album + if @album.update_attributes(params[:album]) + flash[:notice] = "update successful" + redirect_to event_album_url(@event) + else + flash.now[:error] = "There was an error updating this album" + render :action => 'edit' + end + end + + def confirm_destroy + @event = Event.find(params[:event_id]) + @user = @event.poster + @album = @event.album + rescue ActiveRecord::RecordNotFound + render :text => 'album not found' + end + + def destroy + @event = Event.find(params[:event_id]) + @user = @event.poster + @album = @event.album + if session[:validation_text] == params[:validation_text] + @album.destroy + respond_to do |format| + format.html { redirect_to event_album_url(:event_id => @event) } + format.xml { head :ok } + end + else + flash.now[:error] = "validation cod +e error" + render :action => 'confirm_destroy' + end + rescue ActiverRecord::RecordNotFound + render :text => 'album not found' + end + +end diff --git a/app/controllers/event/photos_controller.rb b/app/controllers/event/photos_controller.rb new file mode 100644 index 0000000..5ea7dcc --- /dev/null +++ b/app/controllers/event/photos_controller.rb @@ -0,0 +1,144 @@ +class Event::PhotosController < ApplicationController + + layout 'user' + + def show + @event = Event.find(params[:event_id]) + @album = @event.album + @user = @event.poster + if @album.privilege == 'friends' and relationship != 'owner' and relationsihp != 'friend' + flash[:error] = "This photo is only viewable for friends" + redirect_to new_user_friend_url(current_user, :friend_id => @user.id) + end + if @album.privilege == 'myself' and relationship != 'owner' + render :text => 'only owner is allowed to view this album' + end + @photo = @album.photos.find(params[:id]) + rescue ActiveRecord::RecordNotFound + render :text => 'photo not found' + end + + def new + @event = Event.find(params[:event_id]) + @album = @event.album + @user = @event.poster + end + + def create_multiple + @event = Event.find(params[:event_id]) + @album = @event.album + @user = @event.poster + @photos = [] + @migration = 0 + params[:photos].each do |photo_attributes| + photo = Photo.new(photo_attributes) + photo.album = @album + if photo.save + @photos << photo + end + end + + respond_to do |format| + format.html { render :action => 'edit_multiple' } + format.xml { render :xml => @photos } + end + end + + def edit + @event = Event.find(params[:event_id]) + @album = @event.album + @user = @event.poster + @photo = @album.photos.find(params[:id]) + rescue ActiveRecord::RecordNotFound + render :text => 'photo not found' + end + + def edit_multiple + end + + def update + @event = Event.find(params[:event_id]) + @album = @event.album + @user = @event.poster + @photo = @album.photos.find(params[:id]) + Photo.transaction do + unless params[:photo][:cover].blank? + @album.reset_cover(@photo.id) + end + @photo.update_attributes(params[:photo]) + end + redirect_to event_album_url(@event) + rescue ActiveRecord::RecordNotFound + render :text => 'photo not found' + rescue + flash.now[:error] = "There was an error updating this photo" + render :action => 'edit' + end + + def update_multiple + @event = Event.find(params[:event_id]) + @album = @event.album + @user = @event.poster + Photo.transaction do + params[:photos].each do |photo_id, photo_params| + photo = Photo.find(photo_id) + unless photo_params[:cover].blank? + @album.reset_cover(photo_id) + end + photo.update_attributes(photo_params) + end + end + redirect_to event_album_url(@event) + rescue ActiveRecord::RecordNotFound + render :text => 'photo not found' + rescue + flash.now[:error] = "There was an error updating these photos" + render :action => 'edit_multiple' + end + + def confirm_destroy + @event = Event.find(params[:event_id]) + @album = @event.album + @photo = @album.photos.find(params[:id]) + render :action => 'confirm_destroy', :layout => false + rescue ActiveRecord::RecordNotFound + render :text => 'photo not found' + end + + def cover + @event = Event.find(params[:event_id]) + @album = @event.album + @photo = @album.photos.find(params[:id]) + @album.reset_cover(@photo.id) + render :update do |page| + page << "alert('succeeded')" + end + rescue ActiveRecord::RecordNotFound + render :text => 'photo not found' + end + + def destroy + @event = Event.find(params[:event_id]) + @album = @event.album + @user = @event.poster + @photo = @album.photos.find(params[:id]) + if session[:validation_text] == params[:validation_text] + @photo.destroy + render :update do |page| + page.redirect_to event_album_url(@event) + end + else + render :update do |page| + page << "$('error').innerHTML = 'incorrect validation code'" + end + end + rescue ActiveRecord::RecordNotFound + render :text => 'photo not found' + end + + def friends + @friends = current_user.friends + render :partial => 'friends', :object => @friends + end + +end diff --git a/app/controllers/event_wall_messages_controller.rb b/app/controllers/event/wall_messages_controller.rb similarity index 93% rename from app/controllers/event_wall_messages_controller.rb rename to app/controllers/event/wall_messages_controller.rb index f27e575..7a6d2aa 100644 --- a/app/controllers/event_wall_messages_controller.rb +++ b/app/controllers/event/wall_messages_controller.rb @@ -1,34 +1,34 @@ -class EventWallMessagesController < ApplicationController +class Event::WallMessagesController < ApplicationController def index end def new @event = Event.find(params[:id]) @event_wall_messages = @event.event_wall_messages[0, 10] # get most recent 10 wall messages @event_wall_message = EventWallMessage.new @event_wall_message.event_id = params[:id] end def create @event_wall_message = EventWallMessage.new(params[:event_wall_message]) @event_wall_message.poster_id = current_user.id @event_wall_message.save respond_to do |format| format.html { render :partial => 'event_wall_message', :object => @event_wall_message } format.xml { render :xml => @event_wall_message } end end def destroy @event_wall_message = EventWallMessage.find(params[:id]) @event_wall_message.destroy respond_to do |format| format.html { render :nothing => true } format.xml { head :ok } end end end diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb index 9de79af..2548922 100644 --- a/app/controllers/events_controller.rb +++ b/app/controllers/events_controller.rb @@ -1,46 +1,101 @@ class EventsController < ApplicationController layout 'event' def index + @user = current_user + case params[:term] + when 'up_coming' + games_id = [] + @user.games.each do |game| + games_id << game.id + end + #could not find a way to combine IN games_id with time > Time.now!!! + events = Event.find(:all,:conditions => {:game_id => games_id}) + @events = events.paginate :page => params[:page], :per_page => 10, :order => 'time ASC' + when 'mine' + @events = @user.events.paginate :page => params[:page], :per_page => 10, :order => 'time ASC' + when 'game' + events = Event.find(:all,:conditions => ["game_id = :game_id AND time > :time", {:game_id => params[:game_id], :time => Time.now }]) + @events = events.paginate :page => params[:page], :per_page => 10, :order => 'time ASC' + end end def new @event = Event.new @games = Game.all end def show @event = Event.find(params[:id]) @user = User.find(@event.poster_id) @game = Game.find(@event.game_id) @game_server = GameServer.find(@event.game_server_id) @game_area = GameArea.find(@event.game_area_id) unless @event.game_area_id.nil? @event_wall_messages = @event.event_wall_messages[0, 10] # get most recent 10 event wall messages @event_wall_message = EventWallMessage.new @event_wall_message.receiver_id = @user.id @event_wall_message.event_id = @event.id @album = @event.album @photos = @album.photos.paginate :page => params[:page], :per_page => 4, :order => 'updated_at DESC' # get most recent 5 photos end def create @event = Event.new(params[:event]) - event_album = Album.create(:game_id => @event.game_id, :title => @event.title+'\'s album', :user_id => current_user.id) + event_album = Album.create(:game_id => @event.game_id, :title => @event.title+' event album', :user_id => current_user.id) @event.album_id = event_album.id @event.poster_id = current_user.id @event.save + @event.participations.create(:inviter_id => current_user.id, :participant_id => current_user.id, :event_status => 4) flash[:notice] = "Event is successfully created" redirect_to "/participations/new?event_id="+String(@event.id) end def update end def edit end + def confirm_destroy + @event = Event.find(params[:id]) + render :action => 'confirm_destroy', :layout => false + rescue ActiveRecord::RecordNotFound + render :text => 'event not found' + end + def destroy + @event = Event.find(params[:id]) + if session[:validation_text] == params[:validation_text] + @event.destroy + render :update do |page| + page.redirect_to user_personal_url(current_user) + end + else + render :update do |page| + page << "$('error').innerHTML = 'incorrect validation code'" + end + end + rescue ActiveRecord::RecordNotFound + render :text => 'event not found' end + + def game_details + @game = Game.find(params[:game_id]) + if @game.no_areas + @servers = @game.servers + else + @areas = @game.areas + @servers = [] + end + render :partial => 'game_details' + end + + def area_details + @game_area = GameArea.find(params[:area_id]) + @servers = @game_area.servers + render :partial => 'server_select', :locals => {:servers => @servers, :server_id => nil} + end + end diff --git a/app/controllers/participations_controller.rb b/app/controllers/participations_controller.rb index 740590f..ab5b236 100644 --- a/app/controllers/participations_controller.rb +++ b/app/controllers/participations_controller.rb @@ -1,49 +1,62 @@ class ParticipationsController < ApplicationController layout 'event' def index + @event = Event.find(params[:event_id]) + @type = params[:type] + @people_participations = case @type + when '1' then @event.invitee_participations.paginate :page => params[:page], :per_page => 10, :order => 'created_at DESC' + when '2' then @event.refuser_participations.paginate :page => params[:page], :per_page => 10, :order => 'created_at DESC' + when '3' then @event.maybe_attender_participations.paginate :page => params[:page], :per_page => 10, :order => 'created_at DESC' + when '4' then @event.must_attender_participations.paginate :page => params[:page], :per_page => 10, :order => 'created_at DESC' + end end def new event_id = params[:event_id] @event = Event.find(event_id) @user = current_user @games = Game.all end def create @event = Event.find(params[:event_id]) params[:participants].each do |participant_id| - @event.participations.create(:participant_id => participant_id, :inviter_id => current_user.id) + @event.participations.create(:participant_id => participant_id, :inviter_id => current_user.id, :event_status => 1) end unless params[:participants].blank? flash[:notice] = "successfully invited your friends" render :update do |page| page.redirect_to event_url(@event) end end def new_participation participations = [] params[:participants].each do |participant_id| participations << Participation.new(:participant_id => participant_id) end render :partial => "participation", :collection => participations end def friends_list @user = current_user if params[:game_id].blank? @friends = @user.friends else game = Game.find(params[:game_id]) @friends = @user.friends.find_all {|f| f.games.include?(game) } end render :partial => 'friends_list', :object => @friends end def auto_complete_for_event_participations @user = current_user @friends = @user.friends.find_all {|f| f.login.include?(params[:event][:participations]) } render :partial => 'friends' end + def destroy + @participation = Participation.find(params[:id]) + @participation.destroy + end + end diff --git a/app/helpers/event/album_helper.rb b/app/helpers/event/album_helper.rb new file mode 100644 index 0000000..9319672 --- /dev/null +++ b/app/helpers/event/album_helper.rb @@ -0,0 +1,13 @@ +module Event::AlbumHelper + + def event_album_cover(event, size="medium") + if event.album.photos.count == 0 + link_to image_tag("default_cover_#{size}.jpg"), event_album_url(:event_id => event) + elsif event.album.cover.blank? + link_to image_tag(event.album.photos.first.public_filename(size)), event_album_url(:event_id => event) + else + link_to image_tag(event.album.cover.public_filename(size)), event_album_url(:event_id => event) + end + end + +end diff --git a/app/helpers/event_albums_helper.rb b/app/helpers/event_albums_helper.rb new file mode 100644 index 0000000..7e6a8a1 --- /dev/null +++ b/app/helpers/event_albums_helper.rb @@ -0,0 +1,2 @@ +module EventAlbumsHelper +end diff --git a/app/helpers/event_photos_helper.rb b/app/helpers/event_photos_helper.rb new file mode 100644 index 0000000..26c9c56 --- /dev/null +++ b/app/helpers/event_photos_helper.rb @@ -0,0 +1,2 @@ +module EventPhotosHelper +end diff --git a/app/models/event.rb b/app/models/event.rb index 468c2c6..51a552e 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -1,59 +1,95 @@ class Event < ActiveRecord::Base # the poster of this activity belongs_to :poster, :class_name => 'User' # the category of this activity belongs_to :game # the location of the activity belongs_to :game_server # the album for the event, one-one relation belongs_to :album # the wall messages for a event has_many :event_wall_messages, :dependent => :destroy, :finder_sql => 'select event_wall_messages.* from event_wall_messages where event_wall_messages.event_id = #{id} ORDER BY created_at DESC' # participants of this activity has_many :participations, :dependent => :destroy + has_many :requests, + :class_name => 'Participation', + :conditions => 'event_status = 0', + :dependent => :destroy + has_many :invitee_participations, + :class_name => 'Participation', + :conditions => 'event_status = 1', + :dependent => :destroy + has_many :refuser_participations, + :class_name => 'Participation', + :conditions => 'event_status = 2', + :dependent => :destroy + has_many :maybe_attender_participations, + :class_name => 'Participation', + :conditions => 'event_status = 3', + :dependent => :destroy + has_many :must_attender_participations, + :class_name => 'Participation', + :conditions => 'event_status = 4', + :dependent => :destroy has_many :participants, + :uniq => true, + :through => :participations + has_many :requesters, + :conditions => 'event_status = 0', + :through => :participations + has_many :invitees, + :conditions => 'event_status = 1', + :through => :participations + has_many :refusers, + :conditions => 'event_status = 2', + :through => :participations + has_many :maybe_attenders, + :conditions => 'event_status = 3', + :through => :participations + has_many :must_attenders, + :conditions => 'event_status = 4', :through => :participations # others can comment your activity has_many :comments, :as => 'resource' # register the activity def register(user_id) user = User.find(user_id) if user self.participants << user end end # unregister the activity def unregister(user_id) user = self.participants.find(user_id) if user self.participants.delete(user) end end # cancel this activity # this action is only allowed for the poster of this activity def cancel(user_id) if poster?(user_id) self.destroy end end private # if the user is the poster of this activity def poster?(user_id) (poster_id == user_id)? true : false end end diff --git a/app/models/participation.rb b/app/models/participation.rb index bf9f4f8..0213ad3 100644 --- a/app/models/participation.rb +++ b/app/models/participation.rb @@ -1,13 +1,33 @@ class Participation < ActiveRecord::Base # each participation involves a participant and an event and an inviter belongs_to :participant, :class_name => 'User', :foreign_key => 'participant_id' + belongs_to :invitee, + :class_name => 'User', + :foreign_key => 'participant_id' + + belongs_to :refuser, + :class_name => 'User', + :foreign_key => 'participant_id' + + belongs_to :maybe_attender, + :class_name => 'User', + :foreign_key => 'participant_id' + + belongs_to :must_attender, + :class_name => 'User', + :foreign_key => 'participant_id' + + belongs_to :requester, + :class_name => 'User', + :foreign_key => 'participant_id' + belongs_to :event, :counter_cache => true belongs_to :inviter, :class_name => 'User', :foreign_key => 'inviter_id' end diff --git a/app/models/user.rb b/app/models/user.rb index 32c30c4..90fc068 100755 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,244 +1,252 @@ require 'digest/sha1' class User < ActiveRecord::Base has_many :visitor_records, :order => 'created_at DESC' belongs_to :city belongs_to :province belongs_to :country has_many :wall_messages, :dependent => :destroy, :finder_sql => 'select wall_messages.* from wall_messages where wall_messages.user_id = #{id} OR wall_messages.receiver_id = #{id} ORDER BY created_at DESC' has_many :sent_mails, :class_name => 'Mail', :foreign_key => 'sender_id', :conditions => { :delete_by_sender => false } has_many :recv_mails, :class_name => 'Mail', :foreign_key => 'receiver_id', :conditions => { :delete_by_receiver => false } def unread_recv_mails_count recv_mails.find_all { |m| !m.read_by_receiver? }.count end has_many :friendships, :dependent => :destroy has_many :friends, :class_name => 'User', :order => 'login ASC', :through => :friendships def has_friend(user) self.friends.include?(user) end has_many :game_characters, :dependent => :destroy has_many :currently_playing_game_characters, :class_name => 'GameCharacter', :conditions => { :playing => true }, :order => 'created_at DESC' has_many :games, :through => :game_characters, :uniq => true + has_many :participations, + :foreign_key => 'participant_id', + :dependent => :destroy + + has_many :events, + :through => :participations, + :uniq => true + has_many :icons, :class_name => 'Photo', :order => 'created_at DESC', :dependent => :destroy has_one :current_icon, :class_name => 'Photo', :order => 'created_at DESC', :conditions => {:current_icon => true} def next_prev_icon(cur_icon) size = self.icons.count next_icon_idx = 0 prev_icon_idx = 0 cur_icon_idx = 0 self.icons.each_with_index do |icon, i| if cur_icon == icon next_icon_idx = (i + 1) % size prev_icon_idx = (i - 1 + size) % size cur_icon_idx = i + 1 break end end [self.icons[next_icon_idx], self.icons[prev_icon_idx], cur_icon_idx] end def reset_icon(new_icon) old_icon = self.current_icon unless new_icon == old_icon old_icon.update_attribute(:current_icon, false) unless old_icon.blank? new_icon.current_icon = true new_icon.user_id = self.id end end has_many :statuses, :order => 'created_at DESC', :dependent => :destroy has_one :latest_status, :class_name => 'Status', :order => 'created_at DESC' has_many :blogs, :order => 'position DESC', :conditions => {:draft => false} has_many :bcomment_notifications, :order => 'created_at DESC' def can_view(blog) return true if blog.user == self case blog.privilege when 'all' return true when 'myself' return (blog.user == self) when 'only friends' return blog.user.has_friend(self) end end has_many :drafts, :class_name => 'Blog', :order => 'updated_at DESC', :conditions => {:draft => true} has_many :albums, :order => 'updated_at DESC' has_many :videos, :order => 'position DESC' # permissions and roles has_many :permissions has_many :roles, :through => :permissions # Virtual attribute for the unencrypted password attr_accessor :password, :password_confirmation # callbacks before_save :encrypt_password before_create :make_activation_code # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :gender, :password, :password_confirmation, :qq, :website, :mobile, :country, :city, :province, :birthday # Activates the user in the database. def activate @activated = true self.activated_at = Time.now.utc self.activation_code = nil save(false) end def active? # the existence of an activation code means they have not activated yet activation_code.nil? end # Authenticates a user by their login name and unencrypted password. Returns the user or nil. def self.authenticate(email, password) u = find :first, :conditions => ['email = ? and activated_at IS NOT NULL', email] u && u.authenticated?(password) ? u : nil end # Encrypts some data with the salt. def self.encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end # Encrypts the password with the user salt def encrypt(password) self.class.encrypt(password, salt) end def authenticated?(password) crypted_password == encrypt(password) end def remember_token? remember_token_expires_at && Time.now.utc < remember_token_expires_at end # These create and unset the fields required for remembering users between browser closes def remember_me remember_me_for 2.weeks end def remember_me_for(time) remember_me_until time.from_now.utc end def remember_me_until(time) self.remember_token_expires_at = time self.remember_token = encrypt("#{email}--#{remember_token_expires_at}") save(false) end def forget_me self.remember_token_expires_at = nil self.remember_token = nil save(false) end def forgot_password @forgotten_password = true self.make_password_reset_code end def reset_password update_attribute(:password_reset_code, nil) @reset_password = true end def has_role?(name) self.roles.find_by_name(name) ? true : false end # Returns true if the user has just been activated. def recently_activated? @activated end def recently_forgot_password? @forgotten_password end def recently_reset_password? @reset_password end protected def encrypt_password return if password.blank? self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record? self.crypted_password = encrypt(password) end def make_activation_code self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end def make_password_reset_code self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end end diff --git a/app/views/event/album/_edit_menu.html.erb b/app/views/event/album/_edit_menu.html.erb new file mode 100644 index 0000000..a594a4d --- /dev/null +++ b/app/views/event/album/_edit_menu.html.erb @@ -0,0 +1,5 @@ +<%= link_to "upload", new_event_photo_url(@event) %> | +<%= link_to "edit", edit_event_album_url(@event) %> | +<%= link_to "delete", confirm_destroy_event_album_url(@event), :method => 'get' %> | +<%= link_to "back to event", event_url(@event) %> + diff --git a/app/views/event/album/_photos.html.erb b/app/views/event/album/_photos.html.erb new file mode 100755 index 0000000..50f836f --- /dev/null +++ b/app/views/event/album/_photos.html.erb @@ -0,0 +1,4 @@ +<% photos.each do |photo| %> + <% image_divid = "photo_#{photo.id}" %> + <%= link_to (image_tag photo.public_filename(:medium), :onmouseover => "this.setStyle({ border: '5px grey solid'});", :onmouseout => "this.setStyle({ border: '5px white solid'});", :style => "border:5px white solid"), event_photo_url(@event, photo)%> +<% end %> diff --git a/app/views/event/album/confirm_destroy.html.erb b/app/views/event/album/confirm_destroy.html.erb new file mode 100755 index 0000000..f9ad715 --- /dev/null +++ b/app/views/event/album/confirm_destroy.html.erb @@ -0,0 +1,11 @@ +<p><%= "Edit album - #{@album.title}" %></p> +<p><%= render :partial => 'edit_menu' %></p> + +<p><%= "Are you sure to delete #{link_to @album.title, event_album_url(@event)}?" %></p> + +<p><%= event_album_cover(@event) %></p> +<% form_tag event_album_url(@event), :method => :delete do %> + <p>Validation code: <%= text_field_tag 'validation_text', '', :size => 4 %><%= submit_tag 'submit'%></p> + <p><%= validation_image %></p> +<% end %> + diff --git a/app/views/event/album/edit.html.erb b/app/views/event/album/edit.html.erb new file mode 100755 index 0000000..eaa2a69 --- /dev/null +++ b/app/views/event/album/edit.html.erb @@ -0,0 +1,22 @@ +<p><%= "Edit album - #{@album.title}" %></p> +<p><%= render :partial => 'edit_menu' %></p> + +<table cellpadding=10> +<% form_for :album, :url => event_album_url(@event, @album), :html => {:method => :put} do |form| %> + <tr> + <td><%= form.label 'title' %></td> + <td><%= form.text_field 'title' %></td> + </tr> + <tr vAlign='top'> + <td><%= form.label 'description' %></td> + <td><%= form.text_area 'description', :rows => 8, :cols => 60 %></td> + </tr> + <tr> + <td><%= form.label 'privilege' %></td> + <td><%= privilege_select_tag :album, @album.privilege %></td> + </tr> + <tr> + <td></td><td><%= form.submit 'update' %></td> + </tr> +<% end %> +</table> diff --git a/app/views/event/album/show.html.erb b/app/views/event/album/show.html.erb new file mode 100755 index 0000000..c7fe5b4 --- /dev/null +++ b/app/views/event/album/show.html.erb @@ -0,0 +1,20 @@ +<div class='show-header'> + <%= event_album_cover(@event) %> + <%= @album.title %><br/> + <%= link_to " back to event", event_url(@event) %> + <% if @user == current_user %> + <%= link_to "upload photo", new_event_photo_url(@event) %> + <% end %> +</div> + +<p> + <%= page_entries_info @photos, :entry_name => 'photo' %> | + <% if @user == current_user %> + <%= link_to 'edit album', edit_event_album_url(@event) %> | + <% end %> +</p> + +<div class='album'> + <%= render :partial => 'photos', :object => @photos %> + <%= will_paginate @photos %> +</div> diff --git a/app/views/event/photos/.edit.html.erb.swp b/app/views/event/photos/.edit.html.erb.swp new file mode 100644 index 0000000..b9400e1 Binary files /dev/null and b/app/views/event/photos/.edit.html.erb.swp differ diff --git a/app/views/event/photos/.new.html.erb.swp b/app/views/event/photos/.new.html.erb.swp new file mode 100644 index 0000000..e8f2a51 Binary files /dev/null and b/app/views/event/photos/.new.html.erb.swp differ diff --git a/app/views/event/photos/_edition.html.erb b/app/views/event/photos/_edition.html.erb new file mode 100755 index 0000000..3e7d478 --- /dev/null +++ b/app/views/event/photos/_edition.html.erb @@ -0,0 +1,15 @@ +<% photo = edition %> +<% fields_for 'photos[]', photo do |form| %> +<table> + <tr> + <td vAlign='top'><%= form.label 'notation:' %></td> + <td vAlign='top'><%= form.text_area 'notation', :rows => 5, :cols => 50 %></td> + <td vAlign='top'> + <%= image_tag photo.public_filename(:medium) %><br/> + <%= form.label 'cover: ' %> <%= form.radio_button 'cover', true %><br/> + <%= form.label 'move to: ' %> + <%= select_tag "photos[#{photo.id}][album_id]", options_from_collection_for_select(@user.albums, :id, :title, photo.album_id) %> <br/> + </td> + </tr> +</table> +<% end %> diff --git a/app/views/event/photos/_friends.html.erb b/app/views/event/photos/_friends.html.erb new file mode 100755 index 0000000..1edea3f --- /dev/null +++ b/app/views/event/photos/_friends.html.erb @@ -0,0 +1,5 @@ +<% friends.each do |f| %> + <div id=<%= f.id %> name=<%= f.login %>> + <%= check_box_tag '', f.id, false %><%= f.login %><br/> + </div> +<% end %> diff --git a/app/views/event/photos/_photo_menu.html.erb b/app/views/event/photos/_photo_menu.html.erb new file mode 100755 index 0000000..11e0264 --- /dev/null +++ b/app/views/event/photos/_photo_menu.html.erb @@ -0,0 +1,8 @@ +<ul id='photo_operations'> + <li> <%= link_to_function 'tag your friends', "photo_tag.init();" %> </li> + <% if @user == current_user %> + <li> <%= link_to_remote 'make it cover', :url => cover_event_photo_url(@event, @photo), :confirm => 'are you sure?', :method => :post %> </li> + <li> <%= link_to 'edit photo', edit_event_photo_url(@event, @photo) %> </li> + <li> <%= link_to 'delete photo', confirm_destroy_event_photo_url(@event, @photo), :rel => 'facebox' %> </li> + <% end %> +</ul> diff --git a/app/views/event/photos/_photo_upload_form.html.erb b/app/views/event/photos/_photo_upload_form.html.erb new file mode 100755 index 0000000..62f4382 --- /dev/null +++ b/app/views/event/photos/_photo_upload_form.html.erb @@ -0,0 +1,7 @@ +<% photo = photo_upload_form %> +<div class='photo'> +<% fields_for "photos[]", photo do |form| %> + <%= form.file_field :uploaded_data %> + <%= link_to_function "delete", "$(this).up('.photo').remove();" %> +<% end %> +</div> diff --git a/app/views/event/photos/confirm_cover.html.erb b/app/views/event/photos/confirm_cover.html.erb new file mode 100755 index 0000000..8b13789 --- /dev/null +++ b/app/views/event/photos/confirm_cover.html.erb @@ -0,0 +1 @@ + diff --git a/app/views/event/photos/confirm_destroy.html.erb b/app/views/event/photos/confirm_destroy.html.erb new file mode 100755 index 0000000..b01162e --- /dev/null +++ b/app/views/event/photos/confirm_destroy.html.erb @@ -0,0 +1,5 @@ +<p><%= "Are you sure to delete this photo?" %></p> +<% form_remote_tag :url => event_photo_url(@event, @photo), :method => :delete do %> + <p>Validation code: <%= text_field_tag 'validation_text', '', :size => 4 %><%= submit_tag 'submit'%></p> + <p><%= validation_image %></p> +<% end %> diff --git a/app/views/event/photos/edit.html.erb b/app/views/event/photos/edit.html.erb new file mode 100755 index 0000000..cbdb238 --- /dev/null +++ b/app/views/event/photos/edit.html.erb @@ -0,0 +1,19 @@ +<p><%= "edit album - #{@album.title}" %></p> +<p><%= link_to 'back to album', event_album_url(@event) %></p> + +<% form_for :photo, :url => event_photo_url(@event, @photo), :html => {:method => :put} do |form| %> + <table> + <tr> + <td vAlign='top'><%= form.label 'notation:' %></td> + <td vAlign='top'><%= form.text_area 'notation', :rows => 5, :cols => 50 %></td> + <td vAlign='top'> + <%= image_tag @photo.public_filename(:medium) %><br/> + <%= form.label 'cover: ' %> <%= form.radio_button 'cover', true, :checked => @photo.cover %><br/> + <%= form.label 'move to: ' %> + <%= select_tag "photo[album_id]", options_from_collection_for_select(@user.albums, :id, :title, @photo.album_id) %> <br/> + </td> + </tr> + </table> + <%= submit_tag 'update' %> +<% end %> + diff --git a/app/views/event/photos/edit_multiple.html.erb b/app/views/event/photos/edit_multiple.html.erb new file mode 100755 index 0000000..baa4f93 --- /dev/null +++ b/app/views/event/photos/edit_multiple.html.erb @@ -0,0 +1,9 @@ +<p><%= "edit album - #{@album.title}" %></p> +<p><%= link_to 'back to album', event_album_url(@event) %></p> + +<% form_tag update_multiple_event_photos_url(@event), :method => :put do %> + <div id='photo'> + <%= render :partial => 'edition', :collection => @photos %> + </div> + <%= submit_tag 'update' %> +<% end %> diff --git a/app/views/event/photos/new.html.erb b/app/views/event/photos/new.html.erb new file mode 100755 index 0000000..799d2f9 --- /dev/null +++ b/app/views/event/photos/new.html.erb @@ -0,0 +1,15 @@ +<p><%= "Edit album - #{@album.title}" %></p> +<p><%= render :partial => 'event/album/edit_menu' %></p> +<p><%= "Upload Photos: you can upload JPG, GIF, PNG or BMG formats" %></p> + +<% form_tag create_multiple_event_photos_url, :multipart => true do %> + <div id='photos'> + <% 1.upto(3) do %> + <%= render :partial => 'photo_upload_form', :object => Photo.new %> + <% end %> + </div> + <%= link_to_function 'add photo' do |page| + page.insert_html :bottom, :photos, :partial => 'photo_upload_form', :object => Photo.new + end %> + <%= submit_tag 'upload' %> +<% end %> diff --git a/app/views/event/photos/show.html.erb b/app/views/event/photos/show.html.erb new file mode 100755 index 0000000..1bc426f --- /dev/null +++ b/app/views/event/photos/show.html.erb @@ -0,0 +1,40 @@ +<%= javascript_include_tag 'photo.js' %> +<%= stylesheet_link_tag 'photo_tag.css' %> + +<p> + <%= "#{@album.photos.count - @photo.position + 1} of #{@album.photos.count} photos" %> | + <%= link_to "back to album", event_album_url(@event) %> | + <%= link_to "back to event", event_url(@event) %> +</p> + +<p> + <%= link_to 'prev', event_photo_url(@event, @photo.lower_item) %> | + <%= link_to 'next', event_photo_url(@event, @photo.higher_item) %> +</p> + +<div class='album-photo'> + <%= image_tag @photo.public_filename, :id => "photo_#{@photo.id}" %> + <div id='complete_panel' style="display:none"> + After you finish tagging, close this<%= button_to_function 'complete', "photo_tag.complete();" %> + </div> + <div class='notation'> + notation: <%= @photo.notation %> + </div> + <div class='tags' id='photo_tags'> + Tags: <%= render :partial => 'user/ptags/ptag', :collection => @photo.tags %> + </div> + <div class='operations'> + <%= link_to_function "Comment", "$('pcomment_content_#{@photo.id}').focus();" %>(<%= label_tag 'nil', "#{@photo.comments_count}", :id => 'comments_count' %>) | + <%= link_to_remote "Dig", :url => photo_digs_url( @photo) %>(<%= label_tag nil, "#{@photo.digs_count}", :id => 'digs_count' %>) + </div> +</div> + +<%= render :partial => 'photo_menu' %> + +<div id='pcomments_<%= @photo.id%>'> + <%= render :partial => 'user/pcomments/pcomment', :collection => @photo.comments %> +</div> + +<%= render :partial => 'user/pcomments/new', :locals => {:photo => @photo} %> + +<%= javascript_tag "var photo_tag = new PhotoTag(#{@photo.id}, #{current_user.id});" %> diff --git a/app/views/event_wall_messages/_event_wall_message.html.erb b/app/views/event/wall_messages/_event_wall_message.html.erb similarity index 92% rename from app/views/event_wall_messages/_event_wall_message.html.erb rename to app/views/event/wall_messages/_event_wall_message.html.erb index 0927524..a0cea06 100755 --- a/app/views/event_wall_messages/_event_wall_message.html.erb +++ b/app/views/event/wall_messages/_event_wall_message.html.erb @@ -1,14 +1,14 @@ <% message = event_wall_message %> <% wall_message_divid = "event_wall_message_#{message.id}" %> <div id=<%= wall_message_divid %>> <%= user_icon(message.poster) %> <%= link_to message.poster.login %> <%= ftime message.created_at %> <br/> <%= message.content %> <% if current_user == message.poster %> - <%= link_to_remote 'delete', :complete => "$('#{wall_message_divid}').remove();",:url => {:controller => 'event_wall_messages', :action => 'destroy', :id => message.id }, :confirm => 'are you sure' %> + <%= link_to_remote 'delete', :complete => "$('#{wall_message_divid}').remove();",:url => {:controller => 'event/wall_messages', :action => 'destroy', :id => message.id }, :confirm => 'are you sure' %> <% else %> <%= link_to_function 'comment', "$('event_wall_message_content').value='reply to #{message.poster.login}: ';$('event_wall_message_content').focus();$('event_wall_message_receiver_id').value=#{message.poster.id};$('event_wall_message_event_id').value=#{@event.id}" %> <% end %> </div> diff --git a/app/views/event_wall_messages/_input.html.erb b/app/views/event/wall_messages/_input.html.erb similarity index 88% rename from app/views/event_wall_messages/_input.html.erb rename to app/views/event/wall_messages/_input.html.erb index a26b58f..09d0d20 100755 --- a/app/views/event_wall_messages/_input.html.erb +++ b/app/views/event/wall_messages/_input.html.erb @@ -1,11 +1,11 @@ <% form_remote_for :event_wall_message, :position => :top, :update => 'event_wall_messages', :complete => "$('event_wall_message_content').value='';", - :url => {:controller => 'event_wall_messages', :action => 'create'} do |form| %> + :url => {:controller => 'event/wall_messages', :action => 'create'} do |form| %> <p style="display:none"><%= form.text_field 'event_id' %></p> <p style="display:none"><%= form.text_field 'receiver_id' %></p> <p><%= form.text_area 'content', :rows => 8, :cols => 80 %></p> <p><%= form.submit 'leave a message' %></p> <% end %> diff --git a/app/views/events/_area_select.html.erb b/app/views/events/_area_select.html.erb new file mode 100644 index 0000000..3576eca --- /dev/null +++ b/app/views/events/_area_select.html.erb @@ -0,0 +1,8 @@ +<% area_array = [['---','---']] %> +<% areas.each { |area| area_array << [area.name, area.id] } %> + +<div id='areas'> + <%= label_tag '', 'Game Area: '%> + <%= select_tag 'event[game_area_id]', options_for_select(area_array, area_id), :onchange => "validate_area_id(this.value);event_area_onchange(this.value)" %> + <a id='area_id_info'></a> +</div> diff --git a/app/views/events/_event_menu.html.erb b/app/views/events/_event_menu.html.erb new file mode 100644 index 0000000..fb6c513 --- /dev/null +++ b/app/views/events/_event_menu.html.erb @@ -0,0 +1,11 @@ +<ul> + <li><%= link_to "all up coming events", events_url(:term => 'up_coming') %></li> + <ul> + <div id="game_list"> + <% @user.games.each do |game| %> + <li><%= link_to game.name, events_url(@user, :term => 'game', :game_id => game) %></li> + <% end %> + </div> + </ul> + <li><%= link_to "my events", events_url(:term => 'mine') %></li> +</ul> diff --git a/app/views/events/_events.html.erb b/app/views/events/_events.html.erb new file mode 100644 index 0000000..f55e682 --- /dev/null +++ b/app/views/events/_events.html.erb @@ -0,0 +1,16 @@ +<% if events.blank? %> + no events is found. +<% else %> + <% events.each do |event| %> + <% event_divid = "event_#{event.id}" %> + <div id=<%= event_divid %>> + <%= event_album_cover(event) %> + <%= link_to event.title, event_url(event)%> + </div> + <% end %> + <% if @remote %> + <%= will_paginate events, :renderer => 'RemoteLinkRenderer', :remote => @remote %> + <% else %> + <%= will_paginate events %> + <% end %> +<% end %> diff --git a/app/views/events/_game_details.html.erb b/app/views/events/_game_details.html.erb new file mode 100644 index 0000000..eb08399 --- /dev/null +++ b/app/views/events/_game_details.html.erb @@ -0,0 +1,4 @@ +<% unless @game.no_areas %> + <%= render :partial => 'area_select', :locals => {:areas => @areas, :area_id => nil} %> +<% end %> +<%= render :partial => 'server_select', :locals => {:servers => @servers, :server_id => nil} %> diff --git a/app/views/events/_invited_lists.html.erb b/app/views/events/_invited_lists.html.erb new file mode 100644 index 0000000..373c12c --- /dev/null +++ b/app/views/events/_invited_lists.html.erb @@ -0,0 +1,22 @@ +<div class='invited_list'> + <table id='friend_table'> + <% i=0 %> + <% invited_lists.each do |person| %> + <% if i == 0 %> + <tr> + <% end %> + <td class='record'> + <%= user_icon person, :small %><br/> + <%= link_to_user person %> + </td> + <% i = i + 1 %> + <% if i == 3 %> + </tr> + <% i = 0 %> + <% end %> + <% end unless invited_lists.blank?%> + </table> + <div class='view-all'> + <%= link_to 'More...', "/participations?event_id=#{@event.id}&type=#{type}" %> + </div> +</div> diff --git a/app/views/events/_messages.html.erb b/app/views/events/_messages.html.erb index 09eb5bf..7953f56 100644 --- a/app/views/events/_messages.html.erb +++ b/app/views/events/_messages.html.erb @@ -1,5 +1,5 @@ Wall: -<%= render :partial => 'event_wall_messages/input' %> +<%= render :partial => 'event/wall_messages/input' %> <div id='event_wall_messages'> -<%= render :partial => 'event_wall_messages/event_wall_message', :collection => @event_wall_messages %> +<%= render :partial => 'event/wall_messages/event_wall_message', :collection => @event_wall_messages %> </div> diff --git a/app/views/events/_server_select.html.erb b/app/views/events/_server_select.html.erb new file mode 100644 index 0000000..45114a2 --- /dev/null +++ b/app/views/events/_server_select.html.erb @@ -0,0 +1,8 @@ +<% server_array = [['---', '---']] %> +<% servers.each { |server| server_array << [server.name, server.id] } %> +<div id='servers'> + <%= label_tag '', 'Game Server: '%> + <%= select_tag 'event[game_server_id]', options_for_select(server_array, server_id), :onchange => "validate_server_id(this.value)"%> + <a id='server_id_info'></a> +</div> + diff --git a/app/views/events/confirm_destroy.html.erb b/app/views/events/confirm_destroy.html.erb new file mode 100644 index 0000000..cd7174d --- /dev/null +++ b/app/views/events/confirm_destroy.html.erb @@ -0,0 +1,5 @@ +<p><%= "Are you sure to delete this event?" %></p> +<% form_remote_tag :url => event_url(@event), :method => :delete do %> + <p>Validation code: <%= text_field_tag 'validation_text', '', :size => 4 %><%= submit_tag 'submit'%></p> + <p><%= validation_image %></p> +<% end %> diff --git a/app/views/events/index.html.erb b/app/views/events/index.html.erb new file mode 100644 index 0000000..ecccd48 --- /dev/null +++ b/app/views/events/index.html.erb @@ -0,0 +1,9 @@ +<% content_for :left do %> + <%= render :partial => 'event_menu' %> +<% end %> +<% content_for :right do%> + <%= link_to 'create an event', new_event_url %> +<% end %> +<div id='events'> + <%= render :partial => 'events', :object => @events %> +</div> diff --git a/app/views/events/new.html.erb b/app/views/events/new.html.erb index fac7bc0..52a63cd 100644 --- a/app/views/events/new.html.erb +++ b/app/views/events/new.html.erb @@ -1,26 +1,26 @@ <% form_for @event, events_path do |f| %> <div> <%= f.label "title:" %><br/> <%= f.text_field :title %> </div> <div> <%= f.label "game:" %> -<%= collection_select :event, :game_id, @games, :id, :name, {:prompt => '---'}, {:onchange => "validate_game_id(this.value);game_onchange_event(this.value)"} %> +<%= collection_select :event, :game_id, @games, :id, :name, {:prompt => '---'}, {:onchange => "validate_game_id(this.value);event_game_onchange(this.value)"} %> <a id='game_id_info'></a> </div> <div id=game_details></div> <div> <%= f.label "starting Date and Time" %> <%= datetime_select :event, :time %> <a id='event_time_form'></a> </div> <div> <%= f.label "description:" %><br/> <%= f.text_area :description %> <a id='event_description_form'></a> </div> <div> <%= f.submit "Next Step" %> <a id='event_submit'></a> </div> <% end %> diff --git a/app/views/events/show.html.erb b/app/views/events/show.html.erb index e997d40..4c94e57 100644 --- a/app/views/events/show.html.erb +++ b/app/views/events/show.html.erb @@ -1,13 +1,24 @@ <p><%= album_cover(@album) %> </p> <p>Title:<%= @event.title %></p> <p>Organizer: <%= @user.login %></p> <p>Starting Time: <%= @event.time %></p> <p>Game: <%= @game.name %></p> <% unless @game_area.nil? %> <p>Area: <%= @game_area.name %></p> <% end %> <p>Server:<%= @game_server.name %></p> <p>Description: <%= @event.description %></p> -<p><%= link_to "upload photos", new_album_photo_url(@album) %></p> -<p><%= render :partial => 'user_albums/photos', :object => @photos %></p> +<p><%= link_to "delete this event", confirm_destroy_event_url(@event), :rel => 'facebox' %></p> +<p><%= link_to "upload photos", new_event_photo_url(@event) %></p> +<p><%= render :partial => 'user/albums/photos', :object => @photos %></p> +<p><%= link_to "More...", event_album_url(@event) %></p> +<p><%= link_to "invite more people", new_participation_url(:event_id => @event.id) %></p> +invited: +<p><%= render :partial => 'invited_lists', :object => @event.invitees[0..2], :locals => {:type => 1} %></p> +Not attend: +<p><%= render :partial => 'invited_lists', :object => @event.refusers[0..2], :locals => {:type => 2}%></p> +Maybe attend: +<p><%= render :partial => 'invited_lists', :object => @event.maybe_attenders[0..2], :locals => {:type => 3}%></p> +will attend: +<p><%= render :partial => 'invited_lists', :object => @event.must_attenders[0..2], :locals => {:type => 4}%></p> <%= render :partial => 'messages' %> diff --git a/app/views/layouts/_user_menus.html.erb b/app/views/layouts/_user_menus.html.erb index 109c059..aa4a4a9 100755 --- a/app/views/layouts/_user_menus.html.erb +++ b/app/views/layouts/_user_menus.html.erb @@ -1,9 +1,10 @@ <div align='center' class='fb2'> <%= link_to 'Home page', user_resource_feeds_url(current_user) %> <%= link_to 'Personal Page', user_personal_url(current_user) %> <%= link_to 'friends', user_friends_url(current_user, :term => 'name') %> +<%= link_to 'events', events_url(:term => 'up_coming') %> <%= link_to 'group/guild' %> <%= link_to 'mailbox', user_mails_url(current_user, :type => 'recv') %> <%= link_to 'settings' %> <%= link_to 'logout', session_url(:id => 1), :method => :delete %> </div> diff --git a/app/views/participations/_friends_list.html.erb b/app/views/participations/_friends_list.html.erb index 2793903..6ecb431 100755 --- a/app/views/participations/_friends_list.html.erb +++ b/app/views/participations/_friends_list.html.erb @@ -1,12 +1,13 @@ +<p><%= select_tag 'select', options_for_select([['---', '^_^'], ['all','all'],['none', 'none']], "---"), :onchange => "participation_builder.select_dropdown_onchange(this.value)" %></p> <% i = 0 %> <table cellpadding='5px'> <% friends_list.each do |f| %> <% "<tr>" if i == 0 %> <td width='100px'> <%= check_box_tag '', f.id, false %> <%= f.login %> <%= user_icon(f) %></td> <% i = i + 1 %> <% if i == 3 %> </tr> <% i = 0 %> <% end %> <% end %> </table> diff --git a/app/views/participations/_participation.html.erb b/app/views/participations/_participation.html.erb index c923ce0..19ce00a 100644 --- a/app/views/participations/_participation.html.erb +++ b/app/views/participations/_participation.html.erb @@ -1,4 +1,4 @@ <div new_record=<%= participation.new_record?%> participant_id=<%= participation.participant_id %> participation_id=<%= participation.new_record? ? 0: participation.id %>> - <p><%= user_icon(participation.participant) %></p> - <p><%= link_to_user participation.participant %> | <%= link_to_function 'delete', "participation_builder.remove_participation(#{participation.participant_id})" %></p> + <p><%= user_icon(participation.invitee) %></p> + <p><%= link_to_user participation.invitee %> | <%= link_to_function 'delete', "participation_builder.remove_participation(#{participation.participant_id})" %></p> </div> diff --git a/app/views/participations/_people_participations.html.erb b/app/views/participations/_people_participations.html.erb new file mode 100755 index 0000000..c8d5783 --- /dev/null +++ b/app/views/participations/_people_participations.html.erb @@ -0,0 +1,17 @@ +<% if people_participations.blank? %> + no one is on this list +<% else %> + <% people_participations.each do |participation| %> + <% participation_divid = "participation_#{participation.id}" %> + <div id=<%= participation_divid %>> + <%= user_icon(participation.participant) %> + <%= link_to_user participation.participant%> + <%= link_to_remote 'delete', :complete => "$('#{participation_divid}').remove()", :url => participation_url(participation), :method => :delete %> + </div> + <% end %> + <% if @remote %> + <%= will_paginate people_participations, :renderer => 'RemoteLinkRenderer', :remote => @remote %> + <% else %> + <%= will_paginate people_participations %> + <% end %> +<% end %> diff --git a/app/views/participations/index.html.erb b/app/views/participations/index.html.erb new file mode 100644 index 0000000..bf25292 --- /dev/null +++ b/app/views/participations/index.html.erb @@ -0,0 +1,4 @@ +<%= link_to 'back to event', event_path(@event) %> +<div id='participants'> + <%= render :partial => 'people_participations', :object => @people_participations %> +</div> diff --git a/app/views/user/characters/_game_select.html.erb b/app/views/user/characters/_game_select.html.erb index 5d05199..be0e0bf 100644 --- a/app/views/user/characters/_game_select.html.erb +++ b/app/views/user/characters/_game_select.html.erb @@ -1,5 +1,5 @@ <% game_array = [['---', '---']] %> <% games.each { |game| game_array << [game.name, game.id] } %> <%= label_tag 'game_id', "Game Name: "%> -<%= select_tag 'character[game_id]', options_for_select(game_array, game_id), :onchange => "validate_game_id(this.value);game_onchange(this.value)"%> +<%= select_tag 'character[game_id]', options_for_select(game_array, game_id), :onchange => "validate_game_id(this.value);game_onchange_event(this.value)"%> <a id='game_id_info'></a><br/> diff --git a/app/views/user/home/_friend_suggestions.html.erb b/app/views/user/home/_friend_suggestions.html.erb index 2691100..20530c4 100644 --- a/app/views/user/home/_friend_suggestions.html.erb +++ b/app/views/user/home/_friend_suggestions.html.erb @@ -1,24 +1,23 @@ <div class='visitors'> <h3>You might know: <%= link_to_function 'fold', "$('friend_table').toggle();if(this.innerHTML == 'fold') this.update('unfold'); else this.update('fold');", :class => 'hide-all'%></h3> <table id='friend_table'> <% i=0 %> <% friends.each do |friend| %> <% if i == 0 %> <tr> <% end %> <td class='record'> <%= user_icon friend, :small %><br/> <%= link_to_user friend %> </td> <% i = i + 1 %> <% if i == 3 %> </tr> <% i = 0 %> <% end %> <% end unless friends.blank?%> </table> <div class='view-all'> <%= link_to 'More...' %> </div> </div> - diff --git a/config/routes.rb b/config/routes.rb index 8107f6f..de4ca9a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,212 +1,224 @@ ActionController::Routing::Routes.draw do |map| - map.resources :events + map.resources :events, :member =>{:confirm_destroy => :get}, :collection => {:game_details => :get, :area_details => :get} do |events| + events.resource :album, + :controller => 'event/album', + :member => {:confirm_destroy => :get} + + events.resources :photos, + :controller => 'event/photos', + :member => {:confirm_destroy => :get, :cover => :post}, + :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} + + events.resources :wall_messages, + :controller => 'event/wall_messages' + end map.resources :participations, :collection => {:new_participation => :get, :friends_list => :get} map.resources :sessions map.root :controller => 'sessions', :action => 'new' map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate' map.forgot_password '/forgot_password', :controller => 'passwords', :action => 'new' map.reset_password '/reset_password/:password_reset_code', :controller => 'passwords', :action => 'edit' map.change_password '/change_password', :controller => 'accounts', :action => 'edit' map.upload_image '/upload_images', :controller => 'user/blog_images', :action => 'upload' map.namespace(:admin) do |admin| admin.resources :videos admin.resources :vtags admin.resources :vdigs admin.resources :vcomments admin.resources :blogs admin.resources :btags admin.resources :bdigs admin.resources :bcomments admin.resources :albums admin.resources :photos admin.resources :ptags admin.resources :pdigs admin.resources :pcomments admin.resources :pages admin.resources :statuses admin.resources :scomments admin.resources :wall_messages admin.resources :mails admin.resources :friendships admin.resources :game_characters admin.resources :game_races admin.resources :game_professions admin.resources :game_servers admin.resources :game_areas admin.resources :games end map.resources :users, :member => {:enable => :put} do |users| users.resource :personal, :controller => 'user/personal' users.resource :profile, :controller => 'user/profile' users.resource :basic_info, :controller => 'user/basic_info' users.resource :contact_info, :controller => 'user/contact_info' users.resources :icons, :controller => 'user/icons', :member => {:confirm_destroy => :get, :set => :post} users.resources :characters, :controller => 'user/characters', :member => {:confirm_destroy => :get} users.resources :wall_messages, :controller => 'user/wall_messages' users.resources :mails, :controller => 'user/mailboxes', :member => {:reply => :post}, :collection => {:read_multiple => :put, :unread_multiple => :put, :destroy_multiple => :delete} users.resources :friends, :controller => 'user/friends', :collection => {:search => :get} users.resources :visitor_records, :controller => 'user/visitor_records' users.resources :statuses, :controller => 'user/statuses' users.resources :status_feeds, :controller => 'user/status_feeds', :collection => {:get => :get} users.resources :blogs, :controller => 'user/blogs', :member => {:confirm_destroy => :get}, :collection => {:destroy_multiple => :delete} users.resources :blog_feeds, :controller => 'user/blog_feeds', :collection => {:get => :get} users.resources :tagged_blogs, :controller => 'user/tagged_blogs' users.resources :albums, :controller => 'user/albums', :member => {:confirm_destroy => :get} users.resources :album_feeds, :controller => 'user/album_feeds', :collection => {:get => :get} users.resources :tagged_photos, :controller => 'user/tagged_photos' users.resources :videos, :controller => 'user/videos', :member => {:confirm_destroy => :get} users.resources :video_feeds, :controller => 'user/video_feeds', :collection => {:get => :get} users.resources :tagged_videos, :controller => 'user/tagged_videos' users.resources :resource_feeds, :controller => 'user/resource_feeds', :collection => {:get => :get} end map.resources :statuses do |statuses| statuses.resources :comments, :controller => 'user/scomments' end map.resources :blogs do |blogs| blogs.resources :comments, :controller => 'user/bcomments' blogs.resources :tags, :controller => 'user/btags' blogs.resources :digs, :controller => 'user/bdigs' end map.resources :photos do |photos| photos.resources :comments, :controller => 'user/pcomments' photos.resources :tags, :controller => 'user/ptags' photos.resources :digs, :controller => 'user/pdigs' end map.resources :albums do |albums| albums.resources :photos, :controller => 'user/photos', :member => {:confirm_destroy => :get, :cover => :post}, :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} end map.resources :videos do |videos| videos.resources :comments, :controller => 'user/vcomments' videos.resources :tags, :controller => 'user/vtags' videos.resources :digs, :controller => 'user/vdigs' end map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090818062911_create_participations.rb b/db/migrate/20090818062911_create_participations.rb index 74f39dd..57ce8fe 100644 --- a/db/migrate/20090818062911_create_participations.rb +++ b/db/migrate/20090818062911_create_participations.rb @@ -1,15 +1,15 @@ class CreateParticipations < ActiveRecord::Migration def self.up create_table :participations do |t| t.integer :inviter_id t.integer :participant_id t.integer :event_id - t.integer :event_status, :default => 1 + t.integer :event_status t.timestamps end end def self.down drop_table :participations end end diff --git a/db/schema.rb b/db/schema.rb index 72a6812..3fa0d77 100755 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,392 +1,392 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20090826033843) do create_table "admin_pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "albums", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "photos_count", :default => 0 t.string "title" t.text "description" t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomment_notifications", :force => true do |t| t.integer "user_id" t.integer "commentor_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomments", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "bdigs", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "blogs", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title", :limit => 64 t.text "content", :limit => 16777215 t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.boolean "draft", :default => true t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "btags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "cities", :force => true do |t| t.string "name" t.integer "city_id" t.datetime "created_at" t.datetime "updated_at" end create_table "countries", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "event_wall_messages", :force => true do |t| t.integer "event_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.datetime "created_at" t.datetime "updated_at" end create_table "events", :force => true do |t| t.string "title" t.integer "poster_id" t.integer "game_id" t.integer "game_server_id" t.integer "game_area_id" t.integer "album_id" t.integer "participations_count", :default => 0 t.datetime "time" t.text "description" t.datetime "created_at" t.datetime "updated_at" end create_table "friendships", :force => true do |t| t.integer "user_id" t.integer "friend_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_areas", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_characters", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "server_id" t.integer "area_id" t.integer "profession_id" t.integer "race_id" t.string "name" t.integer "level" t.boolean "playing" t.datetime "created_at" t.datetime "updated_at" end create_table "game_professions", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_races", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_servers", :force => true do |t| t.string "name" t.string "ip" t.integer "game_id" t.integer "area_id" t.datetime "created_at" t.datetime "updated_at" end create_table "games", :force => true do |t| t.string "name" t.string "company" t.datetime "sale_date" t.text "description" t.boolean "no_areas", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "icons", :force => true do |t| t.integer "user_id" t.boolean "current" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "mails", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.boolean "delete_by_sender", :default => false t.boolean "delete_by_receiver", :default => false t.boolean "read_by_sender", :default => true t.boolean "read_by_receiver", :default => false t.string "title" t.text "content" t.integer "parent_id" t.datetime "created_at" t.datetime "updated_at" end create_table "pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "participations", :force => true do |t| t.integer "inviter_id" t.integer "participant_id" t.integer "event_id" - t.integer "event_status", :default => 1 + t.integer "event_status" t.datetime "created_at" t.datetime "updated_at" end create_table "pcomments", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "pdigs", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.datetime "created_at" t.datetime "updated_at" end create_table "permissions", :force => true do |t| t.string "user_id" t.string "role_id" t.datetime "created_at" t.datetime "updated_at" end create_table "photos", :force => true do |t| t.integer "digs_count", :default => 0 t.integer "tags_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "album_id" t.boolean "cover", :default => false t.integer "user_id" t.boolean "current_icon", :default => false t.text "notation" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "provinces", :force => true do |t| t.string "name" t.integer "country_id" t.datetime "created_at" t.datetime "updated_at" end create_table "ptags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "photo_id" t.integer "x" t.integer "y" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "roles", :force => true do |t| t.string "name", :null => false t.datetime "created_at" t.datetime "updated_at" end create_table "scomments", :force => true do |t| t.integer "user_id" t.integer "status_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "statuses", :force => true do |t| t.integer "user_id" t.text "content" t.integer "comments_count", :default => 0 t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :limit => 64 t.string "email", :limit => 128 t.string "crypted_password", :limit => 64 t.string "salt", :limit => 40 t.string "gender" t.boolean "enabled", :default => true t.string "remember_token" t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "password_reset_code", :limit => 40 t.integer "country_id" t.integer "province_id" t.integer "city_id" t.integer "qq" t.integer "mobile" t.string "website" t.datetime "birthday" t.datetime "created_at" t.datetime "updated_at" end create_table "vcomments", :force => true do |t| t.integer "user_id" t.integer "video_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "vdigs", :force => true do |t| t.integer "user_id" t.integer "video_id" t.datetime "created_at" t.datetime "updated_at" end create_table "videos", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title" t.string "url" t.text "link" t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "visitor_records", :force => true do |t| t.integer "user_id" t.integer "visitor_id" t.boolean "register", :default => true t.datetime "created_at" t.datetime "updated_at" end create_table "vtags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "video_id" t.datetime "created_at" t.datetime "updated_at" end create_table "wall_messages", :force => true do |t| t.integer "user_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end end diff --git a/public/javascripts/participation.js b/public/javascripts/participation.js index c0ab995..75017b8 100644 --- a/public/javascripts/participation.js +++ b/public/javascripts/participation.js @@ -1,123 +1,150 @@ function after_select(input_field, selected_li){ participation_builder.new_participation(selected_li.readAttribute('user_id')); $('event_participations').value = ''; } ParticipationBuilder = Class.create({ initialize: function(user_id, event_id){ this.user_id = user_id; this.event_id = event_id; this.participation_input = $('event_participations'); this.participation_input.value = 'please tag your friend here'; this.participation_input.observe('focus', function(event){ this.value = ''; }); this.participation_input.observe('blur', function(event){ this.value = 'please tag your friends here'; }); this.participations_div = $('participations'); this.friends_list=$('friends'); this.participations = new Hash(); var current_participations = this.participations_div.childElements(); for(var i=0;i<current_participations.length;i++){ this.participations.set(current_participations[i].readAttribute('participant_id'), current_participations[i]); } }, after_select: function(input_field, selected_li){ this.new_participation(selected_li.readAttribute('user_id')); $('event_participations').value = ''; }, new_participation: function(participant_id){ // if this user is already in participation list, skip it if(this.participations.get(participant_id)) return; // send ajax request to retrieve user information(icon, name ... so on) new Ajax.Request('/participations/new_participation?participants[]=' + participant_id, { method: 'get', onSuccess: function(transport){ this.participations_div.innerHTML = transport.responseText + this.participations_div.innerHTML; this.participation_input.value = ''; var children = this.participations_div.childElements(); var length = children.length; for(var i=0;i<length;i++){ this.participations.set(children[i].readAttribute('participant_id'), children[i]); } }.bind(this) }); }, remove_participation: function(participant_id){ var participation = this.participations.unset(participant_id); if(!participation) return; // if it's not a new record, it means it stores in database, // then do an ajax request to remove it from database if(participation.readAttribute('new_record') != 'true') new Ajax.Request('/participations/' + participation.readAttribute('participation_id'), {method: 'delete'}); participation.remove(); }, game_select: function(game_id){ new Ajax.Request('/participations/friends_list?game_id=' + game_id, { method: 'get', onSuccess: function(transport){ this.friends_list.innerHTML = transport.responseText; }.bind(this) }); }, + uncheck_all_checkboxes: function(){ + var inputs = $$('input'); + for(var i=0;i<inputs.length;i++){ + if(inputs[i].type == 'checkbox'){ + inputs[i].checked = false; + } + } + }, + + select_all_checkboxes: function(){ + var inputs = $$('input'); + for(var i=0;i<inputs.length;i++){ + if(inputs[i].type == 'checkbox'){ + inputs[i].checked = true; + } + } + }, + + select_dropdown_onchange: function(selector) { + + this.uncheck_all_checkboxes(); + + if(selector == 'all'){ + this.select_all_checkboxes(); + } + }, + get_selected_users: function(){ var inputs = $$('input'); var length = inputs.length; var selected_users = []; for(var i = 0; i < length; i++){ if(inputs[i].type == 'checkbox' && inputs[i].checked && !this.participations.get(inputs[i].value)){ selected_users.push(inputs[i].value); } } return selected_users; }, confirm_event: function(){ var selected_users = this.get_selected_users(); if (selected_users.length != 0 ){ var url = '/participations/new_participation?'; for(var i=0;i<selected_users.length;i++){ url += "participants[]=" + selected_users[i] + "&"; } new Ajax.Request(url, { method: 'get', onSuccess: function(transport){ this.participations_div.innerHTML = transport.responseText + this.participations_div.innerHTML; var children = this.participations_div.childElements(); var length = children.length; for(var i=0;i<length;i++){ this.participations.set(children[i].readAttribute('participant_id'), children[i]); } }.bind(this) }); } }, save: function(event_id){ // construct url // appending participant inputs var url = '/participations?event_id='+event_id+'&'; this.participations.each(function(pair){ if(pair.value.readAttribute('new_record') == 'true') url += "participants[]=" + pair.key + "&"; }); // send ajax request new Ajax.Request(url, {method: 'post'}); }, }); diff --git a/public/javascripts/validator.js b/public/javascripts/validator.js index 932ed30..db78a81 100755 --- a/public/javascripts/validator.js +++ b/public/javascripts/validator.js @@ -1,539 +1,546 @@ function show_qq_requirement(){ $('qq_info').innerHTML = '<span style="color:grey">input your real qq</span>'; } function validate_qq(qq){ var info = $('qq_info'); if(qq == '') return true; //qq is not mandatory if(qq.length < 6 || qq.length > 11){ info.innerHTML = '<span style="color: red">this qq number is not valid</span>'; return false; } if(parseInt(qq)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits are allowed here</span>'; return false; } } function show_webiste_requirement(){ $('website_info').innerHTML = '<span style="color:grey">input your personal website</span>'; } function validate_website(website){ var info = $('website_info'); info.innerHTML = '<span style="color: green">valid</span>'; return true; } function show_mobile_requirement(){ $('mobile_info').innerHTML = '<span style="color:grey">input your mobile number</span>'; } function validate_mobile(mobile){ var info = $('mobile_info'); if(mobile == '') return true; //qq is not mandatory if(mobile.length != 11){ info.innerHTML = '<span style="color: red">this mobile phone number is not valid</span>'; return false; } if(parseInt(mobile)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits are allowed here</span>'; return false; } } function validate_contact_info(){ var error = false; var qq = $('user_qq').value; var mobile = $('user_mobile').value; var website = $('user_website').value; if(!validate_qq(qq)) error = true; if(!validate_mobile(mobile)) error = true; if(!validate_website(website)) error = true; return error; } function update_contact_info(user_id){ if(validate_contact_info()) return; var form = $('contact_form'); var url = '/users/' + user_id + '/contact_info?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function validate_basic_info(){ var error = false; var login = $('user_login').value; if(!validate_login(login)) error = true; return error; } function update_basic_info(user_id){ if(validate_basic_info()) return; var form = $('basic_form'); var url = '/users/' + user_id + '/basic_info?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function show_login_requirement(){ $('login_info').setStyle({color: 'grey'}); $('login_info').innerHTML = 'only digits, letters and underscore are allowed, range 4..16'; } function validate_login(name){ var info = $('login_info'); // check presence if(name == ''){ info.innerHTML = '<span style="color: red">login cannot be blank</span>'; return false; } // check length if(name.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(name.length > 16){ info.innerHTML = '<span style="color: red">too long, at most 16 characters</span>'; return false; } // check pattern first = name[0]; if((first >= 'a' && first <= 'z') || (first >= 'A' && first <= 'Z')){ if(name.match(/[A-Za-z0-9\_]+/)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits, letters and underscore are allowed</span>'; return false; } }else{ info.innerHTML = '<span style="color: red">must start with A-Z or a-z</span>'; return false; } } function show_email_requirement(){ $('email_info').setStyle({color: 'grey'}); $('email_info').innerHTML = 'please input valid email box' } function validate_email(email){ var info = $('email_info'); // check presence if(email == ''){ info.innerHTML = '<span style="color: red">email cannot be blank</span>'; return false; } // check length if(email.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(email.length > 100){ info.innerHTML = '<span style="color: red">too long, at most 100 characters</span>'; return false; } // check pattern if(email.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)){ // send ajax request to check uniqueness new Ajax.Request('/validator/validates_email_uniqueness?email='+email, { method: 'get', onSuccess: function(transport){ var info = $('email_info'); if(transport.responseText == 'yes'){ info.innerHTML = '<span style="color: green">valid</span>'; }else{ info.innerHTML = '<span style="color: red">this email has already been occupied</span>'; } } }); return true; }else{ info.innerHTML = '<span style="color: red">invalid email format</span>'; return false; } } function show_password_requirement(){ $('password_info').setStyle({color: 'grey'}); $('password_info').innerHTML = 'password consists of 6-20 characters' } function validate_password(password){ var info = $('password_info') var strongReg = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g"); var mediumReg = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g"); // check length if(password.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(password.length > 20){ info.innerHTML = '<span style="color: red">too long, at most 20 characters</span>'; return false; } // check strength if(password.match(strongReg)){ info.innerHTML = '<span style="color: green">Valid: Strong Strength!</span>'; return true; }else if(password.match(mediumReg)){ info.innerHTML = '<span style="color: orange">Valid: Medium Strength!</span>'; return true; }else{ info.innerHTML = '<span style="color: red"> Valid: Weak Strength!</span>'; return true; } } function show_password_confirm_requirement(){ $('password_confirmation_info').setStyle({color: 'grey'}); $('password_confirmation_info').innerHTML = 'confirm your password' } function validate_password_confirmation(password_confirmation){ var info = $('password_confirmation_info'); var password = $('user_password').value; if(password == ''){ info.innerHTML = '<span style="color: red"> password cannot be blank </span>'; return false; } if(password == password_confirmation){ info.innerHTML = '<span style="color: green">Valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">Two passwords are not consistent</span>'; return false; } } function validate_register_info(){ var error = false; var login = $('user_login').value; var email = $('user_email').value; var password = $('user_password').value; var password_confirmation = $('user_password_confirmation').value; if(!validate_login(login)) error = true; if(!validate_email(email)) error = true; if(!validate_password(password)) error = true; if(!validate_password_confirmation(password_confirmation)) error = true; var form = $('register_form'); var cs = $('characters').childElements(); var length = cs.length; if(length == 0){ $('character_info').innerHTML = '<span style="color:red">You must specify at least one game character</span>' error = true; } return error; } function validate_game_id(game_id){ var info = $('game_id_info'); if(game_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> game cannot be blank </span>'; return false; } } -function game_onchange(game_id){ - if(game_id == '---'){ - $('details').innerHTML = ''; +function event_game_onchange(game_id){ + if(game_id == ''){ + $('game_details').innerHTML = ''; }else{ -<<<<<<< HEAD:public/javascripts/validator.js - new Ajax.Updater('details', '/games/' + game_id + '?show=1', {method: 'get'}); + new Ajax.Updater('game_details', '/events/game_details?game_id=' + game_id, {method: 'get'}); } } function game_onchange_event(game_id){ if(game_id == '---'){ - $('game_details').innerHTML = ''; + $('details').innerHTML = ''; }else{ new Ajax.Updater('details', '/register/game_details?game_id=' + game_id, {method: 'get'}); } } function show_name_requirement(){ var info = $('name_info'); info.innerHTML = '<span style="color: grey"> Input your character name </span>'; } function validate_name(name){ var info = $('name_info'); if(name == ''){ info.innerHTML = '<span style="color: red"> name cannot be blank </span>'; return false; }else{ info.innerHTML = '<span style="color: green"> valid </span>'; return true; } } function show_level_requirement(){ var info = $('level_info'); info.innerHTML = '<span style="color: grey"> Input your character level </span>'; } function validate_level(level){ var info = $('level_info'); if(level == ''){ info.innerHTML = '<span style="color: red"> level cannot be blank </span>'; return false; }else{ if(parseInt(level)){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> level should be an integer </span>'; return false; } } } function validate_server_id(server_id){ var info = $('server_id_info'); if(server_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> server cannot be blank </span>'; return false; } } function validate_area_id(area_id){ var info = $('area_id_info'); if(area_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> area cannot be blank </span>'; return false; } } -function area_onchange(area_id,showValue){ +function area_onchange(area_id){ if(area_id == '---'){ $('servers').innerHTML = '<label style="width:125px;float:left">Game Server:</label><select id="server_id" name="server_id"><option value="---">---</option></select>'; }else{ new Ajax.Updater('servers', '/register/area_details?area_id=' + area_id, {method: 'get'}); } } +function event_area_onchange(area_id){ + if(area_id == ''){ + $('servers').innerHTML = '<label style="width:125px;float:left">Game Server:</label><select id="server_id" name="server_id"><option value="---">---</option></select>'; + }else{ + new Ajax.Updater('servers', '/events/area_details?area_id=' + area_id, {method: 'get'}); + } +} + function validate_race_id(race_id){ var info = $('race_id_info'); if(race_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> race cannot be blank </span>'; return false; } } function validate_profession_id(profession_id){ var info = $('profession_id_info'); if(profession_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> profession cannot be blank </span>'; return false; } } var nr=0; function validate_game_character(){ // check all parameters var error = false; var game_id = $('character_game_id').value; var name = $('character_name').value; var level = $('character_level').value; if(!validate_name(name)) error = true; if(!validate_level(level)) error = true; if(!validate_game_id(game_id)) error = true; if(game_id == '---') return true; var server_id = $('character_server_id').value; var race_id = $('character_race_id').value; var profession_id = $('character_profession_id').value; var area_id = null; if(!validate_server_id(server_id)) error = true; if(!validate_race_id(race_id)) error = true; if(!validate_profession_id(profession_id)) error = true; if($('character_area_id') != null){ area_id = $('character_area_id').value; if(!validate_area_id(area_id)) error = true; } return error; } function construct_game_character_element(){ var game_id = $('character_game_id').value; var name = $('character_name').value; var level = $('character_level').value; var server_id = $('character_server_id').value; var race_id = $('character_race_id').value; var profession_id = $('character_profession_id').value; var area_id = null; // construct a character element that will show on registration page // html code looks like: // <li character_attributes> character_name <a href='#' onClick='edit_character'>edit</a> <a href='#' onClick='delete_character'>edit</a></li> var li = new Element('li', {id: 'character'+nr, game_id: game_id, name: name, level: level, server_id: server_id, race_id: race_id, profession_id: profession_id}); if($('character_area_id') != null){ area_id = $('character_area_id').value; li.writeAttribute({area_id: area_id}); } // construct label var label = new Element('label').update(name); label.setStyle({ float:'left', width: '125px' }); // construct url and edit link var parameters = 'id='+nr+'&' +$('character_form').serialize(); var url = '/register/edit_character?' + parameters; var edit_link = new Element('a', { href: url, rel: 'facebox'}).update('edit'); // construct seperator var seperator = new Element('label').update(' | ') // construct delete link and its event var delete_link = new Element('a', { href: '#'}).update('delete'); delete_link.observe('click', function(event){ if(confirm('are you sure?')) this.parentNode.remove(); }); // append elements to li li.appendChild(label); li.appendChild(edit_link); li.appendChild(seperator); li.appendChild(delete_link); nr++; return li; } function add_character(){ if(validate_game_character()) return; $('characters').insert(construct_game_character_element()); // close current facebox facebox.watchClickEvents(); facebox.close(); } function add_user_character(user_id){ if(validate_game_character()) return; var form = $('character_form'); var url = '/users/' + user_id + '/characters?' + form.serialize(); new Ajax.Request(url, {method: 'post'}); } function update_character(id){ if(validate_game_character()) return; $('character'+id).replace(construct_game_character_element()); // close current facebox facebox.watchClickEvents(); facebox.close(); } function update_user_character(user_id, id){ if(validate_game_character()) return; var form = $('character_form'); var url = '/users/' + user_id + '/characters/' + id + '?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function validate_and_request(){ if(validate_register_info()) return; // check if user has input at least one game character var form = $('register_form'); var cs = $('characters').childElements(); var length = cs.length; // construct url and parameter var parameters = ''; for(var i=0;i<length;i++){ var game_id = cs[i].readAttribute('game_id'); var name = cs[i].readAttribute('name'); var level = cs[i].readAttribute('level'); var area_id = cs[i].readAttribute('area_id'); var server_id = cs[i].readAttribute('server_id'); var race_id = cs[i].readAttribute('race_id'); var profession_id = cs[i].readAttribute('profession_id'); parameters += 'cs[][game_id]='+game_id+'&cs[][name]='+name+'&cs[][level]='+level+'&cs[][server_id]='+server_id+'&cs[][race_id]='+race_id+'&cs[][profession_id]='+profession_id; if(area_id != null) parameters += '&cs[][area_id]=' + area_id; parameters += '&'; } parameters += form.serialize(); url = '/users?' + parameters; // send request to server new Ajax.Request(url, {method: 'post'}); } diff --git a/public/photos/0000/0005/OnePiece.jpg b/public/photos/0000/0005/OnePiece.jpg new file mode 100644 index 0000000..fbc4273 Binary files /dev/null and b/public/photos/0000/0005/OnePiece.jpg differ diff --git a/public/photos/0000/0005/OnePiece_large.jpg b/public/photos/0000/0005/OnePiece_large.jpg new file mode 100644 index 0000000..566fad6 Binary files /dev/null and b/public/photos/0000/0005/OnePiece_large.jpg differ diff --git a/public/photos/0000/0005/OnePiece_medium.jpg b/public/photos/0000/0005/OnePiece_medium.jpg new file mode 100644 index 0000000..acfdb4e Binary files /dev/null and b/public/photos/0000/0005/OnePiece_medium.jpg differ diff --git a/public/photos/0000/0005/OnePiece_small.jpg b/public/photos/0000/0005/OnePiece_small.jpg new file mode 100644 index 0000000..b61aaed Binary files /dev/null and b/public/photos/0000/0005/OnePiece_small.jpg differ diff --git a/public/photos/0000/0013/logo-one-piece-82-1280x960.jpg b/public/photos/0000/0013/logo-one-piece-82-1280x960.jpg new file mode 100644 index 0000000..9d6d93e Binary files /dev/null and b/public/photos/0000/0013/logo-one-piece-82-1280x960.jpg differ diff --git a/public/photos/0000/0013/logo-one-piece-82-1280x960_large.jpg b/public/photos/0000/0013/logo-one-piece-82-1280x960_large.jpg new file mode 100644 index 0000000..7b471c4 Binary files /dev/null and b/public/photos/0000/0013/logo-one-piece-82-1280x960_large.jpg differ diff --git a/public/photos/0000/0013/logo-one-piece-82-1280x960_medium.jpg b/public/photos/0000/0013/logo-one-piece-82-1280x960_medium.jpg new file mode 100644 index 0000000..96a35d1 Binary files /dev/null and b/public/photos/0000/0013/logo-one-piece-82-1280x960_medium.jpg differ diff --git a/public/photos/0000/0013/logo-one-piece-82-1280x960_small.jpg b/public/photos/0000/0013/logo-one-piece-82-1280x960_small.jpg new file mode 100644 index 0000000..407a5d9 Binary files /dev/null and b/public/photos/0000/0013/logo-one-piece-82-1280x960_small.jpg differ diff --git a/public/photos/0000/0017/chinaFeng1.jpeg b/public/photos/0000/0017/chinaFeng1.jpeg new file mode 100644 index 0000000..db85400 Binary files /dev/null and b/public/photos/0000/0017/chinaFeng1.jpeg differ diff --git a/public/photos/0000/0017/chinaFeng1_large.jpeg b/public/photos/0000/0017/chinaFeng1_large.jpeg new file mode 100644 index 0000000..da8a506 Binary files /dev/null and b/public/photos/0000/0017/chinaFeng1_large.jpeg differ diff --git a/public/photos/0000/0017/chinaFeng1_medium.jpeg b/public/photos/0000/0017/chinaFeng1_medium.jpeg new file mode 100644 index 0000000..cb0ad96 Binary files /dev/null and b/public/photos/0000/0017/chinaFeng1_medium.jpeg differ diff --git a/public/photos/0000/0017/chinaFeng1_small.jpeg b/public/photos/0000/0017/chinaFeng1_small.jpeg new file mode 100644 index 0000000..4b6b338 Binary files /dev/null and b/public/photos/0000/0017/chinaFeng1_small.jpeg differ diff --git a/public/photos/0000/0025/logo-one-piece-82-1280x960.jpg b/public/photos/0000/0025/logo-one-piece-82-1280x960.jpg new file mode 100644 index 0000000..9d6d93e Binary files /dev/null and b/public/photos/0000/0025/logo-one-piece-82-1280x960.jpg differ diff --git a/public/photos/0000/0025/logo-one-piece-82-1280x960_large.jpg b/public/photos/0000/0025/logo-one-piece-82-1280x960_large.jpg new file mode 100644 index 0000000..7b471c4 Binary files /dev/null and b/public/photos/0000/0025/logo-one-piece-82-1280x960_large.jpg differ diff --git a/public/photos/0000/0025/logo-one-piece-82-1280x960_medium.jpg b/public/photos/0000/0025/logo-one-piece-82-1280x960_medium.jpg new file mode 100644 index 0000000..96a35d1 Binary files /dev/null and b/public/photos/0000/0025/logo-one-piece-82-1280x960_medium.jpg differ diff --git a/public/photos/0000/0025/logo-one-piece-82-1280x960_small.jpg b/public/photos/0000/0025/logo-one-piece-82-1280x960_small.jpg new file mode 100644 index 0000000..407a5d9 Binary files /dev/null and b/public/photos/0000/0025/logo-one-piece-82-1280x960_small.jpg differ diff --git a/test/functional/event_albums_controller_test.rb b/test/functional/event_albums_controller_test.rb new file mode 100644 index 0000000..440deef --- /dev/null +++ b/test/functional/event_albums_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class EventAlbumsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/event_photos_controller_test.rb b/test/functional/event_photos_controller_test.rb new file mode 100644 index 0000000..a451d8a --- /dev/null +++ b/test/functional/event_photos_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class EventPhotosControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/helpers/event_albums_helper_test.rb b/test/unit/helpers/event_albums_helper_test.rb new file mode 100644 index 0000000..958a890 --- /dev/null +++ b/test/unit/helpers/event_albums_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class EventAlbumsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/event_photos_helper_test.rb b/test/unit/helpers/event_photos_helper_test.rb new file mode 100644 index 0000000..5952dfc --- /dev/null +++ b/test/unit/helpers/event_photos_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class EventPhotosHelperTest < ActionView::TestCase +end
goodxiexin/dayday3
139295f6d78bb0f68f12cdab99c7566f62dbd73d
notification_added
diff --git a/TODO b/TODO index 1aa55e9..d8ca623 100755 --- a/TODO +++ b/TODO @@ -1,32 +1,7 @@ -1. think about if we really need personal controller and profile controller +1. conditional counter_cache -2. fix facebox bug DONE +2. how to calculate unread comment notification -3. fix relationship can't be invoked from view bug +3. setting (TONIGHT) -4. with scope DONE - -5. owner_required DONE - -6. compare 2 level resources and >2 level resources (in authentication) DONE - temporarily, I am adopting 2 level resources because it's not difficult to code. The design might be modified in the future. - -7. think about if we can integrate privilege check into authenticate_system - -8. view friends' page DONE - -9. prevent user from viewing mailbox, building new blog etc. DONE - -10. whisper? receiver_id? - -11. view friend's friends - -12. add friend - -13. how about tagged info and someone replied to you... - -order: -require login -require viewable (TO BE DONE tomorrow) -require owner -record visiting +4. comment_notification united? diff --git a/.TODO.swp b/app/controllers/user/.statuses_controller.rb.swp similarity index 84% rename from .TODO.swp rename to app/controllers/user/.statuses_controller.rb.swp index c2d1333..1c77fe0 100644 Binary files a/.TODO.swp and b/app/controllers/user/.statuses_controller.rb.swp differ diff --git a/app/controllers/user/bcomment_notifications_controller.rb b/app/controllers/user/bcomment_notifications_controller.rb new file mode 100644 index 0000000..e3ac382 --- /dev/null +++ b/app/controllers/user/bcomment_notifications_controller.rb @@ -0,0 +1,19 @@ +class User::BcommentNotificationsController < ApplicationController + + before_filter :owner_required + + def read_multiple + @user = resource_owner + BcommentNotification.transaction do + params[:ids].each do |id| + @notification = BcommentNotification.find(id) + @notification.update_attribute('read', true) + end + end + render :nothing => true + rescue + flash[:error] = "There was an error" + redirect_to user_comment_notifications_url(@user) + end + +end diff --git a/app/controllers/user/bcomments_controller.rb b/app/controllers/user/bcomments_controller.rb index 6417b8b..0af2372 100755 --- a/app/controllers/user/bcomments_controller.rb +++ b/app/controllers/user/bcomments_controller.rb @@ -1,37 +1,37 @@ class User::BcommentsController < ApplicationController before_filter :login_required before_filter :owner_required, :only => [:destroy] def create @blog = Blog.find(params[:blog_id]) @comment = Bcomment.new(params[:bcomment]) @comment.user = current_user @comment.blog = @blog if @comment.save - BcommentNotification.create(:user_id => current_user.id, :receiver_id => bcomment.receiver_id, :blog_id => bcomment.blog.id) + # create a notificaiton render :partial => 'bcomment', :object => @comment end rescue ActiveRecord::RecordNotFound render :text => 'blog not found' end def destroy @blog = Blog.find(params[:blog_id]) @comment = @blog.comments.find(params[:id]) @comment.destroy render :nothing => true rescue ActiveRecord::RecordNotFound render :text => 'blog not found' end def index @blog = Blog.find(params[:blog_id]) @comments = @blog.comments render :partial => 'bcomment', :collection => @comments rescue ActiveRecord::RecordNotFound render :text => 'blog not found' end end diff --git a/app/controllers/user/comment_notifications_controller.rb b/app/controllers/user/comment_notifications_controller.rb new file mode 100644 index 0000000..557bce0 --- /dev/null +++ b/app/controllers/user/comment_notifications_controller.rb @@ -0,0 +1,18 @@ +class User::CommentNotificationsController < ApplicationController + + layout 'user' + + before_filter :owner_required + + def index + @user = resource_owner + notifications = [] + notifications.concat @user.scomment_notifications + notifications.concat @user.vcomment_notifications + notifications.concat @user.bcomment_notifications + notifications.concat @user.pcomment_notifications + notifications.sort! { |x,y| y.created_at <=> x.created_at } + @notifications = notifications.paginate :page => params[:page], :per_page => 20 + end + +end diff --git a/app/controllers/user/pcomment_notifications_controller.rb b/app/controllers/user/pcomment_notifications_controller.rb new file mode 100644 index 0000000..81364c8 --- /dev/null +++ b/app/controllers/user/pcomment_notifications_controller.rb @@ -0,0 +1,20 @@ +class User::PcommentNotificationsController < ApplicationController + + before_filter :owner_required + + def read_multiple + @user = resource_owner + PcommentNotification.transaction do + params[:ids].each do |id| + @notification = PcommentNotification.find(id) + @notification.update_attribute('read', true) + end + end + render :nothing => true + rescue + flash[:error] = "There was an error" + redirect_to user_comment_notifications_url(@user) + end + + +end diff --git a/app/controllers/user/resource_feeds_controller.rb b/app/controllers/user/resource_feeds_controller.rb index c3fca99..f524b55 100644 --- a/app/controllers/user/resource_feeds_controller.rb +++ b/app/controllers/user/resource_feeds_controller.rb @@ -1,57 +1,57 @@ class User::ResourceFeedsController < ApplicationController layout 'user' before_filter :login_required - before_filter :record_visiting + before_filter :owner_required def index - @user = User.find(params[:user_id]) + @user = resource_owner @friends = @user.friends[0..8] # friend suggesion # pending request @resource_feeds = [] @resource_feeds.concat Status.feeds(@user, 0) @resource_feeds.concat Blog.feeds(@user, 0) @resource_feeds.concat Video.feeds(@user, 0) @resource_feeds.concat Album.feeds(@user, 0) @resource_feeds.sort! { |x,y| y.created_at <=> x.created_at } @idx = 1 end def get - @user = User.find(params[:user_id]) + @user = resource_owner @idx = params[:idx].to_i @resource_feeds = [] if params[:game_id].blank? while @resource_feeds.blank? and @idx < 4 @resource_feeds.concat Status.feeds(@user, @idx) @resource_feeds.concat Blog.feeds(@user, @idx) @resource_feeds.concat Video.feeds(@user, @idx) @resource_feeds.concat Album.feeds(@user, @idx) @idx = @idx + 1 end else args = "game_id = #{params[:game_id]}" while @resource_feeds.blank? and @idx < 4 @resource_feeds.concat Blog.feeds(@user, @idx, args) @resource_feeds.concat Video.feeds(@user, @idx, args) @resource_feeds.concat Album.feeds(@user, @idx, args) @idx = @idx + 1 end end if @resource_feeds.blank? render :update do |page| page.replace_html 'more_feeds', '<h2> Cannot find any more resource feeds </h2>' end else @resource_feeds.sort! { |x,y| y.created_at <=> x.created_at } render :update do |page| page.insert_html :bottom, 'feeds', :partial => 'resource_feed', :collection => @resource_feeds page.replace_html 'more_feeds', "#{link_to_remote "More..", :url => get_user_resource_feeds_url(@user, :idx => @idx, :game_id => params[:game_id]), :method => :get}" end end end end diff --git a/app/controllers/user/scomment_notifications_controller.rb b/app/controllers/user/scomment_notifications_controller.rb new file mode 100644 index 0000000..3c552c3 --- /dev/null +++ b/app/controllers/user/scomment_notifications_controller.rb @@ -0,0 +1,20 @@ +class User::ScommentNotificationsController < ApplicationController + + before_filter :owner_required + + def read_multiple + @user = resource_owner + ScommentNotification.transaction do + params[:ids].each do |id| + @notification = ScommentNotification.find(id) + @notification.update_attribute('read', true) + end + end + render :nothing => true + rescue + flash[:error] = "There was an error" + redirect_to user_comment_notifications_url(@user) + end + + +end diff --git a/app/controllers/user/status_feeds_controller.rb b/app/controllers/user/status_feeds_controller.rb index ff7c992..31bca76 100644 --- a/app/controllers/user/status_feeds_controller.rb +++ b/app/controllers/user/status_feeds_controller.rb @@ -1,22 +1,33 @@ class User::StatusFeedsController < ApplicationController + layout 'user' + before_filter :login_required + before_filter :owner_required + + def index + @user = resource_owner + ret = Status.more_feeds(@user, 0) + @idx = ret[0] + 1 + @statuses = ret[1] + end + def get @user = User.find(params[:user_id]) ret = Status.more_feeds(@user, params[:idx].to_i) @idx = ret[0] @statuses = ret[1] if @statuses.blank? render :update do |page| page.replace_html 'more_feeds', '<h2> Cannot find any more statuses <h2>' end else render :update do |page| page.insert_html :bottom, 'feeds', :partial => 'sfeed', :collection => @statuses page.replace_html 'more_feeds', "#{link_to_remote "More..", :url => get_user_status_feeds_url(@user, :idx => @idx + 1), :method => :get}" end end end end diff --git a/app/controllers/user/statuses_controller.rb b/app/controllers/user/statuses_controller.rb index 49b298f..2dc7453 100755 --- a/app/controllers/user/statuses_controller.rb +++ b/app/controllers/user/statuses_controller.rb @@ -1,32 +1,54 @@ class User::StatusesController < ApplicationController layout 'user' before_filter :login_required - before_filter :owner_required, :only => [:new, :create] + before_filter :owner_required, :only => [:new, :create, :destroy] def new @user = resource_owner @latest_status = @user.latest_status end def create @user = resource_owner @status = Status.new(params[:status]) @status.user = @user - if @status.save - render :update do |page| - page.replace_html "latest_status", :inline => "<%= distance_of_time_in_words_to_now(@user.latest_status.created_at) %> ago: <%= @user.latest_status.content %>" - page.visual_effect :highlight, 'latest_status', :duration => 2 - page << "$('status_content').value = '';" + if params[:home].to_i == 1 + if @status.save + render :update do |page| + page.replace_html "latest_status", :inline => "<%= distance_of_time_in_words_to_now(@user.latest_status.created_at) %> ago: <%= @user.latest_status.content %>" + page.visual_effect :highlight, 'latest_status', :duration => 2 + page << "$('status_content').value = '';" + end + else + render :update do |page| + page << "alert('something error occurred, try it later')" + end end else - render :update do |page| - page << "alert('something error occurred, try it later')" + if @status.save + render :update do |page| + page.insert_html :top, 'statuses', :partial => 'status', :object => @status + page << "$('status_content').value = '';" + end end end end + def index + @user = resource_owner + @statuses = @user.statuses + end + + def destroy + @status = Status.find(params[:id]) + @status.destroy + render :nothing => true + rescue ActiveRecord::RecordNotFound + render :text => 'status not found' + end + end diff --git a/app/controllers/user/vcomment_notifications_controller.rb b/app/controllers/user/vcomment_notifications_controller.rb new file mode 100644 index 0000000..12a18e8 --- /dev/null +++ b/app/controllers/user/vcomment_notifications_controller.rb @@ -0,0 +1,20 @@ +class User::VcommentNotificationsController < ApplicationController + + before_filter :owner_required + + def read_multiple + @user = resource_owner + VcommentNotification.transaction do + params[:ids].each do |id| + @notification = VcommentNotification.find(id) + @notification.update_attribute('read', true) + end + end + render :nothing => true + rescue + flash[:error] = "There was an error" + redirect_to user_comment_notifications_url(@user) + end + + +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 5434293..62230bf 100755 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,28 +1,32 @@ # Methods added to this helper will be available to all templates in the application. module ApplicationHelper def ftime(time) time.strftime("%Y-%m-%d %H:%M") unless time.blank? end def ftime2(time) time.strftime("%Y-%m-%d") unless time.blank? end def ftime3(time) time.strftime("%m-%d") unless time.blank? end + def ftime4(time) + time.strftime("%H: %M") unless time.blank? + end + def validation_image "<img src='/application/new_validation_image' />" end def privilege_select_tag(resource, privilege) select_tag "#{resource}[privilege]", options_for_select([['all', 'all'], ['friends', 'friends'], ['myself', 'myself']], privilege) end def link_to_game(game) link_to game.name end end diff --git a/app/helpers/user/bcomment_notifications_helper.rb b/app/helpers/user/bcomment_notifications_helper.rb new file mode 100644 index 0000000..13c233c --- /dev/null +++ b/app/helpers/user/bcomment_notifications_helper.rb @@ -0,0 +1,2 @@ +module User::BcommentNotificationsHelper +end diff --git a/app/helpers/user/bcomments_helper.rb b/app/helpers/user/bcomments_helper.rb index 17e3ee9..8dfbee8 100755 --- a/app/helpers/user/bcomments_helper.rb +++ b/app/helpers/user/bcomments_helper.rb @@ -1,2 +1,9 @@ module User::BcommentsHelper + + # if current user is blog owner, or the receiver of this bcomment, or the poster of this bcomment + # then it's viewable + def bcomment_viewable(bcomment, current_user) + !bcomment.whisper || (bcomment.whisper and (current_user == bcomment.user or current_user == bcomment.receiver or current_user == bcomment.blog.user)) + end + end diff --git a/app/helpers/user/comment_notifications_helper.rb b/app/helpers/user/comment_notifications_helper.rb new file mode 100644 index 0000000..85ba111 --- /dev/null +++ b/app/helpers/user/comment_notifications_helper.rb @@ -0,0 +1,2 @@ +module User::CommentNotificationsHelper +end diff --git a/app/helpers/user/pcomment_notifications_helper.rb b/app/helpers/user/pcomment_notifications_helper.rb new file mode 100644 index 0000000..aeb6527 --- /dev/null +++ b/app/helpers/user/pcomment_notifications_helper.rb @@ -0,0 +1,2 @@ +module User::PcommentNotificationsHelper +end diff --git a/app/helpers/user/pcomments_helper.rb b/app/helpers/user/pcomments_helper.rb index 849d9a3..de3c5a9 100755 --- a/app/helpers/user/pcomments_helper.rb +++ b/app/helpers/user/pcomments_helper.rb @@ -1,2 +1,8 @@ module User::PcommentsHelper + + def pcomment_viewable(pcomment, current_user) + !pcomment.whisper || (pcomment.whisper and (current_user == pcomment.user or current_user == pcomment.receiver or current_user == pcomment.photo.album.user)) + end + + end diff --git a/app/helpers/user/scomment_notifications_helper.rb b/app/helpers/user/scomment_notifications_helper.rb new file mode 100644 index 0000000..423babc --- /dev/null +++ b/app/helpers/user/scomment_notifications_helper.rb @@ -0,0 +1,2 @@ +module User::ScommentNotificationsHelper +end diff --git a/app/helpers/user/scomments_helper.rb b/app/helpers/user/scomments_helper.rb index a00630a..d357db0 100644 --- a/app/helpers/user/scomments_helper.rb +++ b/app/helpers/user/scomments_helper.rb @@ -1,2 +1,8 @@ module User::ScommentsHelper + + def scomment_viewable(scomment, current_user) + !scomment.whisper || (scomment.whisper and (current_user == scomment.user or current_user == scomment.receiver or current_user == scomment.status.user)) + end + + end diff --git a/app/helpers/user/vcomment_notifications_helper.rb b/app/helpers/user/vcomment_notifications_helper.rb new file mode 100644 index 0000000..22a270d --- /dev/null +++ b/app/helpers/user/vcomment_notifications_helper.rb @@ -0,0 +1,2 @@ +module User::VcommentNotificationsHelper +end diff --git a/app/helpers/user/vcomments_helper.rb b/app/helpers/user/vcomments_helper.rb index acd66f5..ff04e70 100644 --- a/app/helpers/user/vcomments_helper.rb +++ b/app/helpers/user/vcomments_helper.rb @@ -1,2 +1,8 @@ module User::VcommentsHelper + + def vcomment_viewable(vcomment, current_user) + !vcomment.whisper || (vcomment.whisper and (current_user == vcomment.user or current_user == vcomment.receiver or current_user == vcomment.video.user)) + end + + end diff --git a/app/models/bcomment.rb b/app/models/bcomment.rb index 9af51d3..1acf438 100755 --- a/app/models/bcomment.rb +++ b/app/models/bcomment.rb @@ -1,13 +1,15 @@ class Bcomment < ActiveRecord::Base belongs_to :user # who posted this comment - belongs_to :receiver # who did user reply to + belongs_to :receiver, # who did user reply to + :class_name => 'User' belongs_to :blog, :counter_cache => :comments_count has_one :bcomment_notification, + :foreign_key => 'comment_id', :dependent => :destroy end diff --git a/app/models/bcomment_notification.rb b/app/models/bcomment_notification.rb index ec76db4..3e8ed36 100644 --- a/app/models/bcomment_notification.rb +++ b/app/models/bcomment_notification.rb @@ -1,11 +1,9 @@ -class BcommentNotification < ActiveRecord::Base - - belongs_to :user +class BcommentNotification < ActiveRecord::Base - belongs_to :commentor, - :class_name => 'User', - :foreign_key => 'commentor_id' + belongs_to :user - belongs_to :blog + belongs_to :comment, + :class_name => 'Bcomment' end + diff --git a/app/models/bcomment_observer.rb b/app/models/bcomment_observer.rb deleted file mode 100644 index 06343fa..0000000 --- a/app/models/bcomment_observer.rb +++ /dev/null @@ -1,12 +0,0 @@ -class BcommentObserver < ActiveRecord::Observer - - # after a bcomment is created, send a notification to the receiver - # receiver might be the owner of the resource or someone who commented this resource - def after_save(bcomment) - notification = BcommentNotification.create( - :user_id => current_user.id, - :receiver_id => bcomment.receiver_id, - :blog_id => bcomment.blog.id) - end - -end diff --git a/app/models/comment_observer.rb b/app/models/comment_observer.rb new file mode 100644 index 0000000..224bc4e --- /dev/null +++ b/app/models/comment_observer.rb @@ -0,0 +1,10 @@ +class CommentObserver < ActiveRecord::Observer + + observe :Bcomment, :Vcomment, :Scomment, :Pcomment + + def after_save(comment) + notification_name = comment.class.to_s.concat "Notification" + eval("#{notification_name}").create(:user_id => comment.receiver_id, :comment_id => comment.id) + end + +end diff --git a/app/models/pcomment.rb b/app/models/pcomment.rb index 6e07925..274414f 100755 --- a/app/models/pcomment.rb +++ b/app/models/pcomment.rb @@ -1,10 +1,11 @@ class Pcomment < ActiveRecord::Base belongs_to :user - belongs_to :receiver + belongs_to :receiver, + :class_name => 'User' belongs_to :photo, :counter_cache => 'comments_count' end diff --git a/app/models/pcomment_notification.rb b/app/models/pcomment_notification.rb new file mode 100644 index 0000000..4ddeca7 --- /dev/null +++ b/app/models/pcomment_notification.rb @@ -0,0 +1,11 @@ +class PcommentNotification < ActiveRecord::Base + + belongs_to :user + + belongs_to :commentor, + :class_name => 'User' + + belongs_to :comment, + :class_name => 'Pcomment' + +end diff --git a/app/models/scomment.rb b/app/models/scomment.rb index 0574f53..de42bff 100644 --- a/app/models/scomment.rb +++ b/app/models/scomment.rb @@ -1,10 +1,11 @@ class Scomment < ActiveRecord::Base belongs_to :user - belongs_to :receiver + belongs_to :receiver, + :class_name => 'User' belongs_to :status, :counter_cache => :comments_count end diff --git a/app/models/scomment_notification.rb b/app/models/scomment_notification.rb new file mode 100644 index 0000000..66bab2d --- /dev/null +++ b/app/models/scomment_notification.rb @@ -0,0 +1,11 @@ +class ScommentNotification < ActiveRecord::Base + + belongs_to :user + + belongs_to :commentor, + :class_name => 'User' + + belongs_to :comment, + :class_name => 'Scomment' + +end diff --git a/app/models/user.rb b/app/models/user.rb index 32c30c4..bb483c1 100755 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,244 +1,249 @@ require 'digest/sha1' class User < ActiveRecord::Base has_many :visitor_records, :order => 'created_at DESC' belongs_to :city belongs_to :province belongs_to :country has_many :wall_messages, :dependent => :destroy, :finder_sql => 'select wall_messages.* from wall_messages where wall_messages.user_id = #{id} OR wall_messages.receiver_id = #{id} ORDER BY created_at DESC' has_many :sent_mails, :class_name => 'Mail', :foreign_key => 'sender_id', :conditions => { :delete_by_sender => false } has_many :recv_mails, :class_name => 'Mail', :foreign_key => 'receiver_id', :conditions => { :delete_by_receiver => false } def unread_recv_mails_count recv_mails.find_all { |m| !m.read_by_receiver? }.count end has_many :friendships, :dependent => :destroy has_many :friends, :class_name => 'User', :order => 'login ASC', :through => :friendships def has_friend(user) self.friends.include?(user) end has_many :game_characters, :dependent => :destroy has_many :currently_playing_game_characters, :class_name => 'GameCharacter', :conditions => { :playing => true }, :order => 'created_at DESC' has_many :games, :through => :game_characters, :uniq => true has_many :icons, :class_name => 'Photo', :order => 'created_at DESC', :dependent => :destroy has_one :current_icon, :class_name => 'Photo', :order => 'created_at DESC', :conditions => {:current_icon => true} def next_prev_icon(cur_icon) size = self.icons.count next_icon_idx = 0 prev_icon_idx = 0 cur_icon_idx = 0 self.icons.each_with_index do |icon, i| if cur_icon == icon next_icon_idx = (i + 1) % size prev_icon_idx = (i - 1 + size) % size cur_icon_idx = i + 1 break end end [self.icons[next_icon_idx], self.icons[prev_icon_idx], cur_icon_idx] end def reset_icon(new_icon) old_icon = self.current_icon unless new_icon == old_icon old_icon.update_attribute(:current_icon, false) unless old_icon.blank? new_icon.current_icon = true new_icon.user_id = self.id end end has_many :statuses, :order => 'created_at DESC', :dependent => :destroy has_one :latest_status, :class_name => 'Status', :order => 'created_at DESC' + has_many :scomment_notifications, + :order => 'created_at DESC' + has_many :blogs, :order => 'position DESC', :conditions => {:draft => false} has_many :bcomment_notifications, :order => 'created_at DESC' - - def can_view(blog) - return true if blog.user == self - case blog.privilege - when 'all' - return true - when 'myself' - return (blog.user == self) - when 'only friends' - return blog.user.has_friend(self) - end + + def unread_comments_count + self.bcomment_notifications.find_all {|x| !x.read}.count + + self.vcomment_notifications.find_all {|x| !x.read}.count + + self.scomment_notifications.find_all {|x| !x.read}.count + + self.pcomment_notifications.find_all {|x| !x.read}.count end + has_many :drafts, :class_name => 'Blog', :order => 'updated_at DESC', :conditions => {:draft => true} has_many :albums, :order => 'updated_at DESC' + has_many :pcomment_notifications, + :order => 'created_at DESC' + has_many :videos, :order => 'position DESC' + has_many :vcomment_notifications, + :order => 'created_at DESC' + # permissions and roles has_many :permissions has_many :roles, :through => :permissions # Virtual attribute for the unencrypted password attr_accessor :password, :password_confirmation # callbacks before_save :encrypt_password before_create :make_activation_code # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :gender, :password, :password_confirmation, :qq, :website, :mobile, :country, :city, :province, :birthday # Activates the user in the database. def activate @activated = true self.activated_at = Time.now.utc self.activation_code = nil save(false) end def active? # the existence of an activation code means they have not activated yet activation_code.nil? end # Authenticates a user by their login name and unencrypted password. Returns the user or nil. def self.authenticate(email, password) u = find :first, :conditions => ['email = ? and activated_at IS NOT NULL', email] u && u.authenticated?(password) ? u : nil end # Encrypts some data with the salt. def self.encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end # Encrypts the password with the user salt def encrypt(password) self.class.encrypt(password, salt) end def authenticated?(password) crypted_password == encrypt(password) end def remember_token? remember_token_expires_at && Time.now.utc < remember_token_expires_at end # These create and unset the fields required for remembering users between browser closes def remember_me remember_me_for 2.weeks end def remember_me_for(time) remember_me_until time.from_now.utc end def remember_me_until(time) self.remember_token_expires_at = time self.remember_token = encrypt("#{email}--#{remember_token_expires_at}") save(false) end def forget_me self.remember_token_expires_at = nil self.remember_token = nil save(false) end def forgot_password @forgotten_password = true self.make_password_reset_code end def reset_password update_attribute(:password_reset_code, nil) @reset_password = true end def has_role?(name) self.roles.find_by_name(name) ? true : false end # Returns true if the user has just been activated. def recently_activated? @activated end def recently_forgot_password? @forgotten_password end def recently_reset_password? @reset_password end protected def encrypt_password return if password.blank? self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record? self.crypted_password = encrypt(password) end def make_activation_code self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end def make_password_reset_code self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end end diff --git a/app/models/vcomment.rb b/app/models/vcomment.rb index 26359d3..720a988 100644 --- a/app/models/vcomment.rb +++ b/app/models/vcomment.rb @@ -1,11 +1,12 @@ class Vcomment < ActiveRecord::Base belongs_to :user - belongs_to :receiver + belongs_to :receiver, + :class_name => 'User' belongs_to :video, :counter_cache => :comments_count end diff --git a/app/models/vcomment_notification.rb b/app/models/vcomment_notification.rb new file mode 100644 index 0000000..6e425f5 --- /dev/null +++ b/app/models/vcomment_notification.rb @@ -0,0 +1,11 @@ +class VcommentNotification < ActiveRecord::Base + + belongs_to :user + + belongs_to :commentor, + :class_name => 'User' + + belongs_to :comment, + :class_name => 'Vcomment' + +end diff --git a/app/views/layouts/user.html.erb b/app/views/layouts/user.html.erb index cd9a286..e776f86 100755 --- a/app/views/layouts/user.html.erb +++ b/app/views/layouts/user.html.erb @@ -1,41 +1,42 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <%= stylesheet_link_tag "user" %> <%= stylesheet_link_tag 'facebox' %> <%= javascript_include_tag :defaults %> <%= javascript_include_tag 'facebox' %> <%= javascript_include_tag 'nicEdit' %> <%= javascript_include_tag 'resource_feeds' %> <%= javascript_include_tag 'video' %> <%= javascript_include_tag 'validator' %> + <%= javascript_include_tag 'comment_notification' %> </head> <body> <div id="container">   <div id="header"> <%= render :partial => 'layouts/user_menus' %>   </div> <div id='containter'>    <div id="left"> <%= yield :left %> </div>   <div id="middle"> <% if flash[:notice] %> <div class='yellow-info'><%= flash[:notice] %></div> <% end -%> <% if flash[:error] %> <div class='red-error'><%= flash[:error] %></div> <% end -%> <%= yield %>    </div> <div id="right"> <%= yield :right %>    </div> </div>   <div id="footer"> <!-- Dayday3 Group: xiahong gao, xin xie -->   </div> </div> </body> diff --git a/app/views/user/bcomment_notifications/_bnotification.html.erb b/app/views/user/bcomment_notifications/_bnotification.html.erb new file mode 100644 index 0000000..b9ea33a --- /dev/null +++ b/app/views/user/bcomment_notifications/_bnotification.html.erb @@ -0,0 +1,13 @@ +<% blog = bnotification.comment.blog %> +<% owner = blog.user %> +<% commentor = bnotification.comment.user %> +<li id="bnotification_<%= bnotification.id%>" type='blog' type_id='<%= blog.id %>' notification_id='<%= bnotification.id%>'> + <span class='notification-tiny'><%= ftime4 bnotification.created_at %></span> + <% if delete %> + <%= link_to_function 'X', "read_notification('blog', '#{blog.id}', #{@user.id}, 1);", :style => "float:right;margin-right:5px" %> + <% end %> + <% style = (bnotification.read)? "font-weight: normal;" : "font-weight: bold;" %> + <span style='<%= style %>'> + <%= link_to_user commentor %> replied to you in blog <%= link_to_function (truncate blog.title, 20), "read_notification('blog','#{blog.id}', #{@user.id}, #{delete ? 1:0});window.open('#{user_blog_url(owner, blog)}');", :popup => true %> + </span> +</li> diff --git a/app/views/user/bcomments/_bcomment.html.erb b/app/views/user/bcomments/_bcomment.html.erb index b444ac0..b8cef8f 100755 --- a/app/views/user/bcomments/_bcomment.html.erb +++ b/app/views/user/bcomments/_bcomment.html.erb @@ -1,15 +1,20 @@ <% user = bcomment.user %> -<% comment_divid = "comment_#{bcomment.id}" %> +<% comment_divid = "bcomment_#{bcomment.id}" %> +<% if bcomment_viewable(bcomment, current_user) %> <div id=<%= comment_divid %> class='comment-box'> + <% if bcomment.whisper %> + <span class='whisper'><strong>whisper</strong></span> + <% end %> <%= user_icon(user) %> <strong><%= link_to_user user %></strong> <span class="comment-box-tiny"><%= ftime bcomment.created_at %></span><br/> <%= bcomment.content %><br/> <% if current_user == user %> <%= link_to_remote 'delete', :complete => "$('#{comment_divid}').remove();", :url => blog_comment_url(bcomment.blog, bcomment), :method => :delete %> <% else %> <%= link_to_function 'comment', "$('bcomment_receiver_#{bcomment.blog.id}').value=#{user.id};$('bcomment_content_#{bcomment.blog.id}').value='reply to #{user.login}: '; $('bcomment_content_#{bcomment.blog.id}').focus();" %> <% end %> </div> +<% end %> diff --git a/app/views/user/bcomments/_new.html.erb b/app/views/user/bcomments/_new.html.erb index 1e718a4..b948d85 100644 --- a/app/views/user/bcomments/_new.html.erb +++ b/app/views/user/bcomments/_new.html.erb @@ -1,16 +1,16 @@ <% form_remote_for :bcomment, :position => :bottom, :update => "bcomments_#{blog.id}", :complete => "$('bcomment_content_#{blog.id}').value = '';", :url => blog_comments_url(blog) do |form| %> - <p style="display:none"><%= text_field_tag 'bcomment[receiver_id]', blog.user.id, :id => "bcomment_receiver_#{blog.id}" %></p> + <p style="display:none"><%= text_field_tag 'bcomment[receiver_id]', blog.user_id, :id => "bcomment_receiver_#{blog.id}" %></p> <div class='comment-box'> <%= user_icon(current_user) %> <%= text_area_tag 'bcomment[content]', '', :cols => 40, :rows => 3, :id => "bcomment_content_#{blog.id}" %><br/> <div style="float:right; margin-right:15px"> <%= form.label "whisper?" %><%= form.check_box 'whisper' %> <%= form.submit 'comment' %> </div> </div> <% end %> diff --git a/app/views/user/comment_notifications/_index.html.erb b/app/views/user/comment_notifications/_index.html.erb new file mode 100644 index 0000000..23a0a32 --- /dev/null +++ b/app/views/user/comment_notifications/_index.html.erb @@ -0,0 +1,19 @@ +<% + notifications = [] + notifications.concat @user.scomment_notifications + notifications.concat @user.vcomment_notifications + notifications.concat @user.bcomment_notifications + notifications.concat @user.pcomment_notifications + @notifications = notifications.find_all {|x| !x.read} + @notifications = @notifications.sort { |x,y| y.created_at <=> x.created_at } +%> +<div class='comment-notification'> + <h3> comments and messages <%= link_to_function 'fold', "$('notifications').toggle();if(this.innerHTML == 'unfold') this.update('fold'); else this.update('unfold');", :class => 'hide-all'%></h3> + <div id='notifications'> + <%= render :partial => 'user/comment_notifications/notification', :collection => @notifications[0..7], :locals => {:delete => true} %> + </div> + <div class='view-all'> + <%= link_to 'more..', user_comment_notifications_url(@user) %> + </div> +</div> + diff --git a/app/views/user/comment_notifications/_notification.html.erb b/app/views/user/comment_notifications/_notification.html.erb new file mode 100644 index 0000000..19c2d9c --- /dev/null +++ b/app/views/user/comment_notifications/_notification.html.erb @@ -0,0 +1,5 @@ +<% class_name = notification.class.to_s.downcase.pluralize %> +<% idx = class_name.index 'notification' %> +<% directory = class_name[0..(idx-1)] + '_' + class_name[idx..class_name.size] %> +<% initial = class_name[0..0] %> +<%= render :partial => "user/#{directory}/#{initial}notification", :object => notification, :locals => {:delete => delete} %> diff --git a/app/views/user/comment_notifications/index.html.erb b/app/views/user/comment_notifications/index.html.erb new file mode 100644 index 0000000..b03f735 --- /dev/null +++ b/app/views/user/comment_notifications/index.html.erb @@ -0,0 +1,10 @@ +<h3>comment notifications</h3> + +<div class='notification-board'> +<div class='comment-notification' id='notifications'> + <%= render :partial => 'user/comment_notifications/notification', :collection => @notifications, :locals => {:delete => false} %> +</div> +</div> + +<%= page_entries_info @notifications, :entry_name => 'notification' %> +<%= will_paginate @notifications %> diff --git a/app/views/user/pcomment_notifications/_pnotification.html.erb b/app/views/user/pcomment_notifications/_pnotification.html.erb new file mode 100644 index 0000000..27f28e0 --- /dev/null +++ b/app/views/user/pcomment_notifications/_pnotification.html.erb @@ -0,0 +1,14 @@ +<% photo = pnotification.comment.photo %> +<% owner = photo.user %> +<% commentor = pnotification.comment.user %> +<li id="pnotification_<%= pnotification.id%>" type='photo' type_id='<%= photo.id %>' notification_id='<%= pnotification.id %>'> + <span class='notification-tiny'><%= ftime4 pnotification.created_at %></span> + <% if delete %> + <%= link_to_function 'X', "read_notification('photo', '#{photo.id}', #{@user.id}, 1)", :style => "float:right;margin-right:5px" %> + <% end %> + <% style = (pnotification.read)? "font-weight: normal;" : "font-weight: bold;" %> + <span style='<%= style %>'> + <%= link_to_user commentor %> replied to you in album <%= link_to_function (truncate photo.album.title, 20), "read_notification('photo', '#{photo.id}', #{@user.id}, #{delete ? 1 : 0});window.open('#{album_photo_url(photo.album, photo)}');", :popup => true %> + </span> +</li> + diff --git a/app/views/user/pcomments/_new.html.erb b/app/views/user/pcomments/_new.html.erb index 6d4cd0b..9fc7350 100644 --- a/app/views/user/pcomments/_new.html.erb +++ b/app/views/user/pcomments/_new.html.erb @@ -1,15 +1,16 @@ <% form_remote_for :pcomment, :position => :bottom, :update => "pcomments_#{photo.id}", :complete => "$('pcomment_content_#{photo.id}').value = '';", :url => photo_comments_url(photo) do |form| %> + <p style="display:none"><%= text_field_tag 'pcomment[receiver_id]', photo.album.user_id, :id => "pcomment_receiver_#{photo.id}" %></p> <div class='comment-box'> <%= user_icon(current_user) %> <%= text_area_tag 'pcomment[content]', '', :cols => 40, :rows => 3, :id => "pcomment_content_#{photo.id}" %><br/> <div style="float:right; margin-right:15px"> <%= form.label "whisper?" %><%= form.check_box 'whisper' %> <%= form.submit 'comment' %> </div> </div> <% end %> diff --git a/app/views/user/pcomments/_pcomment.html.erb b/app/views/user/pcomments/_pcomment.html.erb index bd03107..f58e0d7 100644 --- a/app/views/user/pcomments/_pcomment.html.erb +++ b/app/views/user/pcomments/_pcomment.html.erb @@ -1,14 +1,19 @@ <% user = pcomment.user %> -<% comment_divid = "comment_#{pcomment.id}" %> +<% comment_divid = "pcomment_#{pcomment.id}" %> +<% if pcomment_viewable(pcomment, current_user) %> <div id=<%= comment_divid %> class='comment-box'> + <% if pcomment.whisper %> + <div class='whisper'><strong>whisper</strong></div> + <% end %> <%= user_icon(user) %> <strong><%= link_to_user user %></strong> <span class="comment-box-tiny"><%= ftime pcomment.created_at %></span><br/> <%= pcomment.content %><br/> <% if current_user == user %> <%= link_to_remote 'delete', :complete => "$('#{comment_divid}').remove();", :url => photo_comment_url(pcomment.photo, pcomment), :method => :delete %> <% else %> - <%= link_to_function 'comment', "$('pcomment_content').value='reply to #{user.login}: '; $('pcomment_content').focus();" %> + <%= link_to_function 'comment', "$('pcomment_receiver_#{pcomment.photo.id}').value=#{user.id};$('pcomment_content_#{pcomment.photo.id}').value='reply to #{user.login}: '; $('pcomment_content_#{pcomment.photo.id}').focus();" %> <% end %> </div> +<% end %> diff --git a/app/views/user/personal/index.html.erb b/app/views/user/personal/index.html.erb deleted file mode 100644 index 8cf17f5..0000000 --- a/app/views/user/personal/index.html.erb +++ /dev/null @@ -1,19 +0,0 @@ -<% content_for :left do %> - <%= render :partial => 'user/personal/icon_left' %><br/> - <% if @user.has_friend(current_user) %> - <%= render :partial => 'user/personal/character_left' %><br/> - <% end %> - <%= render :partial => 'user/personal/activity_left' %><br/> - <%= render :partial => 'user/personal/album_left' %><br/> -<% end %> - -<% content_for :right do %> - <%= render :partial => 'user/personal/visitor_history', :object => @user.visitor_records[0..8] %><br/> - <%= render :partial => 'user/personal/friends', :object => @user.friends[0..14] %> -<% end %> - -<%= render :partial => 'user/personal/menu' %> - -<div id='container'> -</div> - diff --git a/app/views/user/personal/show.html.erb b/app/views/user/personal/show.html.erb index 0e36429..775bdcc 100644 --- a/app/views/user/personal/show.html.erb +++ b/app/views/user/personal/show.html.erb @@ -1,17 +1,19 @@ <% content_for :left do %> <%= render :partial => 'user/personal/icon_left' %><br/> <%= render :partial => 'user/personal/character_left' %><br/> <%= render :partial => 'user/personal/activity_left' %><br/> <%= render :partial => 'user/personal/album_left' %><br/> <% end %> <% content_for :right do %> <%= render :partial => 'user/personal/visitor_history', :object => @user.visitor_records[0..8] %><br/> <%= render :partial => 'user/personal/friends', :object => @user.friends[0..14] %> <% end %> <%= render :partial => 'user/personal/menu' %> +<%= render :partial => 'user/statuses/show' %> + <div id='personal_container'> </div> diff --git a/app/views/user/resource_feeds/index.html.erb b/app/views/user/resource_feeds/index.html.erb index d8be014..b64a23f 100644 --- a/app/views/user/resource_feeds/index.html.erb +++ b/app/views/user/resource_feeds/index.html.erb @@ -1,19 +1,21 @@ <% content_for :left do %> <%= render :partial => 'menu' %><br/> <%= render :partial => 'user/home/digs_menu' %> <% end %> <% content_for :right do %> <%= render :partial => 'user/personal/visitor_history', :object => @user.visitor_records[0..8] %><br/> <%= render :partial => 'user/home/friend_suggestions', :locals => {:friends => @friends} %><br/> <%= render :partial => 'user/home/pending_requests' %><br/> <% end %> <%= render :partial => 'user/statuses/new' %> +<%= render :partial => 'user/comment_notifications/index' %> + <div id='feeds'> <%= render :partial => 'resource_feed', :collection => @resource_feeds %> </div> <div id='more_feeds' style="float:left"> <%= link_to_remote "More..", :url => get_user_resource_feeds_url(@user, :idx => @idx), :method => :get %> </div> diff --git a/app/views/user/scomment_notifications/_snotification.html.erb b/app/views/user/scomment_notifications/_snotification.html.erb new file mode 100644 index 0000000..ba0342c --- /dev/null +++ b/app/views/user/scomment_notifications/_snotification.html.erb @@ -0,0 +1,14 @@ +<% status = snotification.comment.status %> +<% owner = status.user %> +<% commentor = snotification.comment.user %> +<li id="snotification_<%= snotification.id%>" type='status' type_id='<%= status.id %>' notification_id='<%= snotification.id %>' > + <span class='notification-tiny'><%= ftime4 snotification.created_at %></span> + <% if delete %> + <%= link_to_function 'X', "read_notification('status', '#{status.id}', #{@user.id}, 1)", :style => "float:right;margin-right:5px" %> + <% end %> + <% style = (snotification.read)? "font-weight: normal;" : "font-weight: bold;" %> + <span style='<%= style %>'> + <%= link_to_user commentor %> replied to you in status <%= link_to_function (truncate status.content, 20), "read_notification('status', '#{status.id}', #{@user.id}, #{delete ? 1 : 0});window.open('#{user_status_url(owner, status)}');", :popup => true %> + </span> +</li> + diff --git a/app/views/user/scomments/_new.html.erb b/app/views/user/scomments/_new.html.erb index b70db20..1ddd59d 100644 --- a/app/views/user/scomments/_new.html.erb +++ b/app/views/user/scomments/_new.html.erb @@ -1,15 +1,16 @@ <% form_remote_for :scomment, :position => :bottom, :update => "scomments_#{status.id}", :complete => "$('scomment_content_#{status.id}').value = '';", :url => status_comments_url(status) do |form| %> + <p style="display:none"><%= text_field_tag 'scomment[receiver_id]', status.user_id, :id => "scomment_receiver_#{status.id}" %></p> <div class='comment-box'> <%= user_icon(current_user) %> <%= text_area_tag 'scomment[content]', '', :cols => 40, :rows => 3, :id => "scomment_content_#{status.id}" %><br/> <div style="float:right; margin-right:15px"> <%= form.label "whisper?" %><%= form.check_box 'whisper' %> <%= form.submit 'comment' %> </div> </div> <% end %> diff --git a/app/views/user/scomments/_scomment.html.erb b/app/views/user/scomments/_scomment.html.erb index 8ae4e8f..9bedb50 100644 --- a/app/views/user/scomments/_scomment.html.erb +++ b/app/views/user/scomments/_scomment.html.erb @@ -1,15 +1,19 @@ <% user = scomment.user %> <% comment_divid = "scomment_#{scomment.id}" %> +<% if scomment_viewable(scomment,current_user) %> <div id=<%= comment_divid %> class='comment-box'> + <% if scomment.whisper %> + <div class='whisper'><strong>whisper</strong></div> + <% end %> <%= user_icon(user) %> <strong><%= link_to_user user %></strong> <span class="comment-box-tiny"><%= ftime scomment.created_at %></span><br/> <%= scomment.content %><br/> <% if current_user == user %> <%= link_to_remote 'delete', :complete => "$('#{comment_divid}').remove();", :url => status_comment_url(scomment.status, scomment), :method => :delete %> <% else %> - <%= link_to_function 'comment', "$('scomment_content_#{scomment.status.id}').value='reply to #{user.login}: '; $('scomment_content_#{scomment.status.id}').focus();" %> + <%= link_to_function 'comment', "$('scomment_receiver_#{scomment.status.id}').value=#{user.id};$('scomment_content_#{scomment.status.id}').value='reply to #{user.login}: '; $('scomment_content_#{scomment.status.id}').focus();" %> <% end %> </div> - +<% end %> diff --git a/app/models/.bcomment.rb.swp b/app/views/user/status_feeds/.index.html.erb.swp similarity index 92% rename from app/models/.bcomment.rb.swp rename to app/views/user/status_feeds/.index.html.erb.swp index 38bcced..6c3892b 100644 Binary files a/app/models/.bcomment.rb.swp and b/app/views/user/status_feeds/.index.html.erb.swp differ diff --git a/app/views/user/status_feeds/_sfeed.html.erb b/app/views/user/status_feeds/_sfeed.html.erb index d99e15d..4a316d3 100644 --- a/app/views/user/status_feeds/_sfeed.html.erb +++ b/app/views/user/status_feeds/_sfeed.html.erb @@ -1,15 +1,18 @@ <div class='blog-feed'> <%= user_icon(sfeed.user) %> <%= link_to_user sfeed.user %> - <span class='blog-feed-tiny'><%= distance_of_time_in_words_to_now sfeed.created_at %> ago</span><br/> + <span class='blog-feed-tiny'><%= distance_of_time_in_words_to_now sfeed.created_at %> ago</span> + <% if @more %> + <span class='blog-feed-tiny'><%= link_to '(more..)', user_statuses_url(sfeed.user) %></span> + <% end %> <br/> <%= sfeed.content %> <div style="float:right"> <%= link_to_function "comment", "unfold_scomments(#{sfeed.id})", :id => "unfold_scomments_#{sfeed.id}" %> <%= link_to_function "fold", "fold_scomments(#{sfeed.id})", :style => "display:none", :id => "fold_scomments_#{sfeed.id}" %> (<%= sfeed.comments_count %>) </div> <div id='scomments_<%= sfeed.id%>' style="margin-left:75px;float:left"></div> <div id='scomments_form_<%= sfeed.id%>' style="margin-left:75px;float:left;display:none"> <%= render :partial => 'user/scomments/new', :locals => {:status => sfeed} %> </div> </div> diff --git a/app/views/user/status_feeds/index.html.erb b/app/views/user/status_feeds/index.html.erb new file mode 100644 index 0000000..d3f02c5 --- /dev/null +++ b/app/views/user/status_feeds/index.html.erb @@ -0,0 +1,11 @@ +<% content_for :left do %> +<%= render :partial => 'user/statuses/status_menu' %> +<% end %> + +<div id='feeds'> +<% @more = 1 %> +<%= render :partial => 'sfeed', :collection => @statuses %> +</div> +<div id='more_feeds'> +<%= link_to_remote "More..", :url => get_user_status_feeds_url(@user, :idx => @idx), :method => :get %> +</div> diff --git a/app/views/user/statuses/_new.html.erb b/app/views/user/statuses/_new.html.erb index d5e249a..93cc474 100644 --- a/app/views/user/statuses/_new.html.erb +++ b/app/views/user/statuses/_new.html.erb @@ -1,15 +1,15 @@ <div class='status'> <%= user_icon @user %> <div id='form'> - <% form_remote_for :status, :url => user_statuses_url(@user) do |form| %> + <% form_remote_for :status, :url => user_statuses_url(@user, :home => 1) do |form| %> <%= form.text_area 'content', :cols => 50, :rows => 3, :style => "margin:3px 6px" %> <%= image_submit_tag 'submit.gif', :style => "margin-right:0px" %><br/> <div id='latest_status' style="float:left;margin-left:6px"> <% unless @user.latest_status.nil? %> <%= distance_of_time_in_words_to_now(@user.latest_status.created_at) %> ago: <%= @user.latest_status.content %> <% end %> </div><br/> <% end %> </div> </div> diff --git a/app/views/user/statuses/_show.html.erb b/app/views/user/statuses/_show.html.erb new file mode 100644 index 0000000..dcd0fcd --- /dev/null +++ b/app/views/user/statuses/_show.html.erb @@ -0,0 +1,13 @@ +<div class='status-show'> + <h3> <%= @user.login %> Latest Status <span class='status-show-tiny'><%= distance_of_time_in_words_to_now @user.latest_status.created_at %> ago</span><%= link_to_function 'fold', "$('latest_status').toggle();if(this.innerHTML == 'unfold') this.update('fold'); else this.update('unfold');", :class => 'hide-all'%></h3> + <div class='content' id='latest_status'> + <% unless @user.latest_status.blank? %> + <%= @user.latest_status.content %> + <% else %> + <span style="color:grey">nothing... a lazy boy</span> + <% end %> + </div> + <div class='view-all'> + <%= link_to 'more..', user_statuses_url(@user) %> + </div> +</div> diff --git a/app/views/user/statuses/_status.html.erb b/app/views/user/statuses/_status.html.erb new file mode 100644 index 0000000..cb2f40c --- /dev/null +++ b/app/views/user/statuses/_status.html.erb @@ -0,0 +1,21 @@ +<div class='blog-feed' id=<%= "status_#{status.id}"%>> + <% if @user == current_user %> + <div style="float:right"> + <%= link_to_remote "x", :after => "$('status_#{status.id}').remove();", :url => user_status_url(@user.id, status), :confirm => 'are you sure?', :method => :delete %> + </div> + <% end %> + <%= user_icon(status.user) %> + <%= link_to_user status.user %> + <span class='blog-feed-tiny'><%= distance_of_time_in_words_to_now status.created_at %> ago</span><br/> + <%= status.content %> + <div style="float:right"> + <%= link_to_function "comment", "unfold_scomments(#{status.id})", :id => "unfold_scomments_#{status.id}" %> + <%= link_to_function "fold", "fold_scomments(#{status.id})", :style => "display:none", :id => "fold_scomments_#{status.id}" %> + (<%= status.comments_count %>) + </div> + <div id='scomments_<%= status.id%>' style="margin-left:75px;float:left"></div> + <div id='scomments_form_<%= status.id%>' style="margin-left:75px;float:left;display:none"> + <%= render :partial => 'user/scomments/new', :locals => {:status => status} %> + </div> +</div> + diff --git a/app/views/user/statuses/_status_menu.html.erb b/app/views/user/statuses/_status_menu.html.erb new file mode 100644 index 0000000..3c50c7a --- /dev/null +++ b/app/views/user/statuses/_status_menu.html.erb @@ -0,0 +1,12 @@ +<% owner = (@user == current_user)? 'my' : "#{@user.login}'s" %> +<div class='fby'> + <h3>Icon: <%= link_to_function 'fold', "$('side_icon').toggle();if(this.innerHTML == 'fold') this.update('unfold'); else this.update('fold');", :class => 'hide-all'%></h3> + <div id='side_icon'> + <p id='user_icon' style="text-align:center"><%= user_icon(@user, :medium) %></p> + <li><%= image_tag 'status.gif'%><%= link_to "#{owner} statuses", user_statuses_url(@user) %></li> + <% if @user == current_user %> + <li><%= image_tag 'blog.gif' %><%= link_to "my friends statuses", user_status_feeds_url(@user) %></li> + <% end %> + </div> +</div> + diff --git a/app/views/user/statuses/index.html.erb b/app/views/user/statuses/index.html.erb new file mode 100644 index 0000000..0ae8d0a --- /dev/null +++ b/app/views/user/statuses/index.html.erb @@ -0,0 +1,14 @@ +<% content_for :left do %> +<%= render :partial => 'status_menu' %> +<% end %> + +<% if @user == current_user %> +<% form_remote_for :status, :url => user_statuses_url(@user, :home => 0) do |form| %> + <%= form.text_area 'content', :cols => 50, :rows => 3, :style => "margin:3px 6px" %> + <%= image_submit_tag 'submit.gif', :style => "margin-right:0px" %><br/> +<% end %> +<% end %> + +<div id='statuses'> +<%= render :partial => 'status', :collection => @statuses %> +</div> diff --git a/app/views/user/vcomment_notifications/_vnotification.html.erb b/app/views/user/vcomment_notifications/_vnotification.html.erb new file mode 100644 index 0000000..0dff05c --- /dev/null +++ b/app/views/user/vcomment_notifications/_vnotification.html.erb @@ -0,0 +1,14 @@ +<% video = vnotification.comment.video %> +<% owner = video.user %> +<% commentor = vnotification.comment.user %> +<li id="vnotification_<%= vnotification.id%>" type='video' type_id='<%= video.id %>' notification_id='<%= vnotification.id %>'> + <span class='notification-tiny'><%= ftime4 vnotification.created_at %></span> + <% if delete %> + <%= link_to_function 'X', "read_notification('video', '#{video.id}', #{@user.id}, 1);", :style => "float:right;margin-right:5px" %> + <% end %> + <% style = (vnotification.read)? "font-weight: normal;" : "font-weight: bold;" %> + <span style='<%= style %>'> + <%= link_to_user commentor %> replied to you in video <%= link_to_function (truncate video.title, 20), "read_notification('video', '#{video.id}', #{@user.id}, #{delete ? 1 : 0});window.open('#{user_video_url(owner, video)}');", :popup => true %> + </span> +</li> + diff --git a/app/views/user/vcomments/_new.html.erb b/app/views/user/vcomments/_new.html.erb index 754410a..3de3631 100644 --- a/app/views/user/vcomments/_new.html.erb +++ b/app/views/user/vcomments/_new.html.erb @@ -1,15 +1,16 @@ <% form_remote_for :vcomment, :position => :bottom, :update => "vcomments_#{video.id}", :complete => "$('vcomment_content_#{video.id}').value = '';", :url => video_comments_url(video) do |form| %> + <p style="display:none"><%= text_field_tag 'vcomment[receiver_id]', video.user_id, :id => "vcomment_receiver_#{video.id}" %></p> <div class='comment-box'> <%= user_icon(current_user) %> <%= text_area_tag 'vcomment[content]', '', :cols => 40, :rows => 3, :id => "vcomment_content_#{video.id}" %><br/> <div style="float:right; margin-right:15px"> <%= form.label "whisper?" %><%= form.check_box 'whisper' %> <%= form.submit 'comment' %> </div> </div> <% end %> diff --git a/app/views/user/vcomments/_vcomment.html.erb b/app/views/user/vcomments/_vcomment.html.erb index d2c61b8..8d73e38 100644 --- a/app/views/user/vcomments/_vcomment.html.erb +++ b/app/views/user/vcomments/_vcomment.html.erb @@ -1,14 +1,19 @@ <% user = vcomment.user %> -<% comment_divid = "comment_#{vcomment.id}" %> +<% comment_divid = "vcomment_#{vcomment.id}" %> +<% if vcomment_viewable(vcomment, current_user) %> <div id=<%= comment_divid %> class='comment-box'> + <% if vcomment.whisper %> + <div class='whisper'><strong>whisper</strong></div> + <% end %> <%= user_icon(user) %> <strong><%= link_to_user user %></strong> <span class="comment-box-tiny"><%= ftime vcomment.created_at %></span><br/> <%= vcomment.content %><br/> <% if current_user == user %> <%= link_to_remote 'delete', :complete => "$('#{comment_divid}').remove();", :url => video_comment_url(vcomment.video, vcomment), :method => :delete %> <% else %> - <%= link_to_function 'comment', "$('vcomment_content_#{vcomment.video.id}').value='reply to #{user.login}: '; $('vcomment_content_#{vcomment.video.id}').focus();" %> + <%= link_to_function 'comment', "$('vcomment_receiver_#{vcomment.video.id}').value=#{user.id};$('vcomment_content_#{vcomment.video.id}').value='reply to #{user.login}: '; $('vcomment_content_#{vcomment.video.id}').focus();" %> <% end %> </div> +<% end %> diff --git a/app/views/user/video_feeds/_vfeed.html.erb b/app/views/user/video_feeds/_vfeed.html.erb index 876438c..dc62a1d 100644 --- a/app/views/user/video_feeds/_vfeed.html.erb +++ b/app/views/user/video_feeds/_vfeed.html.erb @@ -1,23 +1,23 @@ <div class='video-feed'> <%= user_icon(vfeed.user) %> <h3><%= link_to_user vfeed.user %></h3> published <span class='video-feed-tiny'><%= distance_of_time_in_words_to_now vfeed.created_at %> ago</span><br/> <div id='video_<%= vfeed.id %>' style="margin-left:75px"> <%= image_tag 'blank_video.png', :onclick => "play_video(#{vfeed.id}, '#{vfeed.link}');$('video_title_#{vfeed.id}').setStyle({float:'left', marginLeft: '75px'});" %> </div> <div id='video_title_<%= vfeed.id %>'> - <%= link_to vfeed.title, user_video_url(@user, vfeed) %><br/> + <%= link_to vfeed.title, user_video_url(vfeed.user, vfeed) %><br/> <%= link_to vfeed.url, vfeed.url, :popup => true %> </div> <div style="float:right"> <%= link_to_function "comment", "unfold_vcomments(#{vfeed.id})", :id => "unfold_vcomments_#{vfeed.id}" %> <%= link_to_function "fold", "fold_vcomments(#{vfeed.id})", :style => "display:none", :id => "fold_vcomments_#{vfeed.id}" %> (<%= vfeed.comments_count %>) | <%= link_to_remote 'dig', :url => video_digs_url(vfeed), :method => :post%>(<%= label_tag nil, vfeed.digs_count, :id => "digs_count_#{vfeed.id}" %>) </div> <div id='vcomments_<%=vfeed.id%>' style="margin-left:75px;float:left"></div> <div id='vcomments_form_<%= vfeed.id%>' style="margin-left:75px;float:left;display:none"> <%= render :partial => 'user/vcomments/new', :locals => {:video => vfeed} %> </div> </div> diff --git a/config/.routes.rb.swp b/config/.routes.rb.swp new file mode 100644 index 0000000..a0e918a Binary files /dev/null and b/config/.routes.rb.swp differ diff --git a/config/environment.rb b/config/environment.rb index 3fe46a5..7610beb 100755 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,50 +1,50 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') require 'diggable' require 'taggable' require 'commentable' require 'resource_feeder' require 'migration_helper' Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'Beijing' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de - config.active_record.observers = [:photo_observer, :bcomment_observer]#:user_observer] + config.active_record.observers = [:photo_observer, :comment_observer]#:user_observer] end require 'will_paginate' diff --git a/config/routes.rb b/config/routes.rb index a90c5d8..3bfa4d6 100755 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,208 +1,229 @@ ActionController::Routing::Routes.draw do |map| map.resources :sessions map.root :controller => 'sessions', :action => 'new' map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate' map.forgot_password '/forgot_password', :controller => 'passwords', :action => 'new' map.reset_password '/reset_password/:password_reset_code', :controller => 'passwords', :action => 'edit' map.change_password '/change_password', :controller => 'accounts', :action => 'edit' map.upload_image '/upload_images', :controller => 'user/blog_images', :action => 'upload' map.namespace(:admin) do |admin| admin.resources :videos admin.resources :vtags admin.resources :vdigs admin.resources :vcomments admin.resources :blogs admin.resources :btags admin.resources :bdigs admin.resources :bcomments admin.resources :albums admin.resources :photos admin.resources :ptags admin.resources :pdigs admin.resources :pcomments admin.resources :pages admin.resources :statuses admin.resources :scomments admin.resources :wall_messages admin.resources :mails admin.resources :friendships admin.resources :game_characters admin.resources :game_races admin.resources :game_professions admin.resources :game_servers admin.resources :game_areas admin.resources :games end map.resources :users, :member => {:enable => :put} do |users| users.resource :personal, :controller => 'user/personal' users.resource :profile, :controller => 'user/profile' users.resource :basic_info, :controller => 'user/basic_info' users.resource :contact_info, :controller => 'user/contact_info' users.resources :icons, :controller => 'user/icons', :member => {:confirm_destroy => :get, :set => :post} users.resources :characters, :controller => 'user/characters', :member => {:confirm_destroy => :get} users.resources :wall_messages, :controller => 'user/wall_messages' users.resources :mails, :controller => 'user/mailboxes', :member => {:reply => :post}, :collection => {:read_multiple => :put, :unread_multiple => :put, :destroy_multiple => :delete} users.resources :friends, :controller => 'user/friends', :collection => {:search => :get} users.resources :visitor_records, :controller => 'user/visitor_records' users.resources :statuses, :controller => 'user/statuses' users.resources :status_feeds, :controller => 'user/status_feeds', :collection => {:get => :get} users.resources :blogs, :controller => 'user/blogs', :member => {:confirm_destroy => :get}, :collection => {:destroy_multiple => :delete} users.resources :blog_feeds, :controller => 'user/blog_feeds', :collection => {:get => :get} users.resources :tagged_blogs, :controller => 'user/tagged_blogs' users.resources :albums, :controller => 'user/albums', :member => {:confirm_destroy => :get} users.resources :album_feeds, :controller => 'user/album_feeds', :collection => {:get => :get} users.resources :tagged_photos, :controller => 'user/tagged_photos' users.resources :videos, :controller => 'user/videos', :member => {:confirm_destroy => :get} users.resources :video_feeds, :controller => 'user/video_feeds', :collection => {:get => :get} users.resources :tagged_videos, :controller => 'user/tagged_videos' users.resources :resource_feeds, :controller => 'user/resource_feeds', :collection => {:get => :get} + + users.resources :bcomment_notifications, + :controller => 'user/bcomment_notifications', + :collection => {:read_multiple => :post} + + users.resources :scomment_notifications, + :controller => 'user/scomment_notifications', + :collection => {:read_multiple => :post} + + users.resources :pcomment_notifications, + :controller => 'user/pcomment_notifications', + :collection => {:read_multiple => :post} + + users.resources :vcomment_notifications, + :controller => 'user/vcomment_notifications', + :collection => {:read_multiple => :post} + + users.resources :comment_notifications, + :controller => 'user/comment_notifications', + :collection => {:read_multiple => :post} + end map.resources :statuses do |statuses| statuses.resources :comments, :controller => 'user/scomments' end map.resources :blogs do |blogs| blogs.resources :comments, :controller => 'user/bcomments' blogs.resources :tags, :controller => 'user/btags' blogs.resources :digs, :controller => 'user/bdigs' end map.resources :photos do |photos| photos.resources :comments, :controller => 'user/pcomments' photos.resources :tags, :controller => 'user/ptags' photos.resources :digs, :controller => 'user/pdigs' end map.resources :albums do |albums| albums.resources :photos, :controller => 'user/photos', :member => {:confirm_destroy => :get, :cover => :post}, :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} end map.resources :videos do |videos| videos.resources :comments, :controller => 'user/vcomments' videos.resources :tags, :controller => 'user/vtags' videos.resources :digs, :controller => 'user/vdigs' end map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090826033843_create_bcomment_notifications.rb b/db/migrate/20090826033843_create_bcomment_notifications.rb index 000bb7a..123b669 100644 --- a/db/migrate/20090826033843_create_bcomment_notifications.rb +++ b/db/migrate/20090826033843_create_bcomment_notifications.rb @@ -1,14 +1,14 @@ class CreateBcommentNotifications < ActiveRecord::Migration def self.up create_table :bcomment_notifications, :force => true do |t| t.integer :user_id - t.integer :commentor_id - t.integer :blog_id + t.integer :comment_id + t.boolean :read, :default => false t.timestamps end end def self.down drop_table :bcomment_notifications end end diff --git a/db/migrate/20090826063405_create_scomment_notifications.rb b/db/migrate/20090826063405_create_scomment_notifications.rb new file mode 100644 index 0000000..5dc4e56 --- /dev/null +++ b/db/migrate/20090826063405_create_scomment_notifications.rb @@ -0,0 +1,15 @@ +class CreateScommentNotifications < ActiveRecord::Migration + def self.up + create_table :scomment_notifications do |t| + t.integer :user_id + t.integer :commentor_id + t.integer :comment_id + t.boolean :read, :default => false + t.timestamps + end + end + + def self.down + drop_table :scomment_notifications + end +end diff --git a/db/migrate/20090826063416_create_vcomment_notifications.rb b/db/migrate/20090826063416_create_vcomment_notifications.rb new file mode 100644 index 0000000..b96b87a --- /dev/null +++ b/db/migrate/20090826063416_create_vcomment_notifications.rb @@ -0,0 +1,15 @@ +class CreateVcommentNotifications < ActiveRecord::Migration + def self.up + create_table :vcomment_notifications do |t| + t.integer :user_id + t.integer :commentor_id + t.integer :comment_id + t.boolean :read, :default => false + t.timestamps + end + end + + def self.down + drop_table :vcomment_notifications + end +end diff --git a/db/migrate/20090826063423_create_pcomment_notifications.rb b/db/migrate/20090826063423_create_pcomment_notifications.rb new file mode 100644 index 0000000..d0b65ea --- /dev/null +++ b/db/migrate/20090826063423_create_pcomment_notifications.rb @@ -0,0 +1,15 @@ +class CreatePcommentNotifications < ActiveRecord::Migration + def self.up + create_table :pcomment_notifications do |t| + t.integer :user_id + t.integer :commentor_id + t.integer :comment_id + t.boolean :read, :default => false + t.timestamps + end + end + + def self.down + drop_table :pcomment_notifications + end +end diff --git a/db/schema.rb b/db/schema.rb index f038f6c..a4094ff 100755 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,356 +1,383 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090826033843) do +ActiveRecord::Schema.define(:version => 20090826063423) do create_table "admin_pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "albums", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "photos_count", :default => 0 t.string "title" t.text "description" t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomment_notifications", :force => true do |t| t.integer "user_id" - t.integer "commentor_id" - t.integer "blog_id" + t.integer "comment_id" + t.boolean "read", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "bcomments", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "bdigs", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "blogs", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title", :limit => 64 t.text "content", :limit => 16777215 t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.boolean "draft", :default => true t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "btags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "cities", :force => true do |t| t.string "name" t.integer "city_id" t.datetime "created_at" t.datetime "updated_at" end create_table "countries", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "event_wall_messages", :force => true do |t| t.integer "activity_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "friendships", :force => true do |t| t.integer "user_id" t.integer "friend_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_areas", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_characters", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "server_id" t.integer "area_id" t.integer "profession_id" t.integer "race_id" t.string "name" t.integer "level" t.boolean "playing" t.datetime "created_at" t.datetime "updated_at" end create_table "game_professions", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_races", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_servers", :force => true do |t| t.string "name" t.string "ip" t.integer "game_id" t.integer "area_id" t.datetime "created_at" t.datetime "updated_at" end create_table "games", :force => true do |t| t.string "name" t.string "company" t.datetime "sale_date" t.text "description" t.boolean "no_areas", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "mails", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.boolean "delete_by_sender", :default => false t.boolean "delete_by_receiver", :default => false t.boolean "read_by_sender", :default => true t.boolean "read_by_receiver", :default => false t.string "title" t.text "content" t.integer "parent_id" t.datetime "created_at" t.datetime "updated_at" end create_table "pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end + create_table "pcomment_notifications", :force => true do |t| + t.integer "user_id" + t.integer "commentor_id" + t.integer "comment_id" + t.boolean "read", :default => false + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "pcomments", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "pdigs", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.datetime "created_at" t.datetime "updated_at" end create_table "permissions", :force => true do |t| t.string "user_id" t.string "role_id" t.datetime "created_at" t.datetime "updated_at" end create_table "photos", :force => true do |t| t.integer "digs_count", :default => 0 t.integer "tags_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "album_id" t.boolean "cover", :default => false t.integer "user_id" t.boolean "current_icon", :default => false t.text "notation" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "provinces", :force => true do |t| t.string "name" t.integer "country_id" t.datetime "created_at" t.datetime "updated_at" end create_table "ptags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "photo_id" t.integer "x" t.integer "y" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "roles", :force => true do |t| t.string "name", :null => false t.datetime "created_at" t.datetime "updated_at" end + create_table "scomment_notifications", :force => true do |t| + t.integer "user_id" + t.integer "commentor_id" + t.integer "comment_id" + t.boolean "read", :default => false + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "scomments", :force => true do |t| t.integer "user_id" t.integer "status_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "statuses", :force => true do |t| t.integer "user_id" t.text "content" t.integer "comments_count", :default => 0 t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :limit => 64 t.string "email", :limit => 128 t.string "crypted_password", :limit => 64 t.string "salt", :limit => 40 t.string "gender" t.boolean "enabled", :default => true t.string "remember_token" t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "password_reset_code", :limit => 40 t.integer "country_id" t.integer "province_id" t.integer "city_id" t.integer "qq" t.integer "mobile" t.string "website" t.datetime "birthday" t.datetime "created_at" t.datetime "updated_at" end + create_table "vcomment_notifications", :force => true do |t| + t.integer "user_id" + t.integer "commentor_id" + t.integer "comment_id" + t.boolean "read", :default => false + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "vcomments", :force => true do |t| t.integer "user_id" t.integer "video_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "vdigs", :force => true do |t| t.integer "user_id" t.integer "video_id" t.datetime "created_at" t.datetime "updated_at" end create_table "videos", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title" t.string "url" t.text "link" t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.string "privilege", :default => "all" t.datetime "created_at" t.datetime "updated_at" t.integer "position" end create_table "visitor_records", :force => true do |t| t.integer "user_id" t.integer "visitor_id" t.boolean "register", :default => true t.datetime "created_at" t.datetime "updated_at" end create_table "vtags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "video_id" t.datetime "created_at" t.datetime "updated_at" end create_table "wall_messages", :force => true do |t| t.integer "user_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end end diff --git a/public/javascripts/comment_notification.js b/public/javascripts/comment_notification.js new file mode 100644 index 0000000..6898953 --- /dev/null +++ b/public/javascripts/comment_notification.js @@ -0,0 +1,34 @@ +function read_notification(type, type_id, user_id, partial){ + var lis = $('notifications').childElements(); + var length = lis.length; + var related_items = []; + + // get all items with same type and type_id + for(var i=0;i<length;i++){ + if(lis[i].readAttribute('type') == type && lis[i].readAttribute('type_id') == type_id){ + related_items.push(lis[i]); + } + } + + // send ajax request to set these notifications as read + length = related_items.length; + params = ""; + for(var i=0;i<length;i++){ + params += "ids[]=" + related_items[i].readAttribute('notification_id') + "&"; + } + new Ajax.Request('/users/'+user_id+'/'+type[0]+'comment_notifications/read_multiple?' + params, { + method: 'post', + onSuccess: function(transport){ + for(var i=0;i<length;i++){ + if(!partial){ + var children = related_items[i].childElements(); + var size = children.length; + children[size-1].style.fontWeight = ''; + }else{ + related_items[i].remove(); + } + } + } + }); +} + diff --git a/public/photos/0000/0005/14.jpg b/public/photos/0000/0005/14.jpg new file mode 100644 index 0000000..d33d2c1 Binary files /dev/null and b/public/photos/0000/0005/14.jpg differ diff --git a/public/photos/0000/0005/14_large.jpg b/public/photos/0000/0005/14_large.jpg new file mode 100644 index 0000000..3a537de Binary files /dev/null and b/public/photos/0000/0005/14_large.jpg differ diff --git a/public/photos/0000/0005/14_medium.jpg b/public/photos/0000/0005/14_medium.jpg new file mode 100644 index 0000000..7199e9a Binary files /dev/null and b/public/photos/0000/0005/14_medium.jpg differ diff --git a/public/photos/0000/0005/14_small.jpg b/public/photos/0000/0005/14_small.jpg new file mode 100644 index 0000000..cb7be73 Binary files /dev/null and b/public/photos/0000/0005/14_small.jpg differ diff --git a/public/stylesheets/.user.css.swp b/public/stylesheets/.user.css.swp new file mode 100644 index 0000000..df5c064 Binary files /dev/null and b/public/stylesheets/.user.css.swp differ diff --git a/public/stylesheets/user.css b/public/stylesheets/user.css index 030d182..45629e2 100755 --- a/public/stylesheets/user.css +++ b/public/stylesheets/user.css @@ -1,588 +1,691 @@ body{ font-family: verdana, arial, helvetica, sans-serif; font-size: 13px; line-height: 18px; margin: 0px; padding: 0px; } #header { width:1000px; height:50px; margin:0 auto; } #container { width:1000px; margin:0 auto; } #footer { width:1000px; height:60px; margin:0 auto; text-align: center; } #left { width:200px; height:600px; float:left; } #middle { width:600px; height:800px; float:left; } #right { width:200px; height:600px; float:left; } .comment-box { float: left; font-size:12px; font-weight:normal; background: #f2f3f8; color:#000; width: 400px; padding: 5px; border: 1px solid #B7B7B7; } .comment-box img { float:left; border:0px; margin-bottom:2px; margin-top:2px; margin-left:2px; margin-right:10px; background:white; width: 55px; } .comment-box H3 { font-size:10px; background: #e9e9e9; color:#333; padding: 2px; margin-bottom: 5px; margin-top: 0px; } .comment-box-tiny { font-size:9px; color: #777; } .comment-box a { color: #3B5998; text-decoration:none; } .comment-box .operation{ margin-left: 340px; } .comment-box .content { margin-left: 66px; } .fb2 { padding: 5px; color: #FFFFFF; background: #3B5998; } .fb2 a { color:#FFFFFF; text-decoration: none; outline-style: none; padding: 5px; font-size:16px; } .fb2 a:hover { background: #6D84B4; padding: 5px; text-decoration: none; font-weight: bold; } .blog-feed { font-size:12px; font-weight:normal; color:#000; -width: 550px; +width: 580px; padding: 5px; border-bottom: 1px solid #B7B7B7; float: left; } +.blog-feed .comments { +float:left; +margin-left:75px; +} + .blog-feed img { float:left; border:0px; margin-bottom:2px; margin-top:2px; margin-left:2px; margin-right:10px; background:white; width: 65px; } .blog-feed H3 { font-size:10px; background: #e9e9e9; color:#333; padding: 2px; margin-bottom: 5px; margin-top: 0px; } .blog-feed-tiny { font-size:9px; color: #777; } .blog-feed a { color: #3B5998; text-decoration:none; } .video-feed { font-size:12px; font-weight:normal; color:#000; -width: 550px; +width: 580px; padding: 5px; border-bottom: 1px solid #B7B7B7; float: left; } .video-feed img { float:left; border:0px; margin-bottom:2px; margin-top:2px; margin-left:2px; margin-right:10px; background:white; width: 65px; } .video-feed H3 { font-size:10px; background: #e9e9e9; color:#333; padding: 2px; margin-bottom: 5px; margin-top: 0px; } .video-feed-tiny { font-size:9px; color: #777; } .video-feed a { color: #3B5998; text-decoration:none; } .video-feed .comment-dig{ float:right; } .fby { width:180px; border:1px solid #eee; } +.fby-tiny { +font-size:9px; +color; #777; +} + .fby a { color: #3B5998; border-bottom:1px thin #ccc; font-weight: 12px; } .fby a:hover { text-decoration:underline; } .fby H3 { font-size:11px; color:#3B5998; background:#d8dfea; border-top: 1px solid #3B5998; padding: 3px 10px; margin: 0px; } .fby H3:hover { background:#cfd7e4; border-top: 1px solid #3B5998; } .fby li { font-size:11px; font-weight: normal; margin-left: 5px; padding: 3px 0px; list-style:none; border-bottom:1px solid #ccc; width: 175px; } .fby img { border:0; } .fby .view-all{ text-align:right; margin-right: 2px; margin-bottom: 2px; } .status { -width: 550px; +width: 580px; } .status img { float:left; width: 65px; padding:5px; border:0px; } .status form { background: #f2f3f8; margin-left: 90px; } .visitors { width: 200px; border:1px solid #eee; } .visitors .view-all { text-align:right; font-size:14px; text-decoration:none; margin-right: 10px; margin-bottom: 5px; } .visitors h3 { font-size:11px; color:#3B5998; background:#d8dfea; border-top: 1px solid #3B5998; padding: 3px 10px; margin: 0px; } .visitors .record { width: 55px; padding: 5px; padding-bottom: 10px; padding-top: 10px; } .visitors .record img{ width: 45px; border: 0px; } .game-character label{ width: 125px; float: left; } .fby-submenu li { float:left; margin-left:30px; width:145px; } .blog { font-size:12px; font-weight:normal; color:#000; width: 600px; padding-top: 5px; } .blog-tags { font-size:13px; } .blog-title{ float:left; width: 600px; font-size:15px; color:#3B5998; background:#d8dfea; border-top: 1px solid #3B5998; margin: 0px; } .blog-title a { text-decoration: none; } .blog-tiny { float:left; font-size:9px; color: #777; } .blog-category { float:left; font-size: 10px; } .blog-operation { font-size: 10px; margin-right: 5px; float: right; } .blog-menus { width: 600px; font-size: 11px; border-top: 1px solid #3B5998; text-align: right; } .draft { font-size: 12px; width: 600px; padding-top: 10px; padding-bottom: 10px; } .draft table { border: 0px; } .draft th { background:#d8dfea; border-top: 1px solid #3B5998; border-bottom: 1px solid #3B5998; } .draft tr { border-bottom: 1px solid #3B5998; } .draft-select { width: 100px; text-align:center; } .draft-title { width: 350px; text-align:center; } .draft-updated-at { width: 150px; text-align:center; } .side-albums { width: 180px; } .side-albums a { color: #3B5998; border-bottom:1px thin #ccc; font-weight: 12px; } .side-albums a:hover { text-decoration:underline; } .side-albums H3 { font-size:11px; color:#3B5998; background:#d8dfea; border-top: 1px solid #3B5998; padding: 3px 10px; margin: 0px; } .side-albums H3:hover { background:#cfd7e4; border-top: 1px solid #3B5998; } .side-albums li { font-size:11px; font-weight: normal; margin-left: 5px; padding: 3px 0px; list-style:none; border-bottom:1px solid #ccc; width: 175px; } .side-album-cover { float:left; text-align:center; } .side-albums img { border: 0px; width: 60px; padding: 10px; } .side-albums-tiny { font-size: 10px; color: #777; } .show-header { width: 600px; float: left; } .show-header img { float: left; margin-right: 10px; } .prev-next{ text-align: right; } .album-covers { background: #f2f3f8; margin-top: 10px; float: left; border-top: 1px solid #B7B7B7; } .album-cover { width: 600px; background: #fff; font-size: 12px; float: left; padding: 10px; border: 1px solid #B7B7B7; margin-top: 10px; margin-left: 10px; margin-right: 10px; } .album-cover img { float: left; border: 1px solid #B7B7B7; margin-right: 10px; } .album { width: 600px; background: #f2f3f8; font-size: 12px; float: left; padding: 10px; border-top: 1px solid #B7B7B7; } .album img { float: left; background: #fff; border: 1px solid #B7B7B7; margin-left: 10px; margin-right: 10px; margin-top: 10px; width: 120px; } .video { font-size:12px; font-weight:normal; color:#000; width: 600px; padding: 5px; float: left; border-bottom: 1px solid #3B5998; } .video img { float:left; border:0px; margin:5px; background:white; width: 90px; } .video-header { font-size:10px; background:#d8dfea; border-top: 1px solid #3B5998; color:#333; padding: 2px; width: 600px; float: left; } .video-tags { font-size:13px; } .video-header a { text-decoration: none; } .video-tiny { float:left; font-size:9px; color: #777; } .video-body { text-align: center; margin: 15px; } .video-category { float:left; font-size: 10px; } .video-operation { float: right; margin-right: 5px; font-size: 10px; } .video-menus { font-size: 11px; float: right; } .yellow-info { color: #333; background:#fff9d7; border: 1px solid #e2c822; width: 400px; padding: 10px; margin-top: 10px; margin-bottom: 10px; } .yellow-info img { } .red-error { color: #333; background:#ffebe8; border: 1px solid #dd3c10; width: 400px; padding: 10px; margin-top: 10px; margin-bottom: 10px; } + +.comment-notification { +width:580px; +margin-top: 15px; +margin-bottom: 10px; +border:1px solid #eee; +background: white; +} + +.comment-notification h3 { +font-size:11px; +color:#3B5998; +background:#d8dfea; +border-top: 1px solid #3B5998; +padding: 3px 10px; +margin: 0px; +} + +.comment-notification li { +font-size:11px; +font-weight: normal; +margin-left: 5px; +padding: 3px; +list-style:none; +border-bottom:1px solid #ccc; +} + +.comment-notification .view-all{ +text-align:right; +margin-right: 2px; +margin-bottom: 2px; +} + +.notification-tiny { +float:right; +font-size:9px; +color: #777; +} + +.notification-board { +padding-left:10px; +padding-right:10px; +padding-bottom:10px; +background: #f2f3f8; +margin-top: 10px; +border-top: 1px solid #B7B7B7; +} + +.whisper { +float:right; +font-size:9px; +} + +.status-show { +width:580px; +margin-top: 15px; +margin-bottom: 10px; +border:1px solid #eee; +background: white; +} + +.status-show h3 { +font-size:11px; +color:#3B5998; +background:#d8dfea; +border-top: 1px solid #3B5998; +padding: 3px 10px; +margin: 0px; +} + +.status-show li { +font-size:11px; +font-weight: normal; +margin-left: 5px; +padding: 3px; +list-style:none; +border-bottom:1px solid #ccc; +} + +.status-show .view-all{ +text-align:right; +margin-right: 5px; +margin-bottom: 2px; +} + +.status-show-tiny { +font-size:9px; +color: #777; +} + +.status-show .content { +margin-left:5px; +} diff --git a/test/fixtures/pcomment_notifications.yml b/test/fixtures/pcomment_notifications.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/pcomment_notifications.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/fixtures/scomment_notifications.yml b/test/fixtures/scomment_notifications.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/scomment_notifications.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/fixtures/vcomment_notifications.yml b/test/fixtures/vcomment_notifications.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/vcomment_notifications.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/functional/user/bcomment_notifications_controller_test.rb b/test/functional/user/bcomment_notifications_controller_test.rb new file mode 100644 index 0000000..36fc308 --- /dev/null +++ b/test/functional/user/bcomment_notifications_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class User::BcommentNotificationsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/user/comment_notifications_controller_test.rb b/test/functional/user/comment_notifications_controller_test.rb new file mode 100644 index 0000000..2a0ed5e --- /dev/null +++ b/test/functional/user/comment_notifications_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class User::CommentNotificationsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/user/pcomment_notifications_controller_test.rb b/test/functional/user/pcomment_notifications_controller_test.rb new file mode 100644 index 0000000..b3a2288 --- /dev/null +++ b/test/functional/user/pcomment_notifications_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class User::PcommentNotificationsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/user/scomment_notifications_controller_test.rb b/test/functional/user/scomment_notifications_controller_test.rb new file mode 100644 index 0000000..cef7199 --- /dev/null +++ b/test/functional/user/scomment_notifications_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class User::ScommentNotificationsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/user/vcomment_notifications_controller_test.rb b/test/functional/user/vcomment_notifications_controller_test.rb new file mode 100644 index 0000000..57b1482 --- /dev/null +++ b/test/functional/user/vcomment_notifications_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class User::VcommentNotificationsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/helpers/user/bcomment_notifications_helper_test.rb b/test/unit/helpers/user/bcomment_notifications_helper_test.rb new file mode 100644 index 0000000..49b1637 --- /dev/null +++ b/test/unit/helpers/user/bcomment_notifications_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class User::BcommentNotificationsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/user/comment_notifications_helper_test.rb b/test/unit/helpers/user/comment_notifications_helper_test.rb new file mode 100644 index 0000000..b835708 --- /dev/null +++ b/test/unit/helpers/user/comment_notifications_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class User::CommentNotificationsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/user/pcomment_notifications_helper_test.rb b/test/unit/helpers/user/pcomment_notifications_helper_test.rb new file mode 100644 index 0000000..d16e094 --- /dev/null +++ b/test/unit/helpers/user/pcomment_notifications_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class User::PcommentNotificationsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/user/scomment_notifications_helper_test.rb b/test/unit/helpers/user/scomment_notifications_helper_test.rb new file mode 100644 index 0000000..eacf9e3 --- /dev/null +++ b/test/unit/helpers/user/scomment_notifications_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class User::ScommentNotificationsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/user/vcomment_notifications_helper_test.rb b/test/unit/helpers/user/vcomment_notifications_helper_test.rb new file mode 100644 index 0000000..ac0cc2b --- /dev/null +++ b/test/unit/helpers/user/vcomment_notifications_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class User::VcommentNotificationsHelperTest < ActionView::TestCase +end diff --git a/test/unit/pcomment_notification_test.rb b/test/unit/pcomment_notification_test.rb new file mode 100644 index 0000000..5155713 --- /dev/null +++ b/test/unit/pcomment_notification_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class PcommentNotificationTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/scomment_notification_test.rb b/test/unit/scomment_notification_test.rb new file mode 100644 index 0000000..6c736b7 --- /dev/null +++ b/test/unit/scomment_notification_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class ScommentNotificationTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/vcomment_notification_test.rb b/test/unit/vcomment_notification_test.rb new file mode 100644 index 0000000..54137ff --- /dev/null +++ b/test/unit/vcomment_notification_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class VcommentNotificationTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end
goodxiexin/dayday3
8177ecf51e9c16a7ff51ef89a0d1507d451d9e57
event photo added
diff --git a/app/controllers/.album_photos_controller.rb.swp b/app/controllers/.album_photos_controller.rb.swp new file mode 100644 index 0000000..05825c9 Binary files /dev/null and b/app/controllers/.album_photos_controller.rb.swp differ diff --git a/app/controllers/.events_controller.rb.swp b/app/controllers/.events_controller.rb.swp index dc1874c..597a7f0 100644 Binary files a/app/controllers/.events_controller.rb.swp and b/app/controllers/.events_controller.rb.swp differ diff --git a/app/controllers/event_wall_messages_controller.rb b/app/controllers/event_wall_messages_controller.rb index 15f4480..f27e575 100644 --- a/app/controllers/event_wall_messages_controller.rb +++ b/app/controllers/event_wall_messages_controller.rb @@ -1,2 +1,34 @@ class EventWallMessagesController < ApplicationController + + def index + end + + def new + @event = Event.find(params[:id]) + @event_wall_messages = @event.event_wall_messages[0, 10] # get most recent 10 wall messages + @event_wall_message = EventWallMessage.new + @event_wall_message.event_id = params[:id] + end + + def create + @event_wall_message = EventWallMessage.new(params[:event_wall_message]) + @event_wall_message.poster_id = current_user.id + @event_wall_message.save + + respond_to do |format| + format.html { render :partial => 'event_wall_message', :object => @event_wall_message } + format.xml { render :xml => @event_wall_message } + end + end + + def destroy + @event_wall_message = EventWallMessage.find(params[:id]) + @event_wall_message.destroy + + respond_to do |format| + format.html { render :nothing => true } + format.xml { head :ok } + end + end + end diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb index 5d46792..9de79af 100644 --- a/app/controllers/events_controller.rb +++ b/app/controllers/events_controller.rb @@ -1,34 +1,46 @@ class EventsController < ApplicationController layout 'event' def index end def new @event = Event.new @games = Game.all end def show - @event = Event.find_by_id(params[:id]) + @event = Event.find(params[:id]) + @user = User.find(@event.poster_id) + @game = Game.find(@event.game_id) + @game_server = GameServer.find(@event.game_server_id) + @game_area = GameArea.find(@event.game_area_id) unless @event.game_area_id.nil? + + @event_wall_messages = @event.event_wall_messages[0, 10] # get most recent 10 event wall messages + @event_wall_message = EventWallMessage.new + @event_wall_message.receiver_id = @user.id + @event_wall_message.event_id = @event.id + + @album = @event.album + @photos = @album.photos.paginate :page => params[:page], :per_page => 4, :order => 'updated_at DESC' # get most recent 5 photos end def create @event = Event.new(params[:event]) - event_album = Album.new + event_album = Album.create(:game_id => @event.game_id, :title => @event.title+'\'s album', :user_id => current_user.id) @event.album_id = event_album.id @event.poster_id = current_user.id @event.save flash[:notice] = "Event is successfully created" redirect_to "/participations/new?event_id="+String(@event.id) end def update end def edit end def destroy end end diff --git a/app/controllers/participations_controller.rb b/app/controllers/participations_controller.rb index c2c5d5c..740590f 100644 --- a/app/controllers/participations_controller.rb +++ b/app/controllers/participations_controller.rb @@ -1,49 +1,49 @@ class ParticipationsController < ApplicationController layout 'event' def index end def new event_id = params[:event_id] @event = Event.find(event_id) @user = current_user @games = Game.all end def create @event = Event.find(params[:event_id]) params[:participants].each do |participant_id| @event.participations.create(:participant_id => participant_id, :inviter_id => current_user.id) end unless params[:participants].blank? flash[:notice] = "successfully invited your friends" render :update do |page| - page.redirect_to new_event_url + page.redirect_to event_url(@event) end end def new_participation participations = [] params[:participants].each do |participant_id| participations << Participation.new(:participant_id => participant_id) end render :partial => "participation", :collection => participations end def friends_list @user = current_user if params[:game_id].blank? @friends = @user.friends else game = Game.find(params[:game_id]) @friends = @user.friends.find_all {|f| f.games.include?(game) } end render :partial => 'friends_list', :object => @friends end def auto_complete_for_event_participations @user = current_user @friends = @user.friends.find_all {|f| f.login.include?(params[:event][:participations]) } render :partial => 'friends' end end diff --git a/public/javascripts/.blog.js.swp b/app/helpers/.user_albums_helper.rb.swp similarity index 65% rename from public/javascripts/.blog.js.swp rename to app/helpers/.user_albums_helper.rb.swp index 6af108f..23b2cc9 100644 Binary files a/public/javascripts/.blog.js.swp and b/app/helpers/.user_albums_helper.rb.swp differ diff --git a/app/models/.event.rb.swp b/app/models/.event.rb.swp new file mode 100644 index 0000000..1e94690 Binary files /dev/null and b/app/models/.event.rb.swp differ diff --git a/app/models/event.rb b/app/models/event.rb index 9bbb071..468c2c6 100644 --- a/app/models/event.rb +++ b/app/models/event.rb @@ -1,56 +1,59 @@ class Event < ActiveRecord::Base # the poster of this activity belongs_to :poster, :class_name => 'User' # the category of this activity belongs_to :game # the location of the activity belongs_to :game_server - # teh wall messages for a event + # the album for the event, one-one relation + belongs_to :album + + # the wall messages for a event has_many :event_wall_messages, :dependent => :destroy, - :finder_sql => 'select event_wall_messages.* from event_wall_messages where event_wall_messages.user_id = #{id} OR event_wall_messages.receiver_id = #{id} ORDER BY created_at DESC' + :finder_sql => 'select event_wall_messages.* from event_wall_messages where event_wall_messages.event_id = #{id} ORDER BY created_at DESC' # participants of this activity has_many :participations, :dependent => :destroy has_many :participants, :through => :participations # others can comment your activity has_many :comments, :as => 'resource' # register the activity def register(user_id) user = User.find(user_id) if user self.participants << user end end # unregister the activity def unregister(user_id) user = self.participants.find(user_id) if user self.participants.delete(user) end end # cancel this activity # this action is only allowed for the poster of this activity def cancel(user_id) if poster?(user_id) self.destroy end end private # if the user is the poster of this activity def poster?(user_id) (poster_id == user_id)? true : false end end diff --git a/app/models/event_wall_message.rb b/app/models/event_wall_message.rb index 1f6647e..6bd60b4 100644 --- a/app/models/event_wall_message.rb +++ b/app/models/event_wall_message.rb @@ -1,8 +1,8 @@ class EventWallMessage < ActiveRecord::Base belongs_to :event belongs_to :poster, - :class_name => 'User' + :class_name => 'User', :foreign_key => 'poster_id' end diff --git a/app/views/album_photos/.new.html.erb.swp b/app/views/album_photos/.new.html.erb.swp new file mode 100644 index 0000000..bbc8209 Binary files /dev/null and b/app/views/album_photos/.new.html.erb.swp differ diff --git a/app/views/event_wall_messages/_event_wall_message.html.erb b/app/views/event_wall_messages/_event_wall_message.html.erb new file mode 100755 index 0000000..0927524 --- /dev/null +++ b/app/views/event_wall_messages/_event_wall_message.html.erb @@ -0,0 +1,14 @@ +<% message = event_wall_message %> +<% wall_message_divid = "event_wall_message_#{message.id}" %> + +<div id=<%= wall_message_divid %>> + <%= user_icon(message.poster) %> + <%= link_to message.poster.login %> + <%= ftime message.created_at %> <br/> + <%= message.content %> + <% if current_user == message.poster %> + <%= link_to_remote 'delete', :complete => "$('#{wall_message_divid}').remove();",:url => {:controller => 'event_wall_messages', :action => 'destroy', :id => message.id }, :confirm => 'are you sure' %> + <% else %> + <%= link_to_function 'comment', "$('event_wall_message_content').value='reply to #{message.poster.login}: ';$('event_wall_message_content').focus();$('event_wall_message_receiver_id').value=#{message.poster.id};$('event_wall_message_event_id').value=#{@event.id}" %> + <% end %> +</div> diff --git a/app/views/event_wall_messages/_input.html.erb b/app/views/event_wall_messages/_input.html.erb new file mode 100755 index 0000000..a26b58f --- /dev/null +++ b/app/views/event_wall_messages/_input.html.erb @@ -0,0 +1,11 @@ +<% form_remote_for :event_wall_message, + :position => :top, + :update => 'event_wall_messages', + :complete => "$('event_wall_message_content').value='';", + :url => {:controller => 'event_wall_messages', :action => 'create'} do |form| %> + <p style="display:none"><%= form.text_field 'event_id' %></p> + <p style="display:none"><%= form.text_field 'receiver_id' %></p> + <p><%= form.text_area 'content', :rows => 8, :cols => 80 %></p> + <p><%= form.submit 'leave a message' %></p> +<% end %> + diff --git a/app/views/events/.show.html.erb.swp b/app/views/events/.show.html.erb.swp index 7081e60..580a952 100644 Binary files a/app/views/events/.show.html.erb.swp and b/app/views/events/.show.html.erb.swp differ diff --git a/app/views/events/_messages.html.erb b/app/views/events/_messages.html.erb new file mode 100644 index 0000000..09eb5bf --- /dev/null +++ b/app/views/events/_messages.html.erb @@ -0,0 +1,5 @@ +Wall: +<%= render :partial => 'event_wall_messages/input' %> +<div id='event_wall_messages'> +<%= render :partial => 'event_wall_messages/event_wall_message', :collection => @event_wall_messages %> +</div> diff --git a/app/views/events/new.html.erb b/app/views/events/new.html.erb index c461e90..fac7bc0 100644 --- a/app/views/events/new.html.erb +++ b/app/views/events/new.html.erb @@ -1,22 +1,26 @@ <% form_for @event, events_path do |f| %> <div> -<%= f.label "title" %> +<%= f.label "title:" %><br/> +<%= f.text_field :title %> +</div> +<div> +<%= f.label "game:" %> <%= collection_select :event, :game_id, @games, :id, :name, {:prompt => '---'}, {:onchange => "validate_game_id(this.value);game_onchange_event(this.value)"} %> <a id='game_id_info'></a> </div> <div id=game_details></div> <div> <%= f.label "starting Date and Time" %> <%= datetime_select :event, :time %> <a id='event_time_form'></a> </div> <div> <%= f.label "description:" %><br/> <%= f.text_area :description %> <a id='event_description_form'></a> </div> <div> <%= f.submit "Next Step" %> <a id='event_submit'></a> </div> <% end %> diff --git a/app/views/events/show.html.erb b/app/views/events/show.html.erb new file mode 100644 index 0000000..e997d40 --- /dev/null +++ b/app/views/events/show.html.erb @@ -0,0 +1,13 @@ +<p><%= album_cover(@album) %> </p> +<p>Title:<%= @event.title %></p> +<p>Organizer: <%= @user.login %></p> +<p>Starting Time: <%= @event.time %></p> +<p>Game: <%= @game.name %></p> +<% unless @game_area.nil? %> +<p>Area: <%= @game_area.name %></p> +<% end %> +<p>Server:<%= @game_server.name %></p> +<p>Description: <%= @event.description %></p> +<p><%= link_to "upload photos", new_album_photo_url(@album) %></p> +<p><%= render :partial => 'user_albums/photos', :object => @photos %></p> +<%= render :partial => 'messages' %> diff --git a/app/views/user_blogs/._btag.html.erb.swp b/app/views/user_albums/._edit_menu.html.erb.swp similarity index 95% rename from app/views/user_blogs/._btag.html.erb.swp rename to app/views/user_albums/._edit_menu.html.erb.swp index 7a637f2..4bafaef 100644 Binary files a/app/views/user_blogs/._btag.html.erb.swp and b/app/views/user_albums/._edit_menu.html.erb.swp differ diff --git a/app/controllers/.user_blogs_controller.rb.swp b/db/migrate/.20090810065714_create_albums.rb.swp similarity index 70% rename from app/controllers/.user_blogs_controller.rb.swp rename to db/migrate/.20090810065714_create_albums.rb.swp index 9fe15c8..0927f0f 100644 Binary files a/app/controllers/.user_blogs_controller.rb.swp and b/db/migrate/.20090810065714_create_albums.rb.swp differ diff --git a/db/migrate/.20090818060826_create_events.rb.swp b/db/migrate/.20090818060826_create_events.rb.swp new file mode 100644 index 0000000..362b944 Binary files /dev/null and b/db/migrate/.20090818060826_create_events.rb.swp differ diff --git a/db/migrate/20090818030745_create_event_wall_messages.rb b/db/migrate/20090818030745_create_event_wall_messages.rb index c01b22e..9a907c2 100644 --- a/db/migrate/20090818030745_create_event_wall_messages.rb +++ b/db/migrate/20090818030745_create_event_wall_messages.rb @@ -1,16 +1,15 @@ class CreateEventWallMessages < ActiveRecord::Migration def self.up create_table :event_wall_messages do |t| t.integer :event_id t.integer :poster_id t.integer :receiver_id t.text :content - t.boolean :whisper, :default => false t.timestamps end end def self.down drop_table :event_wall_messages end end diff --git a/public/photos/0000/0009/2719063547_7c0249508a_o.png b/public/photos/0000/0009/2719063547_7c0249508a_o.png new file mode 100644 index 0000000..fb8e5e4 Binary files /dev/null and b/public/photos/0000/0009/2719063547_7c0249508a_o.png differ diff --git a/public/photos/0000/0009/2719063547_7c0249508a_o_large.png b/public/photos/0000/0009/2719063547_7c0249508a_o_large.png new file mode 100644 index 0000000..f4e26be Binary files /dev/null and b/public/photos/0000/0009/2719063547_7c0249508a_o_large.png differ diff --git a/public/photos/0000/0009/2719063547_7c0249508a_o_medium.png b/public/photos/0000/0009/2719063547_7c0249508a_o_medium.png new file mode 100644 index 0000000..163f588 Binary files /dev/null and b/public/photos/0000/0009/2719063547_7c0249508a_o_medium.png differ diff --git a/public/photos/0000/0009/2719063547_7c0249508a_o_small.png b/public/photos/0000/0009/2719063547_7c0249508a_o_small.png new file mode 100644 index 0000000..0a8649f Binary files /dev/null and b/public/photos/0000/0009/2719063547_7c0249508a_o_small.png differ diff --git a/public/photos/0000/0013/chinaFeng1.jpeg b/public/photos/0000/0013/chinaFeng1.jpeg new file mode 100644 index 0000000..db85400 Binary files /dev/null and b/public/photos/0000/0013/chinaFeng1.jpeg differ diff --git a/public/photos/0000/0013/chinaFeng1_large.jpeg b/public/photos/0000/0013/chinaFeng1_large.jpeg new file mode 100644 index 0000000..da8a506 Binary files /dev/null and b/public/photos/0000/0013/chinaFeng1_large.jpeg differ diff --git a/public/photos/0000/0013/chinaFeng1_medium.jpeg b/public/photos/0000/0013/chinaFeng1_medium.jpeg new file mode 100644 index 0000000..cb0ad96 Binary files /dev/null and b/public/photos/0000/0013/chinaFeng1_medium.jpeg differ diff --git a/public/photos/0000/0013/chinaFeng1_small.jpeg b/public/photos/0000/0013/chinaFeng1_small.jpeg new file mode 100644 index 0000000..4b6b338 Binary files /dev/null and b/public/photos/0000/0013/chinaFeng1_small.jpeg differ diff --git a/public/photos/0000/0017/Family_Guy_with_iPod.jpg b/public/photos/0000/0017/Family_Guy_with_iPod.jpg new file mode 100644 index 0000000..dad10cf Binary files /dev/null and b/public/photos/0000/0017/Family_Guy_with_iPod.jpg differ diff --git a/public/photos/0000/0017/Family_Guy_with_iPod_large.jpg b/public/photos/0000/0017/Family_Guy_with_iPod_large.jpg new file mode 100644 index 0000000..a3f981b Binary files /dev/null and b/public/photos/0000/0017/Family_Guy_with_iPod_large.jpg differ diff --git a/public/photos/0000/0017/Family_Guy_with_iPod_medium.jpg b/public/photos/0000/0017/Family_Guy_with_iPod_medium.jpg new file mode 100644 index 0000000..69d7405 Binary files /dev/null and b/public/photos/0000/0017/Family_Guy_with_iPod_medium.jpg differ diff --git a/public/photos/0000/0017/Family_Guy_with_iPod_small.jpg b/public/photos/0000/0017/Family_Guy_with_iPod_small.jpg new file mode 100644 index 0000000..0f5ce1a Binary files /dev/null and b/public/photos/0000/0017/Family_Guy_with_iPod_small.jpg differ diff --git a/public/photos/0000/0021/logo-one-piece-82-1280x960.jpg b/public/photos/0000/0021/logo-one-piece-82-1280x960.jpg new file mode 100644 index 0000000..9d6d93e Binary files /dev/null and b/public/photos/0000/0021/logo-one-piece-82-1280x960.jpg differ diff --git a/public/photos/0000/0021/logo-one-piece-82-1280x960_large.jpg b/public/photos/0000/0021/logo-one-piece-82-1280x960_large.jpg new file mode 100644 index 0000000..7b471c4 Binary files /dev/null and b/public/photos/0000/0021/logo-one-piece-82-1280x960_large.jpg differ diff --git a/public/photos/0000/0021/logo-one-piece-82-1280x960_medium.jpg b/public/photos/0000/0021/logo-one-piece-82-1280x960_medium.jpg new file mode 100644 index 0000000..96a35d1 Binary files /dev/null and b/public/photos/0000/0021/logo-one-piece-82-1280x960_medium.jpg differ diff --git a/public/photos/0000/0021/logo-one-piece-82-1280x960_small.jpg b/public/photos/0000/0021/logo-one-piece-82-1280x960_small.jpg new file mode 100644 index 0000000..407a5d9 Binary files /dev/null and b/public/photos/0000/0021/logo-one-piece-82-1280x960_small.jpg differ diff --git a/public/photos/0000/0025/OnePiece.jpg b/public/photos/0000/0025/OnePiece.jpg new file mode 100644 index 0000000..fbc4273 Binary files /dev/null and b/public/photos/0000/0025/OnePiece.jpg differ diff --git a/public/photos/0000/0025/OnePiece_large.jpg b/public/photos/0000/0025/OnePiece_large.jpg new file mode 100644 index 0000000..566fad6 Binary files /dev/null and b/public/photos/0000/0025/OnePiece_large.jpg differ diff --git a/public/photos/0000/0025/OnePiece_medium.jpg b/public/photos/0000/0025/OnePiece_medium.jpg new file mode 100644 index 0000000..acfdb4e Binary files /dev/null and b/public/photos/0000/0025/OnePiece_medium.jpg differ diff --git a/public/photos/0000/0025/OnePiece_small.jpg b/public/photos/0000/0025/OnePiece_small.jpg new file mode 100644 index 0000000..b61aaed Binary files /dev/null and b/public/photos/0000/0025/OnePiece_small.jpg differ diff --git a/public/photos/0000/0029/BC01Lohan1920x1200-313142.jpeg b/public/photos/0000/0029/BC01Lohan1920x1200-313142.jpeg new file mode 100644 index 0000000..071ba39 Binary files /dev/null and b/public/photos/0000/0029/BC01Lohan1920x1200-313142.jpeg differ diff --git a/public/photos/0000/0029/BC01Lohan1920x1200-313142_large.jpeg b/public/photos/0000/0029/BC01Lohan1920x1200-313142_large.jpeg new file mode 100644 index 0000000..db71459 Binary files /dev/null and b/public/photos/0000/0029/BC01Lohan1920x1200-313142_large.jpeg differ diff --git a/public/photos/0000/0029/BC01Lohan1920x1200-313142_medium.jpeg b/public/photos/0000/0029/BC01Lohan1920x1200-313142_medium.jpeg new file mode 100644 index 0000000..de65350 Binary files /dev/null and b/public/photos/0000/0029/BC01Lohan1920x1200-313142_medium.jpeg differ diff --git a/public/photos/0000/0029/BC01Lohan1920x1200-313142_small.jpeg b/public/photos/0000/0029/BC01Lohan1920x1200-313142_small.jpeg new file mode 100644 index 0000000..8df255a Binary files /dev/null and b/public/photos/0000/0029/BC01Lohan1920x1200-313142_small.jpeg differ
goodxiexin/dayday3
210a0c11b7b2a0468c06250829a24b1bc7056a4a
event creation
diff --git a/app/views/friends/._friends.html.erb.swp b/app/controllers/.events_controller.rb.swp similarity index 91% rename from app/views/friends/._friends.html.erb.swp rename to app/controllers/.events_controller.rb.swp index f26464a..dc1874c 100644 Binary files a/app/views/friends/._friends.html.erb.swp and b/app/controllers/.events_controller.rb.swp differ diff --git a/app/controllers/.participations_controller.rb.swp b/app/controllers/.participations_controller.rb.swp deleted file mode 100644 index 2ca7d5d..0000000 Binary files a/app/controllers/.participations_controller.rb.swp and /dev/null differ diff --git a/app/controllers/.user_blogs_controller.rb.swp b/app/controllers/.user_blogs_controller.rb.swp index 126ed04..9fe15c8 100644 Binary files a/app/controllers/.user_blogs_controller.rb.swp and b/app/controllers/.user_blogs_controller.rb.swp differ diff --git a/app/controllers/participations_controller.rb b/app/controllers/participations_controller.rb index 96127a7..c2c5d5c 100644 --- a/app/controllers/participations_controller.rb +++ b/app/controllers/participations_controller.rb @@ -1,30 +1,49 @@ class ParticipationsController < ApplicationController layout 'event' def index end def new event_id = params[:event_id] @event = Event.find(event_id) @user = current_user + @games = Game.all end def create + @event = Event.find(params[:event_id]) + params[:participants].each do |participant_id| + @event.participations.create(:participant_id => participant_id, :inviter_id => current_user.id) + end unless params[:participants].blank? + flash[:notice] = "successfully invited your friends" + render :update do |page| + page.redirect_to new_event_url + end end def new_participation participations = [] params[:participants].each do |participant_id| participations << Participation.new(:participant_id => participant_id) end - render :partial => "participants", :collection => participations + render :partial => "participation", :collection => participations end + def friends_list + @user = current_user + if params[:game_id].blank? + @friends = @user.friends + else + game = Game.find(params[:game_id]) + @friends = @user.friends.find_all {|f| f.games.include?(game) } + end + render :partial => 'friends_list', :object => @friends + end + def auto_complete_for_event_participations - logger.error('auto_complete has been run') @user = current_user @friends = @user.friends.find_all {|f| f.login.include?(params[:event][:participations]) } render :partial => 'friends' end end diff --git a/app/models/participation.rb b/app/models/participation.rb index 0c34dec..bf9f4f8 100644 --- a/app/models/participation.rb +++ b/app/models/participation.rb @@ -1,9 +1,13 @@ class Participation < ActiveRecord::Base - # each participation involves a participant and an event + # each participation involves a participant and an event and an inviter belongs_to :participant, :class_name => 'User', :foreign_key => 'participant_id' belongs_to :event, :counter_cache => true + + belongs_to :inviter, + :class_name => 'User', + :foreign_key => 'inviter_id' end diff --git a/app/views/participations/._participants.html.erb.swp b/app/views/events/.show.html.erb.swp similarity index 94% rename from app/views/participations/._participants.html.erb.swp rename to app/views/events/.show.html.erb.swp index 5baca90..7081e60 100644 Binary files a/app/views/participations/._participants.html.erb.swp and b/app/views/events/.show.html.erb.swp differ diff --git a/app/views/participations/.new.html.erb.swp b/app/views/participations/.new.html.erb.swp deleted file mode 100644 index a2ff0a3..0000000 Binary files a/app/views/participations/.new.html.erb.swp and /dev/null differ diff --git a/app/views/participations/_friends_list.html.erb b/app/views/participations/_friends_list.html.erb new file mode 100755 index 0000000..2793903 --- /dev/null +++ b/app/views/participations/_friends_list.html.erb @@ -0,0 +1,12 @@ +<% i = 0 %> +<table cellpadding='5px'> +<% friends_list.each do |f| %> + <% "<tr>" if i == 0 %> + <td width='100px'> <%= check_box_tag '', f.id, false %> <%= f.login %> <%= user_icon(f) %></td> + <% i = i + 1 %> + <% if i == 3 %> + </tr> + <% i = 0 %> + <% end %> +<% end %> +</table> diff --git a/app/views/participations/_participants.html.erb b/app/views/participations/_participation.html.erb similarity index 99% rename from app/views/participations/_participants.html.erb rename to app/views/participations/_participation.html.erb index 77cba41..c923ce0 100644 --- a/app/views/participations/_participants.html.erb +++ b/app/views/participations/_participation.html.erb @@ -1,5 +1,4 @@ <div new_record=<%= participation.new_record?%> participant_id=<%= participation.participant_id %> participation_id=<%= participation.new_record? ? 0: participation.id %>> <p><%= user_icon(participation.participant) %></p> <p><%= link_to_user participation.participant %> | <%= link_to_function 'delete', "participation_builder.remove_participation(#{participation.participant_id})" %></p> </div> - diff --git a/app/views/participations/new.html.erb b/app/views/participations/new.html.erb index d2f5c2c..8022ccf 100644 --- a/app/views/participations/new.html.erb +++ b/app/views/participations/new.html.erb @@ -1,8 +1,17 @@ <%= javascript_include_tag 'participation.js' %> -<%= javascript_tag "participation_builder = new ParticipationBuilder(#{@user.id}, 0);" %> + <div id="participation_left_box"> <p><%= text_field_with_auto_complete :event, :participations, {}, {:after_update_element => 'after_select' } %></p> +<p><%= collection_select :event, :game_id, @games, :id, :name, {:include_blank => 'all'}, {:onchange => "participation_builder.game_select(this.value)"} %></p> +<div id="friends"></div> </div> <div id="participation_right_box"> <div id="participations"></div> </div> +<%= javascript_tag "participation_builder = new ParticipationBuilder(#{@user.id}, #{@event.id});" %> +<p><%= link_to_function "invite", "participation_builder.confirm_event()" %></p> +<p><%= link_to_function "finish", "participation_builder.save(#{@event.id})" %></p> +<%= javascript_tag "document.observe(\"dom:loaded\", function() { + participation_builder.game_select(#{@event.game_id}); +});" %> + diff --git a/app/views/user_blogs/._btag.html.erb.swp b/app/views/user_blogs/._btag.html.erb.swp index a428e97..7a637f2 100644 Binary files a/app/views/user_blogs/._btag.html.erb.swp and b/app/views/user_blogs/._btag.html.erb.swp differ diff --git a/app/views/user_blogs/.new.html.erb.swp b/app/views/user_blogs/.new.html.erb.swp deleted file mode 100644 index 1fb7e5d..0000000 Binary files a/app/views/user_blogs/.new.html.erb.swp and /dev/null differ diff --git a/app/views/user_wall_messages/_wall_message.html.erb b/app/views/user_wall_messages/_wall_message.html.erb index bb05b5b..89c5be1 100755 --- a/app/views/user_wall_messages/_wall_message.html.erb +++ b/app/views/user_wall_messages/_wall_message.html.erb @@ -1,15 +1,14 @@ <% message = wall_message %> <% wall_message_divid = "wall_message_#{message.id}" %> <div id=<%= wall_message_divid %>> <%= user_icon(message.poster) %> <%= link_to message.poster.login %> <%= ftime message.created_at %> <br/> <%= message.content %> <% if current_user == message.poster %> <%= link_to_remote 'delete', :complete => "$('#{wall_message_divid}').remove();",:url => user_wall_message_url(@user, message), :confirm => 'are you sure', :method => :delete %> <% else %> <%= link_to_function 'comment', "$('wall_message_content').value='reply to #{message.poster.login}: ';$('wall_message_content').focus();$('wall_message_receiver_id').value=#{message.poster.id}" %> <% end %> </div> - diff --git a/config/.routes.rb.swp b/config/.routes.rb.swp deleted file mode 100644 index f73a685..0000000 Binary files a/config/.routes.rb.swp and /dev/null differ diff --git a/config/routes.rb b/config/routes.rb index 4f0463d..93541e3 100755 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,140 +1,140 @@ ActionController::Routing::Routes.draw do |map| - map.resources :participations + map.resources :participations, :collection => {:new_participation => :get, :friends_list => :get} map.resources :pages map.resources :sessions map.resources :statuses map.resources :wall_messages map.resources :mails map.resources :icons map.resources :ptags map.resources :pdigs map.resources :pcomments map.resources :bdigs map.resources :friendships map.resources :game_characters, :collection => {:edit_new => :get} map.resources :game_races map.resources :game_professions map.resources :game_servers map.resources :game_areas map.resources :games map.root :controller => 'sessions', :action => 'new' map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate' map.forgot_password '/forgot_password', :controller => 'passwords', :action => 'new' map.reset_password '/reset_password/:password_reset_code', :controller => 'passwords', :action => 'edit' map.change_password '/change_password', :controller => 'accounts', :action => 'edit' map.resources :users, :member => {:enable => :put} do |users| users.resources :characters, :controller => 'user_characters', :member => {:confirm_destroy => :get} users.resources :wall_messages, :controller => 'user_wall_messages' users.resources :mails, :controller => 'mailboxes', :member => {:reply => :post}, :collection => {:read_multiple => :put, :unread_multiple => :put, :destroy_multiple => :delete} users.resources :friends, :collection => {:search => :get} users.resources :statuses, :controller => 'user_statuses' users.resources :blogs, :controller => 'user_blogs', :member => {:confirm_destroy => :get}, :collection => {:destroy_multiple => :delete} users.resources :videos, :controller => 'user_videos', :member => {:confirm_destroy => :get} users.resources :blog_feeds users.resources :tagged_blogs users.resources :albums, :controller => 'user_albums', :member => {:confirm_destroy => :get} users.resources :album_feeds users.resources :tagged_photos users.resource :profile users.resource :basic_info, :controller => 'basic_info' users.resource :contact_info, :controller => 'contact_info' end map.resources :blogs do |blogs| blogs.resources :comments, :controller => 'blog_comments' blogs.resources :tags, :controller => 'blog_tags' blogs.resources :digs, :controller => 'blog_digs' end map.resources :photos do |photos| photos.resources :comments, :controller => 'photo_comments' photos.resources :tags, :controller => 'photo_tags' photos.resources :digs, :controller => 'photo_digs' end map.resources :albums do |albums| albums.resources :photos, :controller => 'album_photos', :member => {:confirm_destroy => :get, :cover => :post}, :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} end map.resources :events map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090818062911_create_participations.rb b/db/migrate/20090818062911_create_participations.rb index dde84dd..74f39dd 100644 --- a/db/migrate/20090818062911_create_participations.rb +++ b/db/migrate/20090818062911_create_participations.rb @@ -1,14 +1,15 @@ class CreateParticipations < ActiveRecord::Migration def self.up create_table :participations do |t| + t.integer :inviter_id t.integer :participant_id t.integer :event_id t.integer :event_status, :default => 1 t.timestamps end end def self.down drop_table :participations end end diff --git a/db/schema.rb b/db/schema.rb index 493c384..fcbf3ea 100755 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,349 +1,350 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20090818062911) do create_table "albums", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "photos_count", :default => 0 t.string "title" t.text "description" t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomments", :force => true do |t| t.integer "user_id", :null => false t.integer "blog_id", :null => false t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "bdigs", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "blogs", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title", :limit => 64 t.text "content", :limit => 16777215 t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.boolean "draft", :default => true t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "btags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "cities", :force => true do |t| t.string "name" t.integer "city_id" t.datetime "created_at" t.datetime "updated_at" end create_table "countries", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "event_wall_messages", :force => true do |t| t.integer "event_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "events", :force => true do |t| t.string "title" t.integer "poster_id" t.integer "game_id" t.integer "game_server_id" t.integer "game_area_id" t.integer "album_id" t.integer "participations_count", :default => 0 t.datetime "time" t.text "description" t.datetime "created_at" t.datetime "updated_at" end create_table "friendships", :force => true do |t| t.integer "user_id" t.integer "friend_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_areas", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_characters", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "server_id" t.integer "area_id" t.integer "profession_id" t.integer "race_id" t.string "name" t.integer "level" t.boolean "playing" t.datetime "created_at" t.datetime "updated_at" end create_table "game_professions", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_races", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_servers", :force => true do |t| t.string "name" t.string "ip" t.integer "game_id" t.integer "area_id" t.datetime "created_at" t.datetime "updated_at" end create_table "games", :force => true do |t| t.string "name" t.string "company" t.datetime "sale_date" t.text "description" t.boolean "no_areas", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "icons", :force => true do |t| t.integer "user_id" t.boolean "current" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "mails", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.boolean "delete_by_sender", :default => false t.boolean "delete_by_receiver", :default => false t.boolean "read_by_sender", :default => true t.boolean "read_by_receiver", :default => false t.string "title" t.text "content" t.integer "parent_id" t.datetime "created_at" t.datetime "updated_at" end create_table "pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "participations", :force => true do |t| + t.integer "inviter_id" t.integer "participant_id" t.integer "event_id" t.integer "event_status", :default => 1 t.datetime "created_at" t.datetime "updated_at" end create_table "pcomments", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "pdigs", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.datetime "created_at" t.datetime "updated_at" end create_table "permissions", :force => true do |t| t.string "user_id" t.string "role_id" t.datetime "created_at" t.datetime "updated_at" end create_table "photos", :force => true do |t| t.integer "digs_count", :default => 0 t.integer "tags_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "album_id" t.boolean "cover", :default => false t.text "notation" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "provinces", :force => true do |t| t.string "name" t.integer "country_id" t.datetime "created_at" t.datetime "updated_at" end create_table "ptags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "photo_id" t.integer "x" t.integer "y" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "roles", :force => true do |t| t.string "name", :null => false t.datetime "created_at" t.datetime "updated_at" end create_table "statuses", :force => true do |t| t.integer "user_id" t.text "content" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :limit => 64 t.string "email", :limit => 128 t.string "crypted_password", :limit => 64 t.string "salt", :limit => 40 t.string "gender" t.boolean "enabled", :default => true t.string "remember_token" t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "password_reset_code", :limit => 40 t.integer "country_id" t.integer "province_id" t.integer "city_id" t.integer "qq" t.integer "mobile" t.string "website" t.datetime "birthday" t.datetime "created_at" t.datetime "updated_at" end create_table "vcomments", :force => true do |t| t.integer "user_id" t.integer "video_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "vdigs", :force => true do |t| t.integer "user_id" t.integer "video_id" t.datetime "created_at" t.datetime "updated_at" end create_table "videos", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title" t.string "url" t.text "link" t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "vtags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "video_id" t.datetime "created_at" t.datetime "updated_at" end create_table "wall_messages", :force => true do |t| t.integer "user_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end end diff --git a/public/javascripts/.blog.js.swp b/public/javascripts/.blog.js.swp index 21b9f93..6af108f 100644 Binary files a/public/javascripts/.blog.js.swp and b/public/javascripts/.blog.js.swp differ diff --git a/public/javascripts/participation.js b/public/javascripts/participation.js index fe17698..c0ab995 100644 --- a/public/javascripts/participation.js +++ b/public/javascripts/participation.js @@ -1,73 +1,123 @@ - function after_select(input_field, selected_li){ - alert('hello4'); participation_builder.new_participation(selected_li.readAttribute('user_id')); - alert('hello5'); $('event_participations').value = ''; } ParticipationBuilder = Class.create({ initialize: function(user_id, event_id){ this.user_id = user_id; this.event_id = event_id; - alert('hello'); this.participation_input = $('event_participations'); - alert('hello1'); this.participation_input.value = 'please tag your friend here'; - alert('hello2'); this.participation_input.observe('focus', function(event){ this.value = ''; }); this.participation_input.observe('blur', function(event){ this.value = 'please tag your friends here'; }); this.participations_div = $('participations'); + this.friends_list=$('friends'); this.participations = new Hash(); var current_participations = this.participations_div.childElements(); for(var i=0;i<current_participations.length;i++){ this.participations.set(current_participations[i].readAttribute('participant_id'), current_participations[i]); } }, after_select: function(input_field, selected_li){ this.new_participation(selected_li.readAttribute('user_id')); $('event_participations').value = ''; }, new_participation: function(participant_id){ // if this user is already in participation list, skip it if(this.participations.get(participant_id)) return; // send ajax request to retrieve user information(icon, name ... so on) new Ajax.Request('/participations/new_participation?participants[]=' + participant_id, { method: 'get', onSuccess: function(transport){ this.participations_div.innerHTML = transport.responseText + this.participations_div.innerHTML; this.participation_input.value = ''; var children = this.participations_div.childElements(); var length = children.length; for(var i=0;i<length;i++){ this.participations.set(children[i].readAttribute('participant_id'), children[i]); } }.bind(this) }); }, remove_participation: function(participant_id){ var participation = this.participations.unset(participant_id); if(!participation) return; // if it's not a new record, it means it stores in database, // then do an ajax request to remove it from database if(participation.readAttribute('new_record') != 'true') new Ajax.Request('/participations/' + participation.readAttribute('participation_id'), {method: 'delete'}); participation.remove(); }, + game_select: function(game_id){ + new Ajax.Request('/participations/friends_list?game_id=' + game_id, { + method: 'get', + onSuccess: function(transport){ + this.friends_list.innerHTML = transport.responseText; + }.bind(this) + }); + }, + + get_selected_users: function(){ + var inputs = $$('input'); + var length = inputs.length; + var selected_users = []; + for(var i = 0; i < length; i++){ + if(inputs[i].type == 'checkbox' && inputs[i].checked && !this.participations.get(inputs[i].value)){ + selected_users.push(inputs[i].value); + } + } + return selected_users; + }, + + confirm_event: function(){ + var selected_users = this.get_selected_users(); + if (selected_users.length != 0 ){ + var url = '/participations/new_participation?'; + for(var i=0;i<selected_users.length;i++){ + url += "participants[]=" + selected_users[i] + "&"; + } + + new Ajax.Request(url, { + method: 'get', + onSuccess: function(transport){ + this.participations_div.innerHTML = transport.responseText + this.participations_div.innerHTML; + var children = this.participations_div.childElements(); + var length = children.length; + for(var i=0;i<length;i++){ + this.participations.set(children[i].readAttribute('participant_id'), children[i]); + } + }.bind(this) + }); + } + }, + + save: function(event_id){ + // construct url + // appending participant inputs + var url = '/participations?event_id='+event_id+'&'; + this.participations.each(function(pair){ + if(pair.value.readAttribute('new_record') == 'true') + url += "participants[]=" + pair.key + "&"; + }); + // send ajax request + new Ajax.Request(url, {method: 'post'}); + }, + });
goodxiexin/dayday3
4452800f7a012a66450951f240e6df0f717aef29
participation with some problems
diff --git a/app/controllers/.game_areas_controller.rb.swp b/app/controllers/.game_areas_controller.rb.swp deleted file mode 100644 index 2d3ea33..0000000 Binary files a/app/controllers/.game_areas_controller.rb.swp and /dev/null differ diff --git a/app/controllers/.user_characters_controller.rb.swp b/app/controllers/.participations_controller.rb.swp similarity index 78% rename from app/controllers/.user_characters_controller.rb.swp rename to app/controllers/.participations_controller.rb.swp index de19924..2ca7d5d 100644 Binary files a/app/controllers/.user_characters_controller.rb.swp and b/app/controllers/.participations_controller.rb.swp differ diff --git a/app/controllers/.user_blogs_controller.rb.swp b/app/controllers/.user_blogs_controller.rb.swp new file mode 100644 index 0000000..126ed04 Binary files /dev/null and b/app/controllers/.user_blogs_controller.rb.swp differ diff --git a/app/controllers/.users_controller.rb.swp b/app/controllers/.users_controller.rb.swp deleted file mode 100644 index f4e5694..0000000 Binary files a/app/controllers/.users_controller.rb.swp and /dev/null differ diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb index e0fb29f..5d46792 100644 --- a/app/controllers/events_controller.rb +++ b/app/controllers/events_controller.rb @@ -1,30 +1,34 @@ class EventsController < ApplicationController layout 'event' def index end def new @event = Event.new @games = Game.all end def show + @event = Event.find_by_id(params[:id]) end def create @event = Event.new(params[:event]) + event_album = Album.new + @event.album_id = event_album.id + @event.poster_id = current_user.id @event.save flash[:notice] = "Event is successfully created" - redirect_to root_url + redirect_to "/participations/new?event_id="+String(@event.id) end def update end def edit end def destroy end end diff --git a/app/controllers/participations_controller.rb b/app/controllers/participations_controller.rb new file mode 100644 index 0000000..96127a7 --- /dev/null +++ b/app/controllers/participations_controller.rb @@ -0,0 +1,30 @@ +class ParticipationsController < ApplicationController + layout 'event' + def index + end + + def new + event_id = params[:event_id] + @event = Event.find(event_id) + @user = current_user + end + + def create + end + + def new_participation + participations = [] + params[:participants].each do |participant_id| + participations << Participation.new(:participant_id => participant_id) + end + render :partial => "participants", :collection => participations + end + + def auto_complete_for_event_participations + logger.error('auto_complete has been run') + @user = current_user + @friends = @user.friends.find_all {|f| f.login.include?(params[:event][:participations]) } + render :partial => 'friends' + end + +end diff --git a/app/helpers/participations_helper.rb b/app/helpers/participations_helper.rb new file mode 100644 index 0000000..051325c --- /dev/null +++ b/app/helpers/participations_helper.rb @@ -0,0 +1,2 @@ +module ParticipationsHelper +end diff --git a/app/models/participation.rb b/app/models/participation.rb index 04cd6d2..0c34dec 100644 --- a/app/models/participation.rb +++ b/app/models/participation.rb @@ -1,2 +1,9 @@ class Participation < ActiveRecord::Base + # each participation involves a participant and an event + belongs_to :participant, + :class_name => 'User', + :foreign_key => 'participant_id' + + belongs_to :event, + :counter_cache => true end diff --git a/app/views/game_areas/.show.html.erb.swp b/app/views/friends/._friends.html.erb.swp similarity index 91% rename from app/views/game_areas/.show.html.erb.swp rename to app/views/friends/._friends.html.erb.swp index a4d3235..f26464a 100644 Binary files a/app/views/game_areas/.show.html.erb.swp and b/app/views/friends/._friends.html.erb.swp differ diff --git a/app/views/games/.show.html.erb.swp b/app/views/games/.show.html.erb.swp deleted file mode 100644 index 4795733..0000000 Binary files a/app/views/games/.show.html.erb.swp and /dev/null differ diff --git a/app/controllers/.games_controller.rb.swp b/app/views/participations/._participants.html.erb.swp similarity index 76% rename from app/controllers/.games_controller.rb.swp rename to app/views/participations/._participants.html.erb.swp index 4122e1e..5baca90 100644 Binary files a/app/controllers/.games_controller.rb.swp and b/app/views/participations/._participants.html.erb.swp differ diff --git a/app/views/user_characters/.new.html.erb.swp b/app/views/participations/.new.html.erb.swp similarity index 88% rename from app/views/user_characters/.new.html.erb.swp rename to app/views/participations/.new.html.erb.swp index e427ecd..a2ff0a3 100644 Binary files a/app/views/user_characters/.new.html.erb.swp and b/app/views/participations/.new.html.erb.swp differ diff --git a/app/views/participations/_friends.html.erb b/app/views/participations/_friends.html.erb new file mode 100755 index 0000000..d9fe628 --- /dev/null +++ b/app/views/participations/_friends.html.erb @@ -0,0 +1,5 @@ +<ul> + <% friends.each do |friend| %> + <li style="list-style-type:none;" user_id=<%= friend.id %>><%= friend.login %> </li> + <% end %> +</ul> diff --git a/app/views/participations/_participants.html.erb b/app/views/participations/_participants.html.erb new file mode 100644 index 0000000..77cba41 --- /dev/null +++ b/app/views/participations/_participants.html.erb @@ -0,0 +1,5 @@ +<div new_record=<%= participation.new_record?%> participant_id=<%= participation.participant_id %> participation_id=<%= participation.new_record? ? 0: participation.id %>> + <p><%= user_icon(participation.participant) %></p> + <p><%= link_to_user participation.participant %> | <%= link_to_function 'delete', "participation_builder.remove_participation(#{participation.participant_id})" %></p> +</div> + diff --git a/app/views/participations/new.html.erb b/app/views/participations/new.html.erb new file mode 100644 index 0000000..d2f5c2c --- /dev/null +++ b/app/views/participations/new.html.erb @@ -0,0 +1,8 @@ +<%= javascript_include_tag 'participation.js' %> +<%= javascript_tag "participation_builder = new ParticipationBuilder(#{@user.id}, 0);" %> +<div id="participation_left_box"> +<p><%= text_field_with_auto_complete :event, :participations, {}, {:after_update_element => 'after_select' } %></p> +</div> +<div id="participation_right_box"> +<div id="participations"></div> +</div> diff --git a/app/views/user_blogs/._btag.html.erb.swp b/app/views/user_blogs/._btag.html.erb.swp new file mode 100644 index 0000000..a428e97 Binary files /dev/null and b/app/views/user_blogs/._btag.html.erb.swp differ diff --git a/app/views/user_blogs/.new.html.erb.swp b/app/views/user_blogs/.new.html.erb.swp new file mode 100644 index 0000000..1fb7e5d Binary files /dev/null and b/app/views/user_blogs/.new.html.erb.swp differ diff --git a/config/routes.rb b/config/routes.rb index 15eca91..4f0463d 100755 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,134 +1,140 @@ ActionController::Routing::Routes.draw do |map| + map.resources :participations + map.resources :pages map.resources :sessions map.resources :statuses map.resources :wall_messages map.resources :mails map.resources :icons map.resources :ptags map.resources :pdigs map.resources :pcomments map.resources :bdigs map.resources :friendships map.resources :game_characters, :collection => {:edit_new => :get} map.resources :game_races map.resources :game_professions map.resources :game_servers map.resources :game_areas map.resources :games map.root :controller => 'sessions', :action => 'new' map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate' map.forgot_password '/forgot_password', :controller => 'passwords', :action => 'new' map.reset_password '/reset_password/:password_reset_code', :controller => 'passwords', :action => 'edit' map.change_password '/change_password', :controller => 'accounts', :action => 'edit' map.resources :users, :member => {:enable => :put} do |users| users.resources :characters, :controller => 'user_characters', :member => {:confirm_destroy => :get} users.resources :wall_messages, :controller => 'user_wall_messages' users.resources :mails, :controller => 'mailboxes', :member => {:reply => :post}, :collection => {:read_multiple => :put, :unread_multiple => :put, :destroy_multiple => :delete} users.resources :friends, :collection => {:search => :get} users.resources :statuses, :controller => 'user_statuses' users.resources :blogs, :controller => 'user_blogs', :member => {:confirm_destroy => :get}, :collection => {:destroy_multiple => :delete} + + users.resources :videos, + :controller => 'user_videos', + :member => {:confirm_destroy => :get} users.resources :blog_feeds users.resources :tagged_blogs users.resources :albums, :controller => 'user_albums', :member => {:confirm_destroy => :get} users.resources :album_feeds users.resources :tagged_photos users.resource :profile users.resource :basic_info, :controller => 'basic_info' users.resource :contact_info, :controller => 'contact_info' end map.resources :blogs do |blogs| blogs.resources :comments, :controller => 'blog_comments' blogs.resources :tags, :controller => 'blog_tags' blogs.resources :digs, :controller => 'blog_digs' end map.resources :photos do |photos| photos.resources :comments, :controller => 'photo_comments' photos.resources :tags, :controller => 'photo_tags' photos.resources :digs, :controller => 'photo_digs' end map.resources :albums do |albums| albums.resources :photos, :controller => 'album_photos', :member => {:confirm_destroy => :get, :cover => :post}, :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} end map.resources :events map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/schema.rb b/db/schema.rb index 6f35ea0..493c384 100755 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,311 +1,349 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20090818062911) do create_table "albums", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "photos_count", :default => 0 t.string "title" t.text "description" t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomments", :force => true do |t| t.integer "user_id", :null => false t.integer "blog_id", :null => false t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "bdigs", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "blogs", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title", :limit => 64 t.text "content", :limit => 16777215 t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.boolean "draft", :default => true t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "btags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "cities", :force => true do |t| t.string "name" t.integer "city_id" t.datetime "created_at" t.datetime "updated_at" end create_table "countries", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "event_wall_messages", :force => true do |t| t.integer "event_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "events", :force => true do |t| t.string "title" t.integer "poster_id" t.integer "game_id" t.integer "game_server_id" t.integer "game_area_id" t.integer "album_id" t.integer "participations_count", :default => 0 t.datetime "time" t.text "description" t.datetime "created_at" t.datetime "updated_at" end create_table "friendships", :force => true do |t| t.integer "user_id" t.integer "friend_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_areas", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_characters", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "server_id" t.integer "area_id" t.integer "profession_id" t.integer "race_id" t.string "name" t.integer "level" t.boolean "playing" t.datetime "created_at" t.datetime "updated_at" end create_table "game_professions", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_races", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_servers", :force => true do |t| t.string "name" t.string "ip" t.integer "game_id" t.integer "area_id" t.datetime "created_at" t.datetime "updated_at" end create_table "games", :force => true do |t| t.string "name" t.string "company" t.datetime "sale_date" t.text "description" t.boolean "no_areas", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "icons", :force => true do |t| t.integer "user_id" t.boolean "current" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "mails", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.boolean "delete_by_sender", :default => false t.boolean "delete_by_receiver", :default => false t.boolean "read_by_sender", :default => true t.boolean "read_by_receiver", :default => false t.string "title" t.text "content" t.integer "parent_id" t.datetime "created_at" t.datetime "updated_at" end create_table "pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "participations", :force => true do |t| t.integer "participant_id" t.integer "event_id" t.integer "event_status", :default => 1 t.datetime "created_at" t.datetime "updated_at" end create_table "pcomments", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "pdigs", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.datetime "created_at" t.datetime "updated_at" end create_table "permissions", :force => true do |t| t.string "user_id" t.string "role_id" t.datetime "created_at" t.datetime "updated_at" end create_table "photos", :force => true do |t| t.integer "digs_count", :default => 0 t.integer "tags_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "album_id" t.boolean "cover", :default => false t.text "notation" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "provinces", :force => true do |t| t.string "name" t.integer "country_id" t.datetime "created_at" t.datetime "updated_at" end create_table "ptags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "photo_id" t.integer "x" t.integer "y" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "roles", :force => true do |t| t.string "name", :null => false t.datetime "created_at" t.datetime "updated_at" end create_table "statuses", :force => true do |t| t.integer "user_id" t.text "content" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :limit => 64 t.string "email", :limit => 128 t.string "crypted_password", :limit => 64 t.string "salt", :limit => 40 t.string "gender" t.boolean "enabled", :default => true t.string "remember_token" t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "password_reset_code", :limit => 40 t.integer "country_id" t.integer "province_id" t.integer "city_id" t.integer "qq" t.integer "mobile" t.string "website" t.datetime "birthday" t.datetime "created_at" t.datetime "updated_at" end + create_table "vcomments", :force => true do |t| + t.integer "user_id" + t.integer "video_id" + t.text "content" + t.boolean "whisper", :default => false + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "vdigs", :force => true do |t| + t.integer "user_id" + t.integer "video_id" + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "videos", :force => true do |t| + t.integer "user_id" + t.integer "game_id" + t.string "title" + t.string "url" + t.text "link" + t.integer "digs_count", :default => 0 + t.integer "comments_count", :default => 0 + t.integer "tags_count", :default => 0 + t.string "privilege" + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "vtags", :force => true do |t| + t.integer "user_id" + t.integer "tagged_user_id" + t.integer "video_id" + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "wall_messages", :force => true do |t| t.integer "user_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end end diff --git a/public/javascripts/.blog.js.swp b/public/javascripts/.blog.js.swp index 448b939..21b9f93 100644 Binary files a/public/javascripts/.blog.js.swp and b/public/javascripts/.blog.js.swp differ diff --git a/public/javascripts/.validator.js.swp b/public/javascripts/.validator.js.swp deleted file mode 100644 index a450acb..0000000 Binary files a/public/javascripts/.validator.js.swp and /dev/null differ diff --git a/public/javascripts/participation.js b/public/javascripts/participation.js new file mode 100644 index 0000000..fe17698 --- /dev/null +++ b/public/javascripts/participation.js @@ -0,0 +1,73 @@ + +function after_select(input_field, selected_li){ + alert('hello4'); + participation_builder.new_participation(selected_li.readAttribute('user_id')); + alert('hello5'); + $('event_participations').value = ''; +} + + +ParticipationBuilder = Class.create({ + initialize: function(user_id, event_id){ + this.user_id = user_id; + this.event_id = event_id; + + alert('hello'); + this.participation_input = $('event_participations'); + alert('hello1'); + this.participation_input.value = 'please tag your friend here'; + alert('hello2'); + + this.participation_input.observe('focus', function(event){ + this.value = ''; + }); + + this.participation_input.observe('blur', function(event){ + this.value = 'please tag your friends here'; + }); + + this.participations_div = $('participations'); + + this.participations = new Hash(); + var current_participations = this.participations_div.childElements(); + for(var i=0;i<current_participations.length;i++){ + this.participations.set(current_participations[i].readAttribute('participant_id'), current_participations[i]); + } + }, + + after_select: function(input_field, selected_li){ + this.new_participation(selected_li.readAttribute('user_id')); + $('event_participations').value = ''; + }, + + new_participation: function(participant_id){ + // if this user is already in participation list, skip it + if(this.participations.get(participant_id)) return; + // send ajax request to retrieve user information(icon, name ... so on) + new Ajax.Request('/participations/new_participation?participants[]=' + participant_id, { + method: 'get', + onSuccess: function(transport){ + this.participations_div.innerHTML = transport.responseText + this.participations_div.innerHTML; + this.participation_input.value = ''; + var children = this.participations_div.childElements(); + var length = children.length; + for(var i=0;i<length;i++){ + this.participations.set(children[i].readAttribute('participant_id'), children[i]); + } + }.bind(this) + }); + }, + + remove_participation: function(participant_id){ + var participation = this.participations.unset(participant_id); + if(!participation) return; + + // if it's not a new record, it means it stores in database, + // then do an ajax request to remove it from database + if(participation.readAttribute('new_record') != 'true') + new Ajax.Request('/participations/' + participation.readAttribute('participation_id'), {method: 'delete'}); + + participation.remove(); + }, + +}); diff --git a/test/functional/participations_controller_test.rb b/test/functional/participations_controller_test.rb new file mode 100644 index 0000000..58a66e2 --- /dev/null +++ b/test/functional/participations_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class ParticipationsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/helpers/participations_helper_test.rb b/test/unit/helpers/participations_helper_test.rb new file mode 100644 index 0000000..634b92c --- /dev/null +++ b/test/unit/helpers/participations_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class ParticipationsHelperTest < ActionView::TestCase +end
goodxiexin/dayday3
777b108603b3cad41cb4ba9defcb8ab5515c5816
event new created
diff --git a/app/controllers/.game_areas_controller.rb.swp b/app/controllers/.game_areas_controller.rb.swp new file mode 100644 index 0000000..2d3ea33 Binary files /dev/null and b/app/controllers/.game_areas_controller.rb.swp differ diff --git a/app/controllers/.games_controller.rb.swp b/app/controllers/.games_controller.rb.swp new file mode 100644 index 0000000..4122e1e Binary files /dev/null and b/app/controllers/.games_controller.rb.swp differ diff --git a/app/controllers/.user_characters_controller.rb.swp b/app/controllers/.user_characters_controller.rb.swp new file mode 100644 index 0000000..de19924 Binary files /dev/null and b/app/controllers/.user_characters_controller.rb.swp differ diff --git a/app/controllers/.users_controller.rb.swp b/app/controllers/.users_controller.rb.swp new file mode 100644 index 0000000..f4e5694 Binary files /dev/null and b/app/controllers/.users_controller.rb.swp differ diff --git a/app/controllers/event_wall_messages_controller.rb b/app/controllers/event_wall_messages_controller.rb new file mode 100644 index 0000000..15f4480 --- /dev/null +++ b/app/controllers/event_wall_messages_controller.rb @@ -0,0 +1,2 @@ +class EventWallMessagesController < ApplicationController +end diff --git a/app/controllers/events_controller.rb b/app/controllers/events_controller.rb new file mode 100644 index 0000000..e0fb29f --- /dev/null +++ b/app/controllers/events_controller.rb @@ -0,0 +1,30 @@ +class EventsController < ApplicationController + layout 'event' + + def index + end + + def new + @event = Event.new + @games = Game.all + end + + def show + end + + def create + @event = Event.new(params[:event]) + @event.save + flash[:notice] = "Event is successfully created" + redirect_to root_url + end + + def update + end + + def edit + end + + def destroy + end +end diff --git a/app/controllers/game_areas_controller.rb b/app/controllers/game_areas_controller.rb index fd49dbc..8651af4 100755 --- a/app/controllers/game_areas_controller.rb +++ b/app/controllers/game_areas_controller.rb @@ -1,87 +1,88 @@ class GameAreasController < ApplicationController # GET /game_areas # GET /game_areas.xml def index @game_areas = GameArea.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @game_areas } end end # GET /game_areas/1 # GET /game_areas/1.xml def show + @is_show = params[:show] @game_area = GameArea.find(params[:id]) @servers = @game_area.servers respond_to do |format| format.html # show.html.erb format.xml { render :xml => @game_area } end end # GET /game_areas/new # GET /game_areas/new.xml def new @game_area = GameArea.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @game_area } end end # GET /game_areas/1/edit def edit @game_area = GameArea.find(params[:id]) end # POST /game_areas # POST /game_areas.xml def create @game_area = GameArea.new(params[:game_area]) respond_to do |format| if @game_area.save flash[:notice] = 'GameArea was successfully created.' format.html { redirect_to(@game_area) } format.xml { render :xml => @game_area, :status => :created, :location => @game_area } else format.html { render :action => "new" } format.xml { render :xml => @game_area.errors, :status => :unprocessable_entity } end end end # PUT /game_areas/1 # PUT /game_areas/1.xml def update @game_area = GameArea.find(params[:id]) respond_to do |format| if @game_area.update_attributes(params[:game_area]) flash[:notice] = 'GameArea was successfully updated.' format.html { redirect_to(@game_area) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @game_area.errors, :status => :unprocessable_entity } end end end # DELETE /game_areas/1 # DELETE /game_areas/1.xml def destroy @game_area = GameArea.find(params[:id]) @game_area.destroy respond_to do |format| format.html { redirect_to(game_areas_url) } format.xml { head :ok } end end end diff --git a/app/controllers/games_controller.rb b/app/controllers/games_controller.rb index 23d88b2..59b0bcb 100755 --- a/app/controllers/games_controller.rb +++ b/app/controllers/games_controller.rb @@ -1,92 +1,93 @@ class GamesController < ApplicationController # GET /games # GET /games.xml def index @games = Game.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @games } end end # GET /games/1 # GET /games/1.xml def show + @is_show = params[:show] @game = Game.find(params[:id]) if @game.no_areas @servers = @game.areas else @areas = @game.areas end @races = @game.races @professions = @game.professions respond_to do |format| format.html { render :action => 'show'} format.xml { render :xml => @game } end end # GET /games/new # GET /games/new.xml def new @game = Game.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @game } end end # GET /games/1/edit def edit @game = Game.find(params[:id]) end # POST /games # POST /games.xml def create @game = Game.new(params[:game]) respond_to do |format| if @game.save flash[:notice] = 'Game was successfully created.' format.html { redirect_to(@game) } format.xml { render :xml => @game, :status => :created, :location => @game } else format.html { render :action => "new" } format.xml { render :xml => @game.errors, :status => :unprocessable_entity } end end end # PUT /games/1 # PUT /games/1.xml def update @game = Game.find(params[:id]) respond_to do |format| if @game.update_attributes(params[:game]) flash[:notice] = 'Game was successfully updated.' format.html { redirect_to(@game) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @game.errors, :status => :unprocessable_entity } end end end # DELETE /games/1 # DELETE /games/1.xml def destroy @game = Game.find(params[:id]) @game.destroy respond_to do |format| format.html { redirect_to(games_url) } format.xml { head :ok } end end end diff --git a/app/helpers/event_wall_messages_helper.rb b/app/helpers/event_wall_messages_helper.rb new file mode 100644 index 0000000..44dc9f6 --- /dev/null +++ b/app/helpers/event_wall_messages_helper.rb @@ -0,0 +1,2 @@ +module EventWallMessagesHelper +end diff --git a/app/helpers/events_helper.rb b/app/helpers/events_helper.rb new file mode 100644 index 0000000..8a9a878 --- /dev/null +++ b/app/helpers/events_helper.rb @@ -0,0 +1,2 @@ +module EventsHelper +end diff --git a/app/models/event.rb b/app/models/event.rb new file mode 100644 index 0000000..9bbb071 --- /dev/null +++ b/app/models/event.rb @@ -0,0 +1,56 @@ +class Event < ActiveRecord::Base + # the poster of this activity + belongs_to :poster, + :class_name => 'User' + + # the category of this activity + belongs_to :game + + # the location of the activity + belongs_to :game_server + + # teh wall messages for a event + has_many :event_wall_messages, + :dependent => :destroy, + :finder_sql => 'select event_wall_messages.* from event_wall_messages where event_wall_messages.user_id = #{id} OR event_wall_messages.receiver_id = #{id} ORDER BY created_at DESC' + + # participants of this activity + has_many :participations, + :dependent => :destroy + has_many :participants, + :through => :participations + + # others can comment your activity + has_many :comments, + :as => 'resource' + + # register the activity + def register(user_id) + user = User.find(user_id) + if user + self.participants << user + end + end + + # unregister the activity + def unregister(user_id) + user = self.participants.find(user_id) + if user + self.participants.delete(user) + end + end + + # cancel this activity + # this action is only allowed for the poster of this activity + def cancel(user_id) + if poster?(user_id) + self.destroy + end + end + + private + # if the user is the poster of this activity + def poster?(user_id) + (poster_id == user_id)? true : false + end +end diff --git a/app/models/event_wall_message.rb b/app/models/event_wall_message.rb index d9daf4d..1f6647e 100644 --- a/app/models/event_wall_message.rb +++ b/app/models/event_wall_message.rb @@ -1,2 +1,8 @@ class EventWallMessage < ActiveRecord::Base + + belongs_to :event + + belongs_to :poster, + :class_name => 'User' + :foreign_key => 'poster_id' end diff --git a/app/models/participation.rb b/app/models/participation.rb new file mode 100644 index 0000000..04cd6d2 --- /dev/null +++ b/app/models/participation.rb @@ -0,0 +1,2 @@ +class Participation < ActiveRecord::Base +end diff --git a/app/views/events/new.html.erb b/app/views/events/new.html.erb new file mode 100644 index 0000000..c461e90 --- /dev/null +++ b/app/views/events/new.html.erb @@ -0,0 +1,22 @@ +<% form_for @event, events_path do |f| %> +<div> +<%= f.label "title" %> +<%= collection_select :event, :game_id, @games, :id, :name, {:prompt => '---'}, {:onchange => "validate_game_id(this.value);game_onchange_event(this.value)"} %> +<a id='game_id_info'></a> +</div> +<div id=game_details></div> +<div> +<%= f.label "starting Date and Time" %> +<%= datetime_select :event, :time %> +<a id='event_time_form'></a> +</div> +<div> +<%= f.label "description:" %><br/> +<%= f.text_area :description %> +<a id='event_description_form'></a> +</div> +<div> +<%= f.submit "Next Step" %> +<a id='event_submit'></a> +</div> +<% end %> diff --git a/app/views/game_areas/.show.html.erb.swp b/app/views/game_areas/.show.html.erb.swp new file mode 100644 index 0000000..a4d3235 Binary files /dev/null and b/app/views/game_areas/.show.html.erb.swp differ diff --git a/app/views/game_areas/show.html.erb b/app/views/game_areas/show.html.erb index ab38313..d11187f 100755 --- a/app/views/game_areas/show.html.erb +++ b/app/views/game_areas/show.html.erb @@ -1,5 +1,10 @@ +<% if (@is_show==1) %> <% server_array = [['---', '---']] %> <% @servers.each { |server| server_array << [server.name, server.id] } %> <%= label_tag '', 'Game Server: ', :style => "width: 125px;float:left" %> <%= select_tag 'character[server_id]', options_for_select(server_array), :onchange => "validate_server_id(this.value)" %> <a id='server_id_info'></a> +<% else %> +<%= label_tag '', 'Game Server: ', :style => "width: 125px;float:left" %> +<%= collection_select :event, :game_server_id, @servers, :id, :name, {:prompt => '---'}, :onchange => "validate_server_id(this.value)"%> +<% end %> diff --git a/app/views/games/.show.html.erb.swp b/app/views/games/.show.html.erb.swp new file mode 100644 index 0000000..4795733 Binary files /dev/null and b/app/views/games/.show.html.erb.swp differ diff --git a/app/views/games/show.html.erb b/app/views/games/show.html.erb index ce6e528..008c22b 100755 --- a/app/views/games/show.html.erb +++ b/app/views/games/show.html.erb @@ -1,38 +1,60 @@ -<% if @game.no_areas %> +<% if (@is_show==1) %> + <% if @game.no_areas %> <% server_array = [['---', '---']] %> <% @servers.each { |server| server_array << [server.name, server.id] } %> <div id='servers'> <%= label_tag '', 'Game Server: ', :style => "width:125px;float:left"%> <%= select_tag 'character[server_id]', options_for_select(server_array), :onchange => "validate_server_id(this.value)"%> <a id='server_id_info'></a> </div> -<% else %> + <% else %> <% area_array = [['---','---']] %> <% @areas.each { |area| area_array << [area.name, area.id] } %> <div id='areas'> <%= label_tag '', 'Game Area: ', :style => "width:125px;float:left"%> - <%= select_tag 'character[area_id]', options_for_select(area_array), :onchange => "validate_area_id(this.value);area_onchange(this.value)" %> + <%= select_tag 'character[area_id]', options_for_select(area_array), :onchange => "validate_area_id(this.value);area_onchange(this.value,1)" %> <a id='area_id_info'></a> </div> <div id='servers'> <%= label_tag '', 'Game Server: ', :style => "width:125px;float:left"%> <%= select_tag 'character[server_id]', options_for_select([['---', '---']]) %> <a id='server_id_info'></a> </div> -<% end %> + <% end %> <% race_array = [['---', '---']] %> <% @races.each { |race| race_array << [race.name, race.id] } %> <div id='races'> <%= label_tag '', 'Game Race: ', :style => "width:125px;float:left"%> <%= select_tag 'character[race_id]', options_for_select(race_array), :onchange => "validate_race_id(this.value)" %> <a id='race_id_info'></a> </div> <% profession_array = [['---', '---']] %> <% @professions.each { |profession| profession_array << [profession.name, profession.id] } %> <div id='professions'> <%= label_tag '', 'profession: ', :style => "width:125px;float:left"%> <%= select_tag 'character[profession_id]', options_for_select(profession_array), :onchange => "validate_profession_id(this.value)" %> <a id='profession_id_info'></a> </div> +<% else %> + + <% if @game.no_areas %> + <div id='servers'> + <%= label_tag '', 'Game Server: ', :style => "width:125px;float:left"%> + <%= collection_select :event, :game_server_id, @servers, :id, :name, {:prompt => '---'}, :onchange => "validate_server_id(this.value)"%> + <a id='server_id_info'></a> + </div> + <% else %> + <div id='areas'> + <%= label_tag '', 'Game Area: ', :style => "width:125px;float:left"%> + <%= collection_select :event, :game_area_id, @areas, :id, :name, {:prompt => '---'}, :onchange => "validate_area_id(this.value);area_onchange(this.value,0)" %> + <a id='area_id_info'></a> + </div> + <div id='servers'> + <%= label_tag '', 'Game Server: ', :style => "width:125px;float:left"%> + <%= select_tag 'event[server_id]', options_for_select([['---', '---']]) %> + <a id='server_id_info'></a> + </div> + <% end %> +<% end %> diff --git a/app/views/layouts/event.html.erb b/app/views/layouts/event.html.erb new file mode 100755 index 0000000..8a5d21d --- /dev/null +++ b/app/views/layouts/event.html.erb @@ -0,0 +1,38 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html> +<head> + <%= stylesheet_link_tag "user" %> + <%= stylesheet_link_tag 'facebox' %> + <%= javascript_include_tag :defaults %> + <%= javascript_include_tag 'facebox' %> + <%= javascript_include_tag 'validator' %> +</head> +<body> + <div id="container"> +  <div id="header"> + <%= render :partial => 'layouts/user_menus' %> +  </div> + <div id='containter'> +   <div id="left"> + <%= yield :left %> + </div> +  <div id="middle"> + <% if flash[:notice] %> + <div id='notice'><%= flash[:notice] %></div> + <% end -%> + <% if flash[:error] %> + <div id='error'><%= flash[:error] %></div> + <% end -%> + <%= yield %> +   </div> + <div id="right"> + <%= yield :right %> +   </div> + </div> +  <div id="footer"> + <!-- Dayday3 Group: xiahong gao, xin xie --> +  </div> +</div> +</body> + diff --git a/app/views/user_characters/.new.html.erb.swp b/app/views/user_characters/.new.html.erb.swp new file mode 100644 index 0000000..e427ecd Binary files /dev/null and b/app/views/user_characters/.new.html.erb.swp differ diff --git a/app/views/user_characters/new.html.erb b/app/views/user_characters/new.html.erb index 9a4985c..0c34ee2 100755 --- a/app/views/user_characters/new.html.erb +++ b/app/views/user_characters/new.html.erb @@ -1,25 +1,24 @@ <h3> New Game Character </h3> <% form_for :character, :html => {:id => 'character_form'} do |f| %> <div> <%= f.label 'game_id', "Game Name: ", :style => "width:125px;float:left" %> <% game_array = [['---', '---']] %> <% @games.each { |game| game_array << [game.name, game.id] } %> <%= select_tag 'character[game_id]', options_for_select(game_array), :onchange => "validate_game_id(this.value);game_onchange(this.value)"%> <a id='game_id_info'></a> </div> <div> <%= f.label '', "Character ID: ", :style => "width:125px;float:left" %> <%= f.text_field 'name', :size => 10, :onfocus => "show_name_requirement()", :onblur => "validate_name(this.value)" %> <a id='name_info'></a> </div> <div> <%= f.label '', "Character level: ", :style => "width:125px;float:left" %> <%= f.text_field 'level', :size => 10, :onfocus => "show_level_requirement()", :onblur => "validate_level(this.value)" %> <a id='level_info'></a> </div> <div id=details></div> <% end %> <%= link_to_function 'complete', "add_user_character(#{@user.id})" %> - diff --git a/config/database.yml b/config/database.yml index 944db3d..3ec9566 100755 --- a/config/database.yml +++ b/config/database.yml @@ -1,48 +1,48 @@ # MySQL. Versions 4.1 and 5.0 are recommended. # # Install the MySQL driver: # gem install mysql # On Mac OS X: # sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql # On Mac OS X Leopard: # sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config # This sets the ARCHFLAGS environment variable to your native architecture # On Windows: # gem install mysql # Choose the win32 build. # Install MySQL and put its /bin directory on your path. # # And be sure to use new-style password hashing: # http://dev.mysql.com/doc/refman/5.0/en/old-client.html development: adapter: mysql encoding: utf8 reconnect: false database: dayday3_development pool: 5 username: root - password: 20041065 + password: 123456 socket: /var/run/mysqld/mysqld.sock # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: mysql encoding: utf8 reconnect: false database: dayday3_test pool: 5 username: root - password: + password: 123456 socket: /var/run/mysqld/mysqld.sock production: adapter: mysql encoding: utf8 reconnect: false database: dayday3_production pool: 5 username: root - password: + password: 123456 socket: /var/run/mysqld/mysqld.sock diff --git a/config/routes.rb b/config/routes.rb index d21c8ed..15eca91 100755 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,133 +1,134 @@ ActionController::Routing::Routes.draw do |map| map.resources :pages map.resources :sessions map.resources :statuses map.resources :wall_messages map.resources :mails map.resources :icons map.resources :ptags map.resources :pdigs map.resources :pcomments map.resources :bdigs map.resources :friendships map.resources :game_characters, :collection => {:edit_new => :get} map.resources :game_races map.resources :game_professions map.resources :game_servers map.resources :game_areas map.resources :games map.root :controller => 'sessions', :action => 'new' map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate' map.forgot_password '/forgot_password', :controller => 'passwords', :action => 'new' map.reset_password '/reset_password/:password_reset_code', :controller => 'passwords', :action => 'edit' map.change_password '/change_password', :controller => 'accounts', :action => 'edit' map.resources :users, :member => {:enable => :put} do |users| users.resources :characters, :controller => 'user_characters', :member => {:confirm_destroy => :get} users.resources :wall_messages, :controller => 'user_wall_messages' users.resources :mails, :controller => 'mailboxes', :member => {:reply => :post}, :collection => {:read_multiple => :put, :unread_multiple => :put, :destroy_multiple => :delete} users.resources :friends, :collection => {:search => :get} users.resources :statuses, :controller => 'user_statuses' users.resources :blogs, :controller => 'user_blogs', :member => {:confirm_destroy => :get}, :collection => {:destroy_multiple => :delete} users.resources :blog_feeds users.resources :tagged_blogs users.resources :albums, :controller => 'user_albums', :member => {:confirm_destroy => :get} users.resources :album_feeds users.resources :tagged_photos users.resource :profile users.resource :basic_info, :controller => 'basic_info' users.resource :contact_info, :controller => 'contact_info' end map.resources :blogs do |blogs| blogs.resources :comments, :controller => 'blog_comments' blogs.resources :tags, :controller => 'blog_tags' blogs.resources :digs, :controller => 'blog_digs' end map.resources :photos do |photos| photos.resources :comments, :controller => 'photo_comments' photos.resources :tags, :controller => 'photo_tags' photos.resources :digs, :controller => 'photo_digs' end map.resources :albums do |albums| albums.resources :photos, :controller => 'album_photos', :member => {:confirm_destroy => :get, :cover => :post}, :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} end + map.resources :events map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/migrate/20090818030745_create_event_wall_messages.rb b/db/migrate/20090818030745_create_event_wall_messages.rb index 9e8c370..c01b22e 100644 --- a/db/migrate/20090818030745_create_event_wall_messages.rb +++ b/db/migrate/20090818030745_create_event_wall_messages.rb @@ -1,16 +1,16 @@ class CreateEventWallMessages < ActiveRecord::Migration def self.up create_table :event_wall_messages do |t| - t.integer :activity_id + t.integer :event_id t.integer :poster_id t.integer :receiver_id t.text :content t.boolean :whisper, :default => false t.timestamps end end def self.down drop_table :event_wall_messages end end diff --git a/db/migrate/20090818060826_create_events.rb b/db/migrate/20090818060826_create_events.rb new file mode 100644 index 0000000..194622f --- /dev/null +++ b/db/migrate/20090818060826_create_events.rb @@ -0,0 +1,20 @@ +class CreateEvents < ActiveRecord::Migration + def self.up + create_table :events do |t| + t.string :title + t.integer :poster_id + t.integer :game_id + t.integer :game_server_id + t.integer :game_area_id + t.integer :album_id + t.integer :participations_count, :default => 0 + t.datetime :time + t.text :description + t.timestamps + end + end + + def self.down + drop_table :events + end +end diff --git a/db/migrate/20090818062911_create_participations.rb b/db/migrate/20090818062911_create_participations.rb new file mode 100644 index 0000000..dde84dd --- /dev/null +++ b/db/migrate/20090818062911_create_participations.rb @@ -0,0 +1,14 @@ +class CreateParticipations < ActiveRecord::Migration + def self.up + create_table :participations do |t| + t.integer :participant_id + t.integer :event_id + t.integer :event_status, :default => 1 + t.timestamps + end + end + + def self.down + drop_table :participations + end +end diff --git a/db/schema.rb b/db/schema.rb index b5b252b..6f35ea0 100755 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,279 +1,311 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090816174114) do +ActiveRecord::Schema.define(:version => 20090818062911) do create_table "albums", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "photos_count", :default => 0 t.string "title" t.text "description" t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomments", :force => true do |t| t.integer "user_id", :null => false t.integer "blog_id", :null => false t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "bdigs", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "blogs", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title", :limit => 64 t.text "content", :limit => 16777215 t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.boolean "draft", :default => true t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "btags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "cities", :force => true do |t| t.string "name" t.integer "city_id" t.datetime "created_at" t.datetime "updated_at" end create_table "countries", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end + create_table "event_wall_messages", :force => true do |t| + t.integer "event_id" + t.integer "poster_id" + t.integer "receiver_id" + t.text "content" + t.boolean "whisper", :default => false + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "events", :force => true do |t| + t.string "title" + t.integer "poster_id" + t.integer "game_id" + t.integer "game_server_id" + t.integer "game_area_id" + t.integer "album_id" + t.integer "participations_count", :default => 0 + t.datetime "time" + t.text "description" + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "friendships", :force => true do |t| t.integer "user_id" t.integer "friend_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_areas", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_characters", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "server_id" t.integer "area_id" t.integer "profession_id" t.integer "race_id" t.string "name" t.integer "level" t.boolean "playing" t.datetime "created_at" t.datetime "updated_at" end create_table "game_professions", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_races", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_servers", :force => true do |t| t.string "name" t.string "ip" t.integer "game_id" t.integer "area_id" t.datetime "created_at" t.datetime "updated_at" end create_table "games", :force => true do |t| t.string "name" t.string "company" t.datetime "sale_date" t.text "description" t.boolean "no_areas", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "icons", :force => true do |t| t.integer "user_id" t.boolean "current" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "mails", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.boolean "delete_by_sender", :default => false t.boolean "delete_by_receiver", :default => false t.boolean "read_by_sender", :default => true t.boolean "read_by_receiver", :default => false t.string "title" t.text "content" t.integer "parent_id" t.datetime "created_at" t.datetime "updated_at" end create_table "pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end + create_table "participations", :force => true do |t| + t.integer "participant_id" + t.integer "event_id" + t.integer "event_status", :default => 1 + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "pcomments", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "pdigs", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.datetime "created_at" t.datetime "updated_at" end create_table "permissions", :force => true do |t| t.string "user_id" t.string "role_id" t.datetime "created_at" t.datetime "updated_at" end create_table "photos", :force => true do |t| t.integer "digs_count", :default => 0 t.integer "tags_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "album_id" t.boolean "cover", :default => false t.text "notation" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "provinces", :force => true do |t| t.string "name" t.integer "country_id" t.datetime "created_at" t.datetime "updated_at" end create_table "ptags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "photo_id" t.integer "x" t.integer "y" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "roles", :force => true do |t| t.string "name", :null => false t.datetime "created_at" t.datetime "updated_at" end create_table "statuses", :force => true do |t| t.integer "user_id" t.text "content" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :limit => 64 t.string "email", :limit => 128 t.string "crypted_password", :limit => 64 t.string "salt", :limit => 40 t.string "gender" t.boolean "enabled", :default => true t.string "remember_token" t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "password_reset_code", :limit => 40 t.integer "country_id" t.integer "province_id" t.integer "city_id" t.integer "qq" t.integer "mobile" t.string "website" t.datetime "birthday" t.datetime "created_at" t.datetime "updated_at" end create_table "wall_messages", :force => true do |t| t.integer "user_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end end diff --git a/public/javascripts/.validator.js.swp b/public/javascripts/.validator.js.swp new file mode 100644 index 0000000..a450acb Binary files /dev/null and b/public/javascripts/.validator.js.swp differ diff --git a/public/javascripts/validator.js b/public/javascripts/validator.js index dfb978b..b9004f5 100755 --- a/public/javascripts/validator.js +++ b/public/javascripts/validator.js @@ -1,523 +1,532 @@ + function show_qq_requirement(){ $('qq_info').innerHTML = '<span style="color:grey">input your real qq</span>'; } function validate_qq(qq){ var info = $('qq_info'); if(qq == '') return true; //qq is not mandatory if(qq.length < 6 || qq.length > 11){ info.innerHTML = '<span style="color: red">this qq number is not valid</span>'; return false; } if(parseInt(qq)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits are allowed here</span>'; return false; } } function show_webiste_requirement(){ $('website_info').innerHTML = '<span style="color:grey">input your personal website</span>'; } function validate_website(website){ var info = $('website_info'); info.innerHTML = '<span style="color: green">valid</span>'; return true; } function show_mobile_requirement(){ $('mobile_info').innerHTML = '<span style="color:grey">input your mobile number</span>'; } function validate_mobile(mobile){ var info = $('mobile_info'); if(mobile == '') return true; //qq is not mandatory if(mobile.length != 11){ info.innerHTML = '<span style="color: red">this mobile phone number is not valid</span>'; return false; } if(parseInt(mobile)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits are allowed here</span>'; return false; } } function validate_contact_info(){ var error = false; var qq = $('user_qq').value; var mobile = $('user_mobile').value; var website = $('user_website').value; if(!validate_qq(qq)) error = true; if(!validate_mobile(mobile)) error = true; if(!validate_website(website)) error = true; return error; } function update_contact_info(user_id){ if(validate_contact_info()) return; var form = $('contact_form'); var url = '/users/' + user_id + '/contact_info?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function validate_basic_info(){ var error = false; var login = $('user_login').value; if(!validate_login(login)) error = true; return error; } function update_basic_info(user_id){ if(validate_basic_info()) return; var form = $('basic_form'); var url = '/users/' + user_id + '/basic_info?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function show_login_requirement(){ $('login_info').setStyle({color: 'grey'}); $('login_info').innerHTML = 'only digits, letters and underscore are allowed, range 4..16'; } function validate_login(name){ var info = $('login_info'); // check presence if(name == ''){ info.innerHTML = '<span style="color: red">login cannot be blank</span>'; return false; } // check length if(name.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(name.length > 16){ info.innerHTML = '<span style="color: red">too long, at most 16 characters</span>'; return false; } // check pattern first = name[0]; if((first >= 'a' && first <= 'z') || (first >= 'A' && first <= 'Z')){ if(name.match(/[A-Za-z0-9\_]+/)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits, letters and underscore are allowed</span>'; return false; } }else{ info.innerHTML = '<span style="color: red">must start with A-Z or a-z</span>'; return false; } } function show_email_requirement(){ $('email_info').setStyle({color: 'grey'}); $('email_info').innerHTML = 'please input valid email box' } function validate_email(email){ var info = $('email_info'); // check presence if(email == ''){ info.innerHTML = '<span style="color: red">email cannot be blank</span>'; return false; } // check length if(email.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(email.length > 100){ info.innerHTML = '<span style="color: red">too long, at most 100 characters</span>'; return false; } // check pattern if(email.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)){ // send ajax request to check uniqueness new Ajax.Request('/validator/validates_email_uniqueness?email='+email, { method: 'get', onSuccess: function(transport){ var info = $('email_info'); if(transport.responseText == 'yes'){ info.innerHTML = '<span style="color: green">valid</span>'; }else{ info.innerHTML = '<span style="color: red">this email has already been occupied</span>'; } } }); return true; }else{ info.innderHTML = '<span style="color: red">invalid email format</span>'; return false; } } function show_password_requirement(){ $('password_info').setStyle({color: 'grey'}); $('password_info').innerHTML = 'password consists of 6-20 characters' } function validate_password(password){ var info = $('password_info') var strongReg = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g"); var mediumReg = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g"); // check length if(password.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(password.length > 20){ info.innerHTML = '<span style="color: red">too long, at most 20 characters</span>'; return false; } // check strength if(password.match(strongReg)){ info.innerHTML = '<span style="color: green">Valid: Strong Strength!</span>'; return true; }else if(password.match(mediumReg)){ info.innerHTML = '<span style="color: orange">Valid: Medium Strength!</span>'; return true; }else{ info.innerHTML = '<span style="color: red"> Valid: Weak Strength!</span>'; return true; } } function show_password_confirm_requirement(){ $('password_confirmation_info').setStyle({color: 'grey'}); $('password_confirmation_info').innerHTML = 'confirm your password' } function validate_password_confirmation(password_confirmation){ var info = $('password_confirmation_info'); var password = $('user_password').value; if(password == ''){ info.innerHTML = '<span style="color: red"> password cannot be blank </span>'; return false; } if(password == password_confirmation){ info.innerHTML = '<span style="color: green">Valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">Two passwords are not consistent</span>'; return false; } } function validate_register_info(){ var error = false; var login = $('user_login').value; var email = $('user_email').value; var password = $('user_password').value; var password_confirmation = $('user_password_confirmation').value; if(!validate_login(login)) error = true; if(!validate_email(email)) error = true; if(!validate_password(password)) error = true; if(!validate_password_confirmation(password_confirmation)) error = true; var form = $('register_form'); var cs = $('characters').childElements(); var length = cs.length; if(length == 0){ $('character_info').innerHTML = '<span style="color:red">You must specify at least one game character</span>' error = true; } return error; } function validate_game_id(game_id){ var info = $('game_id_info'); if(game_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> game cannot be blank </span>'; return false; } } function game_onchange(game_id){ if(game_id == '---'){ $('details').innerHTML = ''; }else{ - new Ajax.Updater('details', '/games/' + game_id, {method: 'get'}); + new Ajax.Updater('details', '/games/' + game_id + '?show=1', {method: 'get'}); + } +} + +function game_onchange_event(game_id){ + if(game_id == '---'){ + $('game_details').innerHTML = ''; + }else{ + new Ajax.Updater('game_details', '/games/' + game_id+'?show=0', {method: 'get'}); } } function show_name_requirement(){ var info = $('name_info'); info.innerHTML = '<span style="color: grey"> Input your character name </span>'; } function validate_name(name){ var info = $('name_info'); if(name == ''){ info.innerHTML = '<span style="color: red"> name cannot be blank </span>'; return false; }else{ info.innerHTML = '<span style="color: green"> valid </span>'; return true; } } function show_level_requirement(){ var info = $('level_info'); info.innerHTML = '<span style="color: grey"> Input your character level </span>'; } function validate_level(level){ var info = $('level_info'); if(level == ''){ info.innerHTML = '<span style="color: red"> level cannot be blank </span>'; return false; }else{ if(parseInt(level)){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> level should be an integer </span>'; return false; } } } function validate_server_id(server_id){ var info = $('server_id_info'); if(server_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> server cannot be blank </span>'; return false; } } function validate_area_id(area_id){ var info = $('area_id_info'); if(area_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> area cannot be blank </span>'; return false; } } -function area_onchange(area_id){ +function area_onchange(area_id,showValue){ if(area_id == '---'){ $('servers').innerHTML = '<label style="width:125px;float:left">Game Server:</label><select id="server_id" name="server_id"><option value="---">---</option></select>'; }else{ - new Ajax.Updater('servers', '/game_areas/' + area_id, {method: 'get'}); + new Ajax.Updater('servers', '/game_areas/' + area_id +'?show='+showValue, {method: 'get'}); } } function validate_race_id(race_id){ var info = $('race_id_info'); if(race_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> race cannot be blank </span>'; return false; } } function validate_profession_id(profession_id){ var info = $('profession_id_info'); if(profession_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> profession cannot be blank </span>'; return false; } } var nr=0; function validate_game_character(){ // check all parameters var error = false; var game_id = $('character_game_id').value; var name = $('character_name').value; var level = $('character_level').value; if(!validate_name(name)) error = true; if(!validate_level(level)) error = true; if(!validate_game_id(game_id)) error = true; if(game_id == '---') return true; var server_id = $('character_server_id').value; var race_id = $('character_race_id').value; var profession_id = $('character_profession_id').value; var area_id = null; if(!validate_server_id(server_id)) error = true; alert(1); if(!validate_race_id(race_id)) error = true; alert(2); if(!validate_profession_id(profession_id)) error = true; alert(3); if($('character_area_id') != null){ area_id = $('character_area_id').value; if(!validate_area_id(area_id)) error = true; } alert(4); return error; } function construct_game_character_element(){ var game_id = $('character_game_id').value; var name = $('character_name').value; var level = $('character_level').value; var server_id = $('character_server_id').value; var race_id = $('character_race_id').value; var profession_id = $('character_profession_id').value; var area_id = null; // construct a character element that will show on registration page // html code looks like: // <li character_attributes> character_name <a href='#' onClick='edit_character'>edit</a> <a href='#' onClick='delete_character'>edit</a></li> var li = new Element('li', {id: 'character'+nr, game_id: game_id, name: name, level: level, server_id: server_id, race_id: race_id, profession_id: profession_id}); if($('character_area_id') != null){ area_id = $('character_area_id').value; li.writeAttribute({area_id: area_id}); } // construct label var label = new Element('label').update(name); // construct url var parameters = 'id='+nr+'&' +$('character_form').serialize(); var url = '/game_characters/edit_new?' + parameters; var edit_link = new Element('a', { href: url, rel: 'facebox'}).update('edit'); alert(url); // construct delete link and its event var delete_link = new Element('a', { href: '#'}).update('delete'); delete_link.observe('click', function(event){ this.parentNode.remove(); }); // append elements to li li.appendChild(label); li.appendChild(edit_link); li.appendChild(delete_link); nr++; return li; } function add_character(){ if(validate_game_character()) return; $('characters').insert(construct_game_character_element()); // close current facebox facebox.watchClickEvents(); facebox.close(); } function add_user_character(user_id){ if(validate_game_character()) return; var form = $('character_form'); var url = '/users/' + user_id + '/characters?' + form.serialize(); new Ajax.Request(url, {method: 'post'}); } function update_character(id){ if(validate_game_character()) return; $('character'+id).replace(construct_game_character_element()); // close current facebox facebox.watchClickEvents(); facebox.close(); } function update_user_character(user_id, id){ if(validate_game_character()) return; var form = $('character_form'); var url = '/users/' + user_id + '/characters/' + id + '?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function validate_and_request(){ if(validate_register_info()) return; // check if user has input at least one game character var form = $('register_form'); var cs = $('characters').childElements(); var length = cs.length; // construct url and parameter var parameters = ''; for(var i=0;i<length;i++){ var game_id = cs[i].readAttribute('game_id'); var name = cs[i].readAttribute('name'); var level = cs[i].readAttribute('level'); var area_id = cs[i].readAttribute('area_id'); var server_id = cs[i].readAttribute('server_id'); var race_id = cs[i].readAttribute('race_id'); var profession_id = cs[i].readAttribute('profession_id'); parameters += 'cs[][game_id]='+game_id+'&cs[][name]='+name+'&cs[][level]='+level+'&cs[][server_id]='+server_id+'&cs[][race_id]='+race_id+'&cs[][profession_id]='+profession_id; if(area_id != null) parameters += '&cs[][area_id]=' + area_id; parameters += '&'; } parameters += form.serialize(); url = '/users?' + parameters; // send request to server new Ajax.Request(url, {method: 'post'}); } diff --git a/test/fixtures/events.yml b/test/fixtures/events.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/events.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/fixtures/participations.yml b/test/fixtures/participations.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/participations.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/functional/event_wall_messages_controller_test.rb b/test/functional/event_wall_messages_controller_test.rb new file mode 100644 index 0000000..3c80390 --- /dev/null +++ b/test/functional/event_wall_messages_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class EventWallMessagesControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/events_controller_test.rb b/test/functional/events_controller_test.rb new file mode 100644 index 0000000..313df4b --- /dev/null +++ b/test/functional/events_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class EventsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/event_test.rb b/test/unit/event_test.rb new file mode 100644 index 0000000..c2b9b78 --- /dev/null +++ b/test/unit/event_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class EventTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/helpers/event_wall_messages_helper_test.rb b/test/unit/helpers/event_wall_messages_helper_test.rb new file mode 100644 index 0000000..bc3babc --- /dev/null +++ b/test/unit/helpers/event_wall_messages_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class EventWallMessagesHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/events_helper_test.rb b/test/unit/helpers/events_helper_test.rb new file mode 100644 index 0000000..2e7567e --- /dev/null +++ b/test/unit/helpers/events_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class EventsHelperTest < ActionView::TestCase +end diff --git a/test/unit/participation_test.rb b/test/unit/participation_test.rb new file mode 100644 index 0000000..3a2efe1 --- /dev/null +++ b/test/unit/participation_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class ParticipationTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end
goodxiexin/dayday3
4dcc82368d00b155658a6bd0e6ef652a97272e7f
video uploaded and javascript fixed
diff --git a/app/controllers/blog_digs_controller.rb b/app/controllers/blog_digs_controller.rb index 9e9f5b9..5cd9fb5 100755 --- a/app/controllers/blog_digs_controller.rb +++ b/app/controllers/blog_digs_controller.rb @@ -1,18 +1,20 @@ class BlogDigsController < ApplicationController + before_filter :login_required + def create @blog = Blog.find(params[:blog_id]) if @blog.digs.find_by_user_id(current_user.id) render :update do |page| page << "alert('You have dugg before');" end else @blog.digs.create(:user_id => current_user.id) render :update do |page| page << "var count = parseInt($('digs_count_#{@blog.id}').innerHTML) + 1; $('digs_count_#{@blog.id}').innerHTML = count;" end end end end diff --git a/app/controllers/user_blogs_controller.rb b/app/controllers/user_blogs_controller.rb index f9c685b..55b6551 100755 --- a/app/controllers/user_blogs_controller.rb +++ b/app/controllers/user_blogs_controller.rb @@ -1,138 +1,138 @@ class UserBlogsController < ApplicationController layout 'user' before_filter :login_required, :except => [:index, :show] def index @user = User.find(params[:user_id]) if params[:draft].to_i == 0 @blogs = @user.blogs.paginate :page => params[:page], :per_page => 10, :order => 'updated_at DESC' render :action => 'blogs_index' elsif params[:draft].to_i == 1 @blogs = @user.drafts.paginate :page => params[:page], :per_page => 10, :order => 'updated_at DESC' render :action => 'drafts_index' end end def show @user = User.find(params[:user_id]) @blog = @user.blogs.find(params[:id]) end def new @user = User.find(params[:user_id]) @blog = Blog.new end def create @user = User.find(params[:user_id]) Blog.transaction do @blog = Blog.new(params[:blog]) @blog.user = @user @blog.save params[:tagged_users].each do |user_id| @blog.tags.create(:user_id => @user.id, :tagged_user_id => user_id) end unless params[:tagged_users].blank? end render :update do |page| - page.redirect_to user_blogs_url(:user_id => current_user, :draft => params[:blog][:draft]) + page.redirect_to user_blogs_url(current_user, :draft => params[:blog][:draft]) end rescue # transaction aborts flash.now[:error] = "There was an error while saving this blog" render :action => 'new' end def edit @blog = Blog.find(params[:id]) @user = User.find(params[:user_id]) end def update @user = User.find(params[:user_id]) @blog = @user.blogs.find(params[:id]) Blog.transaction do @blog.update_attributes(params[:blog]) params[:tagged_users].each do |user_id| @blog.tags.create(:user_id => @user.id, :tagged_user_id => user_id) end unless params[:tagged_users].blank? end render :update do |page| page.redirect_to user_blogs_url(:user_id => @user, :draft => params[:blog][:draft]) end rescue falsh.now[:error] = 'There was a problem updating this blog' render :action => 'edit' end def confirm_destroy @user = User.find(params[:user_id]) @blog = Blog.find(params[:id]) render :action => 'confirm_destroy', :layout => false end def destroy @user = current_user @blog = @user.blogs.find(params[:id]) if session[:validation_text] == params[:validation_text] @blog.destroy render :update do |page| page.redirect_to user_blogs_url(:user_id => @user, :draft => params[:draft]) end else render :update do |page| page << "$('error').innerHTML = 'incorrect validation code'" end end end def destroy_multiple @user = User.find(params[:user_id]) Blog.transaction do params[:blogs].each { |id| @user.drafts.find(id).destroy } end render :update do |page| page.redirect_to user_blogs_url(:user_id => @user, :draft => 1) end rescue flash.now[:error] = 'There was a problem deleting these drafts' render :action => 'index', :draft => 1 end def new_tag btags = [] params[:tagged_users].each do |tagged_user_id| btags << Btag.new(:tagged_user_id => tagged_user_id) end render :partial => "btag", :collection => btags end def games_list @user = current_user render :partial => 'games_list', :object => @user.games end def friends_list @user = current_user if params[:game_id] == 'all' @friends = @user.friends else game = Game.find(params[:game_id]) @friends = @user.friends.find_all {|f| f.games.include?(game) } end render :partial => 'friends_list', :object => @friends end def show_popup_tag @user = User.find(params[:tagged_user_id]) render :partial => 'popup_tag' end def auto_complete_for_blog_tags @user = current_user @friends = @user.friends.find_all {|f| f.login.include?(params[:blog][:tags]) } render :partial => 'friends' end end diff --git a/app/controllers/user_videos_controller.rb b/app/controllers/user_videos_controller.rb new file mode 100644 index 0000000..176bd82 --- /dev/null +++ b/app/controllers/user_videos_controller.rb @@ -0,0 +1,107 @@ +class UserVideosController < ApplicationController + + layout 'user' + + before_filter :login_required + + def index + @user = User.find(params[:user_id]) + @videos = @user.videos.paginate :page => params[:page], :per_page => 10, :order => 'updated_at DESC' + end + + def new + @user = User.find(params[:user_id]) + @video = Video.new + @games = Game.all + end + + def create + @user = User.find(params[:user_id]) + Video.transaction do + @video = Video.new(params[:video]) + @video.user = @user + @video.link = Video.generate_link(@video.url) + @video.save + params[:tagged_users].each do |user_id| + @blog.tags.create(:user_id => @user.id, :tagged_user_id => user_id) + end unless params[:tagged_users].blank? + end + render :update do |page| + page.redirect_to user_videos_url(@user)#:action => 'index', :user_id => @user + end + rescue Video::VideoURLNotValid + @games = Game.all + flash[:error] = "only tudou and youku are supported" + render :action => 'new' + rescue + @games = Game.all + flash.now[:error] = "There was an error creating this video" + render :action => 'new' + end + + def show + @user = User.find(params[:user_id]) + @video = Video.find(params[:id]) + end + + def edit + @user = User.find(params[:user_id]) + @video = Video.find(params[:id]) + @games = Game.all + end + + def update + @user = User.find(params[:user_id]) + @video = @user.videos.find(params[:id]) + Video.transaction do + @video.update_attributes(params[:video]) + params[:tagged_users].each do |user_id| + @video.tags.create(:user_id => @user.id, :tagged_user_id => user_id) + end unless params[:tagged_users].blank? + end + render :update do |page| + page.redirect_to user_videos_url(@user) + end + rescue + @games = Game.all + flash.now[:error] = 'There was a problem updating this blog' + render :action => 'edit' + end + + def confirm_destroy + @user = User.find(params[:user_id]) + @video = Video.find(params[:id]) + render :action => 'confirm_destroy', :layout => false + end + + def destroy + @user = User.find(params[:user_id]) + @video = @user.videos.find(params[:id]) + + if session[:validation_text] == params[:validation_text] + @video.destroy + render :update do |page| + page.redirect_to user_videos_url(@user) + end + else + render :update do |page| + page << "$('error').innerHTML = 'incorrect validation code'" + end + end + end + + def new_tag + vtags = [] + params[:tagged_users].each do |tagged_user_id| + vtags << Vtag.new(:tagged_user_id => tagged_user_id) + end + render :partial => "vtag", :collection => vtags + end + + def auto_complete_for_video_tags + @user = current_user + @friends = @user.friends.find_all {|f| f.login.include?(params[:video][:tags]) } + render :partial => 'user_blogs/friends' + end + +end diff --git a/app/controllers/vcomments_controller.rb b/app/controllers/vcomments_controller.rb new file mode 100644 index 0000000..e2d23f3 --- /dev/null +++ b/app/controllers/vcomments_controller.rb @@ -0,0 +1,85 @@ +class VcommentsController < ApplicationController + # GET /vcomments + # GET /vcomments.xml + def index + @vcomments = Vcomment.all + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @vcomments } + end + end + + # GET /vcomments/1 + # GET /vcomments/1.xml + def show + @vcomment = Vcomment.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @vcomment } + end + end + + # GET /vcomments/new + # GET /vcomments/new.xml + def new + @vcomment = Vcomment.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @vcomment } + end + end + + # GET /vcomments/1/edit + def edit + @vcomment = Vcomment.find(params[:id]) + end + + # POST /vcomments + # POST /vcomments.xml + def create + @vcomment = Vcomment.new(params[:vcomment]) + + respond_to do |format| + if @vcomment.save + flash[:notice] = 'Vcomment was successfully created.' + format.html { redirect_to(@vcomment) } + format.xml { render :xml => @vcomment, :status => :created, :location => @vcomment } + else + format.html { render :action => "new" } + format.xml { render :xml => @vcomment.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /vcomments/1 + # PUT /vcomments/1.xml + def update + @vcomment = Vcomment.find(params[:id]) + + respond_to do |format| + if @vcomment.update_attributes(params[:vcomment]) + flash[:notice] = 'Vcomment was successfully updated.' + format.html { redirect_to(@vcomment) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @vcomment.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /vcomments/1 + # DELETE /vcomments/1.xml + def destroy + @vcomment = Vcomment.find(params[:id]) + @vcomment.destroy + + respond_to do |format| + format.html { redirect_to(vcomments_url) } + format.xml { head :ok } + end + end +end diff --git a/app/controllers/vdigs_controller.rb b/app/controllers/vdigs_controller.rb new file mode 100644 index 0000000..2513dac --- /dev/null +++ b/app/controllers/vdigs_controller.rb @@ -0,0 +1,85 @@ +class VdigsController < ApplicationController + # GET /vdigs + # GET /vdigs.xml + def index + @vdigs = Vdig.all + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @vdigs } + end + end + + # GET /vdigs/1 + # GET /vdigs/1.xml + def show + @vdig = Vdig.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @vdig } + end + end + + # GET /vdigs/new + # GET /vdigs/new.xml + def new + @vdig = Vdig.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @vdig } + end + end + + # GET /vdigs/1/edit + def edit + @vdig = Vdig.find(params[:id]) + end + + # POST /vdigs + # POST /vdigs.xml + def create + @vdig = Vdig.new(params[:vdig]) + + respond_to do |format| + if @vdig.save + flash[:notice] = 'Vdig was successfully created.' + format.html { redirect_to(@vdig) } + format.xml { render :xml => @vdig, :status => :created, :location => @vdig } + else + format.html { render :action => "new" } + format.xml { render :xml => @vdig.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /vdigs/1 + # PUT /vdigs/1.xml + def update + @vdig = Vdig.find(params[:id]) + + respond_to do |format| + if @vdig.update_attributes(params[:vdig]) + flash[:notice] = 'Vdig was successfully updated.' + format.html { redirect_to(@vdig) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @vdig.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /vdigs/1 + # DELETE /vdigs/1.xml + def destroy + @vdig = Vdig.find(params[:id]) + @vdig.destroy + + respond_to do |format| + format.html { redirect_to(vdigs_url) } + format.xml { head :ok } + end + end +end diff --git a/app/controllers/video_comments_controller.rb b/app/controllers/video_comments_controller.rb new file mode 100644 index 0000000..4e81523 --- /dev/null +++ b/app/controllers/video_comments_controller.rb @@ -0,0 +1,31 @@ +class VideoCommentsController < ApplicationController + + before_filter :login_required + + def create + @user = current_user + @video = Video.find(params[:video_id]) + @comment = Vcomment.new(params[:vcomment]) + @comment.user = @user + @comment.video = @video + + respond_to do |format| + if @comment.save + format.html { render :partial => 'vcomment', :object => @comment } + format.xml { render :xml => @comment, :status => :created, :location => @comment } + else + flash[:error] = "There was a problem saving this comment" + format.html { render user_video(@user, @blog) } + format.xml { render :xml => @comment.errors, :status => :unprocessable_entity } + end + end + end + + def destroy + @blog = Blog.find(params[:blog_id]) + @comment = @blog.comments.find(params[:id]) + @comment.destroy + render :nothing => true + end + +end diff --git a/app/controllers/video_digs_controller.rb b/app/controllers/video_digs_controller.rb new file mode 100644 index 0000000..b95feab --- /dev/null +++ b/app/controllers/video_digs_controller.rb @@ -0,0 +1,21 @@ +class VideoDigsController < ApplicationController + + before_filter :login_required + + def create + @video = Video.find(params[:video_id]) + + if @video.digs.find_by_user_id(current_user.id) + render :update do |page| + page << "alert('You have dugg before');" + end + else + @video.digs.create(:user_id => current_user.id) + render :update do |page| + page << "var count = parseInt($('digs_count_#{@video.id}').innerHTML) + 1; $('digs_count_#{@video.id}').innerHTML = count;" + end + end + end + + +end diff --git a/app/controllers/video_tags_controller.rb b/app/controllers/video_tags_controller.rb new file mode 100644 index 0000000..b790055 --- /dev/null +++ b/app/controllers/video_tags_controller.rb @@ -0,0 +1,11 @@ +class VideoTagsController < ApplicationController + + before_filter :login_required + + def destroy + @video = Video.find(params[:video_id]) + @video.tags.find(params[:id]).destroy + render :nothing => true + end + +end diff --git a/app/controllers/videos_controller.rb b/app/controllers/videos_controller.rb new file mode 100644 index 0000000..0819488 --- /dev/null +++ b/app/controllers/videos_controller.rb @@ -0,0 +1,85 @@ +class VideosController < ApplicationController + # GET /videos + # GET /videos.xml + def index + @videos = Video.all + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @videos } + end + end + + # GET /videos/1 + # GET /videos/1.xml + def show + @video = Video.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @video } + end + end + + # GET /videos/new + # GET /videos/new.xml + def new + @video = Video.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @video } + end + end + + # GET /videos/1/edit + def edit + @video = Video.find(params[:id]) + end + + # POST /videos + # POST /videos.xml + def create + @video = Video.new(params[:video]) + + respond_to do |format| + if @video.save + flash[:notice] = 'Video was successfully created.' + format.html { redirect_to(@video) } + format.xml { render :xml => @video, :status => :created, :location => @video } + else + format.html { render :action => "new" } + format.xml { render :xml => @video.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /videos/1 + # PUT /videos/1.xml + def update + @video = Video.find(params[:id]) + + respond_to do |format| + if @video.update_attributes(params[:video]) + flash[:notice] = 'Video was successfully updated.' + format.html { redirect_to(@video) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @video.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /videos/1 + # DELETE /videos/1.xml + def destroy + @video = Video.find(params[:id]) + @video.destroy + + respond_to do |format| + format.html { redirect_to(videos_url) } + format.xml { head :ok } + end + end +end diff --git a/app/controllers/vtags_controller.rb b/app/controllers/vtags_controller.rb new file mode 100644 index 0000000..aef667b --- /dev/null +++ b/app/controllers/vtags_controller.rb @@ -0,0 +1,85 @@ +class VtagsController < ApplicationController + # GET /vtags + # GET /vtags.xml + def index + @vtags = Vtag.all + + respond_to do |format| + format.html # index.html.erb + format.xml { render :xml => @vtags } + end + end + + # GET /vtags/1 + # GET /vtags/1.xml + def show + @vtag = Vtag.find(params[:id]) + + respond_to do |format| + format.html # show.html.erb + format.xml { render :xml => @vtag } + end + end + + # GET /vtags/new + # GET /vtags/new.xml + def new + @vtag = Vtag.new + + respond_to do |format| + format.html # new.html.erb + format.xml { render :xml => @vtag } + end + end + + # GET /vtags/1/edit + def edit + @vtag = Vtag.find(params[:id]) + end + + # POST /vtags + # POST /vtags.xml + def create + @vtag = Vtag.new(params[:vtag]) + + respond_to do |format| + if @vtag.save + flash[:notice] = 'Vtag was successfully created.' + format.html { redirect_to(@vtag) } + format.xml { render :xml => @vtag, :status => :created, :location => @vtag } + else + format.html { render :action => "new" } + format.xml { render :xml => @vtag.errors, :status => :unprocessable_entity } + end + end + end + + # PUT /vtags/1 + # PUT /vtags/1.xml + def update + @vtag = Vtag.find(params[:id]) + + respond_to do |format| + if @vtag.update_attributes(params[:vtag]) + flash[:notice] = 'Vtag was successfully updated.' + format.html { redirect_to(@vtag) } + format.xml { head :ok } + else + format.html { render :action => "edit" } + format.xml { render :xml => @vtag.errors, :status => :unprocessable_entity } + end + end + end + + # DELETE /vtags/1 + # DELETE /vtags/1.xml + def destroy + @vtag = Vtag.find(params[:id]) + @vtag.destroy + + respond_to do |format| + format.html { redirect_to(vtags_url) } + format.xml { head :ok } + end + end +end diff --git a/app/helpers/user_videos_helper.rb b/app/helpers/user_videos_helper.rb new file mode 100644 index 0000000..69c05ee --- /dev/null +++ b/app/helpers/user_videos_helper.rb @@ -0,0 +1,2 @@ +module UserVideosHelper +end diff --git a/app/helpers/vcomments_helper.rb b/app/helpers/vcomments_helper.rb new file mode 100644 index 0000000..83365e0 --- /dev/null +++ b/app/helpers/vcomments_helper.rb @@ -0,0 +1,2 @@ +module VcommentsHelper +end diff --git a/app/helpers/vdigs_helper.rb b/app/helpers/vdigs_helper.rb new file mode 100644 index 0000000..ebcb9a6 --- /dev/null +++ b/app/helpers/vdigs_helper.rb @@ -0,0 +1,2 @@ +module VdigsHelper +end diff --git a/app/helpers/video_comments_helper.rb b/app/helpers/video_comments_helper.rb new file mode 100644 index 0000000..4584b63 --- /dev/null +++ b/app/helpers/video_comments_helper.rb @@ -0,0 +1,2 @@ +module VideoCommentsHelper +end diff --git a/app/helpers/video_digs_helper.rb b/app/helpers/video_digs_helper.rb new file mode 100644 index 0000000..1156be3 --- /dev/null +++ b/app/helpers/video_digs_helper.rb @@ -0,0 +1,2 @@ +module VideoDigsHelper +end diff --git a/app/helpers/video_tags_helper.rb b/app/helpers/video_tags_helper.rb new file mode 100644 index 0000000..c177258 --- /dev/null +++ b/app/helpers/video_tags_helper.rb @@ -0,0 +1,2 @@ +module VideoTagsHelper +end diff --git a/app/helpers/videos_helper.rb b/app/helpers/videos_helper.rb new file mode 100644 index 0000000..ee6c155 --- /dev/null +++ b/app/helpers/videos_helper.rb @@ -0,0 +1,2 @@ +module VideosHelper +end diff --git a/app/helpers/vtags_helper.rb b/app/helpers/vtags_helper.rb new file mode 100644 index 0000000..8197253 --- /dev/null +++ b/app/helpers/vtags_helper.rb @@ -0,0 +1,2 @@ +module VtagsHelper +end diff --git a/app/models/user.rb b/app/models/user.rb index f515e16..d55f875 100755 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,193 +1,196 @@ require 'digest/sha1' class User < ActiveRecord::Base belongs_to :city belongs_to :province belongs_to :country has_many :wall_messages, :dependent => :destroy, :finder_sql => 'select wall_messages.* from wall_messages where wall_messages.user_id = #{id} OR wall_messages.receiver_id = #{id} ORDER BY created_at DESC' has_many :sent_mails, :class_name => 'Mail', :foreign_key => 'sender_id', :conditions => { :delete_by_sender => false } has_many :recv_mails, :class_name => 'Mail', :foreign_key => 'receiver_id', :conditions => { :delete_by_receiver => false } def unread_recv_mails_count recv_mails.find_all { |m| !m.read_by_receiver? }.count end has_many :friendships, :dependent => :destroy has_many :friends, :class_name => 'User', :order => 'login ASC', :through => :friendships has_many :game_characters, :dependent => :destroy has_many :currently_playing_game_characters, :class_name => 'GameCharacter', :conditions => { :playing => true }, :order => 'created_at DESC' has_many :games, :through => :game_characters, :uniq => true has_many :icons, :order => 'created_at DESC', :dependent => :destroy has_one :current_icon, :class_name => 'Icon', :order => 'created_at DESC', :conditions => {:current => true} has_many :statuses, :order => 'created_at DESC', :dependent => :destroy has_one :latest_status, :class_name => 'Status', :order => 'created_at DESC' has_many :blogs, :order => 'updated_at DESC', :conditions => {:draft => false} has_many :drafts, :class_name => 'Blog', :order => 'updated_at DESC', :conditions => {:draft => true} has_many :albums, :order => 'updated_at DESC' + has_many :videos, + :order => 'updated_at DESC' + # permissions and roles has_many :permissions has_many :roles, :through => :permissions # Virtual attribute for the unencrypted password attr_accessor :password, :password_confirmation # callbacks before_save :encrypt_password before_create :make_activation_code # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :gender, :password, :password_confirmation, :qq, :website, :mobile, :country, :city, :province, :birthday # Activates the user in the database. def activate @activated = true self.activated_at = Time.now.utc self.activation_code = nil save(false) end def active? # the existence of an activation code means they have not activated yet activation_code.nil? end # Authenticates a user by their login name and unencrypted password. Returns the user or nil. def self.authenticate(email, password) u = find :first, :conditions => ['email = ? and activated_at IS NOT NULL', email] u && u.authenticated?(password) ? u : nil end # Encrypts some data with the salt. def self.encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end # Encrypts the password with the user salt def encrypt(password) self.class.encrypt(password, salt) end def authenticated?(password) crypted_password == encrypt(password) end def remember_token? remember_token_expires_at && Time.now.utc < remember_token_expires_at end # These create and unset the fields required for remembering users between browser closes def remember_me remember_me_for 2.weeks end def remember_me_for(time) remember_me_until time.from_now.utc end def remember_me_until(time) self.remember_token_expires_at = time self.remember_token = encrypt("#{email}--#{remember_token_expires_at}") save(false) end def forget_me self.remember_token_expires_at = nil self.remember_token = nil save(false) end def forgot_password @forgotten_password = true self.make_password_reset_code end def reset_password update_attribute(:password_reset_code, nil) @reset_password = true end def has_role?(name) self.roles.find_by_name(name) ? true : false end # Returns true if the user has just been activated. def recently_activated? @activated end def recently_forgot_password? @forgotten_password end def recently_reset_password? @reset_password end protected def encrypt_password return if password.blank? self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record? self.crypted_password = encrypt(password) end def make_activation_code self.activation_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end def make_password_reset_code self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join ) end end diff --git a/app/models/vcomment.rb b/app/models/vcomment.rb new file mode 100644 index 0000000..350e468 --- /dev/null +++ b/app/models/vcomment.rb @@ -0,0 +1,9 @@ +class Vcomment < ActiveRecord::Base + + belongs_to :user + + belongs_to :video, + :counter_cache => :comments_count + + +end diff --git a/app/models/vdig.rb b/app/models/vdig.rb new file mode 100644 index 0000000..3241af2 --- /dev/null +++ b/app/models/vdig.rb @@ -0,0 +1,2 @@ +class Vdig < ActiveRecord::Base +end diff --git a/app/models/video.rb b/app/models/video.rb new file mode 100644 index 0000000..6c71c0e --- /dev/null +++ b/app/models/video.rb @@ -0,0 +1,63 @@ +class Video < ActiveRecord::Base + + # the owner of this video + belongs_to :user + + # the category of this game + belongs_to :game + + # your friend can comment your video + has_many :comments, + :class_name => 'Vcomment', + :dependent => :destroy + + # you can tag your friends in your video + has_many :tags, + :class_name => 'Vtag', + :dependent => :destroy + + has_many :digs, + :class_name => 'Vdig', + :dependent => :destroy + + acts_as_diggable + + acts_as_taggable + + acts_as_commentable + + class VideoURLNotValid < StandardError; end + + def self.generate_link(url) + if (url =~ /youku\.com/) + startPos = (url =~ /\/id_/) + videoId = url[(startPos + 4)..-6] + videoUrl = "http://player.youku.com/player.php/sid/"+ videoId +"/v.swf" + return "<embed src=\""+ videoUrl + "\" quality=\"high\" width=\"480\" height=\"400\" align=\"middle\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\"></embed>" + elsif (url =~ /tudou\.com/) + startPos = (url =~ /view\//) + videoId = url[(startPos + 5)..-2] + videoUrl = "http://www.tudou.com/v/"+videoId + return "<object width=\"420\" height=\"363\"><param name=\"movie\" value=\""+ videoUrl +"\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><param name=\"wmode\" value=\"opaque\"></param><embed src=\""+ videoUrl+"\"type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" wmode=\"opaque\" width=\"420\" height=\"363\"></embed></object>" + else + raise VideoURLNotValid + end + end + + # get [next blog, prev blog, current blog index] + def self.next_prev_video(user, video) + size = user.videos.count + next_video_idx = 0 + prev_video_idx = 0 + cur_video_idx = 0 + user.videos.each_with_index do |b, i| + if video == b + cur_video_idx = i + next_video_idx = (i + 1) % size + prev_video_idx = (i - 1 + size) % size + end + end + [user.videos[next_video_idx], user.videos[prev_video_idx], cur_video_idx] + end + +end diff --git a/app/models/vtag.rb b/app/models/vtag.rb new file mode 100644 index 0000000..dd878e5 --- /dev/null +++ b/app/models/vtag.rb @@ -0,0 +1,12 @@ +class Vtag < ActiveRecord::Base + + belongs_to :user + + belongs_to :tagged_user, + :class_name => 'User', + :foreign_key => 'tagged_user_id' + + belongs_to :video, + :counter_cache => 'tags_count' + +end diff --git a/app/views/layouts/vcomments.html.erb b/app/views/layouts/vcomments.html.erb new file mode 100644 index 0000000..f47625e --- /dev/null +++ b/app/views/layouts/vcomments.html.erb @@ -0,0 +1,17 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Vcomments: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> diff --git a/app/views/layouts/vdigs.html.erb b/app/views/layouts/vdigs.html.erb new file mode 100644 index 0000000..598fda7 --- /dev/null +++ b/app/views/layouts/vdigs.html.erb @@ -0,0 +1,17 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Vdigs: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> diff --git a/app/views/layouts/videos.html.erb b/app/views/layouts/videos.html.erb new file mode 100644 index 0000000..bb31af4 --- /dev/null +++ b/app/views/layouts/videos.html.erb @@ -0,0 +1,17 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Videos: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> diff --git a/app/views/layouts/vtags.html.erb b/app/views/layouts/vtags.html.erb new file mode 100644 index 0000000..627da78 --- /dev/null +++ b/app/views/layouts/vtags.html.erb @@ -0,0 +1,17 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> +<head> + <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> + <title>Vtags: <%= controller.action_name %></title> + <%= stylesheet_link_tag 'scaffold' %> +</head> +<body> + +<p style="color: green"><%= flash[:notice] %></p> + +<%= yield %> + +</body> +</html> diff --git a/app/views/personal/_menu.html.erb b/app/views/personal/_menu.html.erb index b6c75a3..8023a93 100755 --- a/app/views/personal/_menu.html.erb +++ b/app/views/personal/_menu.html.erb @@ -1,6 +1,6 @@ <%= link_to :wall, new_user_wall_message_url %> <%= link_to :profile, user_profile_url(:user_id => current_user) %> <%= link_to :blog, user_blogs_url(:draft => 0) %> <%= link_to :photo, user_albums_url(:user_id => @user) %> -<%= link_to :video %> +<%= link_to :video, new_user_video_url(@user) %> <%= link_to :calendar %> <br/> diff --git a/app/views/user_blogs/_bcomment.html.erb b/app/views/user_blogs/_bcomment.html.erb index 78163a9..54e23cc 100755 --- a/app/views/user_blogs/_bcomment.html.erb +++ b/app/views/user_blogs/_bcomment.html.erb @@ -1,18 +1,14 @@ <% user = bcomment.user %> <% comment_divid = "comment_#{bcomment.id}" %> <div id=<%= comment_divid %>> <%= user_icon(user) %> - <%= ftime bcomment.created_at %> <br/> - <%= bcomment.content %> - <% if current_user == user %> - <%= link_to_remote 'delete', :complete => "$('#{comment_divid}').remove();", :url => blog_comment_url(:blog_id => bcomment.blog, :id => bcomment), :method => :delete %> + <%= link_to_remote 'delete', :complete => "$('#{comment_divid}').remove();", :url => blog_comment_url(bcomment.blog, bcomment), :method => :delete %> <% else %> <%= link_to_function 'comment', "$('bcomment_content').value='reply to #{user.login}: '; $('bcomment_content').focus();" %> <% end %> - </div> diff --git a/app/views/user_videos/_video_menu.html.erb b/app/views/user_videos/_video_menu.html.erb new file mode 100644 index 0000000..5fa3b71 --- /dev/null +++ b/app/views/user_videos/_video_menu.html.erb @@ -0,0 +1,5 @@ +<%= link_to 'my videos', user_videos_url(@user) %> | +<%= link_to 'friends videos' %> | +<%= link_to 'tagged video' %> | +<%= link_to 'share a video', new_user_video_url(@user) %> + diff --git a/app/views/user_videos/_videos.html.erb b/app/views/user_videos/_videos.html.erb new file mode 100644 index 0000000..e9a96d8 --- /dev/null +++ b/app/views/user_videos/_videos.html.erb @@ -0,0 +1,14 @@ +<%= page_entries_info videos, :entry_name => 'video' %> +<% videos.each do |v| %> + <div> + <%= link_to_user v.user %>'s video<br/><%= ftime v.updated_at %> + <%= link_to 'edit', edit_user_video_url(@user, v) %> | <%= link_to 'delete', confirm_destroy_user_video_url(@user, v), :rel => 'facebox'%> + </div> + <div> + <p id=<%= "video_#{v.id}"%>><%= image_tag 'blank_video.png', :onclick => "play_video(#{v.id}, '#{v.link}')" %></p> + <%= link_to v.title, user_video_url(@user, v) %><br/> + <%= link_to h(truncate(v.url,40)), v.url, :popup => true %> + </div> + <hr/> +<% end %> +<%= will_paginate videos %> diff --git a/app/views/user_videos/_vtag.html.erb b/app/views/user_videos/_vtag.html.erb new file mode 100644 index 0000000..d7d2fed --- /dev/null +++ b/app/views/user_videos/_vtag.html.erb @@ -0,0 +1,4 @@ +<div new_record=<%= vtag.new_record?%> tagged_user_id=<%= vtag.tagged_user_id %> tag_id=<%= vtag.new_record? ? 0: vtag.id %>> + <p><%= user_icon(vtag.tagged_user) %></p> + <p><%= link_to_user vtag.tagged_user %> | <%= link_to_function 'delete', "video_builder.remove_tag(#{vtag.tagged_user_id})" %></p> +</div> diff --git a/app/views/user_videos/confirm_destroy.html.erb b/app/views/user_videos/confirm_destroy.html.erb new file mode 100644 index 0000000..8dd5176 --- /dev/null +++ b/app/views/user_videos/confirm_destroy.html.erb @@ -0,0 +1,5 @@ +<p><%= "Are you sure to delete this video?" %></p> +<% form_remote_tag :url => user_video_url(@user, @video), :method => :delete do %> + <p>Validation code: <%= text_field_tag 'validation_text', '', :size => 4 %><%= submit_tag 'submit'%></p> + <p><%= validation_image %></p> +<% end %> diff --git a/app/views/user_videos/edit.html.erb b/app/views/user_videos/edit.html.erb new file mode 100644 index 0000000..24be70b --- /dev/null +++ b/app/views/user_videos/edit.html.erb @@ -0,0 +1,25 @@ +<%= javascript_include_tag 'video' %> +<p><%= render :partial => 'video_menu' %></p> + +<% form_for :video, :url => user_video_url(@user, @video), :html => { :onsubmit => "if($('video_game_id').value == '') return false; else return true;", :id => 'video_input'} do |f| %> +<p> + <%= f.label :title %><br/> + <%= f.text_field :title %> +</p> +<p> + <%= f.label :game_id, "Catalog" %> + <%= f.collection_select :game_id, @games, :id, :name, {:prompt => true } %> +</p> +<% end %> + +<% content_for 'right' do %> +<p><%= text_field_with_auto_complete :video, :tags, {}, {:after_update_element => 'after_tag'} %></p> +<p><%= link_to_function "unfold", "video_builder.show_friends()", :id => 'unfold' %></p> +<div id='vtags'> + <%= render :partial => 'vtag', :collection => @video.tags %> +</div> +<%= javascript_tag "video_builder = new VideoBuilder(#{@user.id}, #{@video.id})" %> +<% end %> + +<%= link_to_function 'create', "video_builder.update(#{@video.id})" %> + diff --git a/app/views/user_videos/index.html.erb b/app/views/user_videos/index.html.erb new file mode 100644 index 0000000..7465aef --- /dev/null +++ b/app/views/user_videos/index.html.erb @@ -0,0 +1,7 @@ +<%= javascript_include_tag 'video' %> + +<%= render :partial => 'video_menu' %> + +<div id='videos'> + <%= render :partial => 'videos', :object => @videos %> +</div> diff --git a/app/views/user_videos/new.html.erb b/app/views/user_videos/new.html.erb new file mode 100644 index 0000000..f338dbb --- /dev/null +++ b/app/views/user_videos/new.html.erb @@ -0,0 +1,27 @@ +<%= javascript_include_tag 'video' %> +<p><%= render :partial => 'video_menu' %></p> + +<% form_for :video, :url => user_videos_url(@user), :html => { :onsubmit => "if($('video_game_id').value == '') return false; else return true;", :id => 'video_input'} do |f| %> +<p> + <%= f.label :title %><br/> + <%= f.text_field :title %> +</p> +<p> + <%= f.label :url %><br/> + <%= f.text_field :url %> +</p> +<p> + <%= f.label :game_id, "Catalog" %> + <%= collection_select :video, :game_id, @games, :id, :name, {:prompt => true } %> +</p> +<% end %> + +<% content_for 'right' do %> +<p><%= text_field_with_auto_complete :video, :tags, {}, {:after_update_element => 'after_tag'} %></p> +<p><%= link_to_function "unfold", "video_builder.show_friends()", :id => 'unfold' %></p> +<div id='vtags'></div> +<%= javascript_tag "video_builder = new VideoBuilder(#{@user.id}, 0)" %> +<% end %> + +<%= link_to_function 'create', "video_builder.save()" %> + diff --git a/app/views/user_videos/show.html.erb b/app/views/user_videos/show.html.erb new file mode 100644 index 0000000..56e31bb --- /dev/null +++ b/app/views/user_videos/show.html.erb @@ -0,0 +1,48 @@ +<table> + <tr> + <td> <%= user_icon(@user) %></td> + <td> <%= @user.login %> Videos <br/> <%= link_to 'back to video list', user_videos_url %> | <%= link_to 'personal page', new_user_wall_message_url %> </td> + </tr> +</table> + +<% ret = Video.next_prev_video(@user, @video) + @next_video = ret[0] + @prev_video = ret[1] + @cur_video_idx = ret[2] + 1 %> + +<%= link_to "Next: #{truncate(@next_video.title, 15)}", user_video_url(@user, @next_video), :style => "float:right" %> +<%= link_to "Prev: #{truncate(@prev_video.title, 15)}", user_video_url(@user, @video), :style => "float:left" %> + +<table cellpadding='3px'> + <tr > + <td><strong><%= @video.title %></strong><br/><%= ftime @video.updated_at %></td> + <td><%= link_to @video.game.name %><br/><%= link_to 'edit', edit_user_video_url(@user, @video)%> | + <%= link_to 'delete', confirm_destroy_user_video_url(@user, @video), :rel => 'facebox' %></td> + </tr> + <tr> + <td align='center'><%= @video.link %></td> + </tr> +</table> + +<div id='tags'> + Tags: <%= render :partial => 'user_blogs/name_tag', :collection => @video.tags %> +</div> + +<div> + <%= link_to_function "Comment", "$('vcomment_content').focus();" %>(<%= label_tag 'nil', "#{@video.comments.count}", :id => 'comments_count' %>) | + <%= link_to_remote "Dig", :url => video_digs_url(@video), :method => :post%>(<%= label_tag nil, "#{@video.digs.count}", :id => "digs_count_#{@video.id}" %>) +</div> +<hr/> + +<div id='vcomments'> + <%= render :partial => 'video_comments/vcomment', :collection => @video.comments %> +</div> + +<% form_remote_for :vcomment, + :position => :bottom, + :update => 'vcomments', + :complete => "$('vcomment_content').value='';", + :url => video_comments_url(@video) do |form| %> + <p><%= form.text_area 'content', :cols => 70, :rows => 6 %></p> + <p><%= form.label "whisper?" %><%= form.check_box 'whisper' %><%= form.submit 'comment' %></p> +<% end %> diff --git a/app/views/vcomments/edit.html.erb b/app/views/vcomments/edit.html.erb new file mode 100644 index 0000000..306a0fa --- /dev/null +++ b/app/views/vcomments/edit.html.erb @@ -0,0 +1,24 @@ +<h1>Editing vcomment</h1> + +<% form_for(@vcomment) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :user_id %><br /> + <%= f.text_field :user_id %> + </p> + <p> + <%= f.label :video_id %><br /> + <%= f.text_field :video_id %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit 'Update' %> + </p> +<% end %> + +<%= link_to 'Show', @vcomment %> | +<%= link_to 'Back', vcomments_path %> \ No newline at end of file diff --git a/app/views/vcomments/index.html.erb b/app/views/vcomments/index.html.erb new file mode 100644 index 0000000..4fa8e5b --- /dev/null +++ b/app/views/vcomments/index.html.erb @@ -0,0 +1,24 @@ +<h1>Listing vcomments</h1> + +<table> + <tr> + <th>User</th> + <th>Video</th> + <th>Content</th> + </tr> + +<% @vcomments.each do |vcomment| %> + <tr> + <td><%=h vcomment.user_id %></td> + <td><%=h vcomment.video_id %></td> + <td><%=h vcomment.content %></td> + <td><%= link_to 'Show', vcomment %></td> + <td><%= link_to 'Edit', edit_vcomment_path(vcomment) %></td> + <td><%= link_to 'Destroy', vcomment, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New vcomment', new_vcomment_path %> \ No newline at end of file diff --git a/app/views/vcomments/new.html.erb b/app/views/vcomments/new.html.erb new file mode 100644 index 0000000..45f0504 --- /dev/null +++ b/app/views/vcomments/new.html.erb @@ -0,0 +1,23 @@ +<h1>New vcomment</h1> + +<% form_for(@vcomment) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :user_id %><br /> + <%= f.text_field :user_id %> + </p> + <p> + <%= f.label :video_id %><br /> + <%= f.text_field :video_id %> + </p> + <p> + <%= f.label :content %><br /> + <%= f.text_area :content %> + </p> + <p> + <%= f.submit 'Create' %> + </p> +<% end %> + +<%= link_to 'Back', vcomments_path %> \ No newline at end of file diff --git a/app/views/vcomments/show.html.erb b/app/views/vcomments/show.html.erb new file mode 100644 index 0000000..a48a1c0 --- /dev/null +++ b/app/views/vcomments/show.html.erb @@ -0,0 +1,18 @@ +<p> + <b>User:</b> + <%=h @vcomment.user_id %> +</p> + +<p> + <b>Video:</b> + <%=h @vcomment.video_id %> +</p> + +<p> + <b>Content:</b> + <%=h @vcomment.content %> +</p> + + +<%= link_to 'Edit', edit_vcomment_path(@vcomment) %> | +<%= link_to 'Back', vcomments_path %> \ No newline at end of file diff --git a/app/views/vdigs/edit.html.erb b/app/views/vdigs/edit.html.erb new file mode 100644 index 0000000..37776c0 --- /dev/null +++ b/app/views/vdigs/edit.html.erb @@ -0,0 +1,20 @@ +<h1>Editing vdig</h1> + +<% form_for(@vdig) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :user_id %><br /> + <%= f.text_field :user_id %> + </p> + <p> + <%= f.label :video_id %><br /> + <%= f.text_field :video_id %> + </p> + <p> + <%= f.submit 'Update' %> + </p> +<% end %> + +<%= link_to 'Show', @vdig %> | +<%= link_to 'Back', vdigs_path %> \ No newline at end of file diff --git a/app/views/vdigs/index.html.erb b/app/views/vdigs/index.html.erb new file mode 100644 index 0000000..78a298d --- /dev/null +++ b/app/views/vdigs/index.html.erb @@ -0,0 +1,22 @@ +<h1>Listing vdigs</h1> + +<table> + <tr> + <th>User</th> + <th>Video</th> + </tr> + +<% @vdigs.each do |vdig| %> + <tr> + <td><%=h vdig.user_id %></td> + <td><%=h vdig.video_id %></td> + <td><%= link_to 'Show', vdig %></td> + <td><%= link_to 'Edit', edit_vdig_path(vdig) %></td> + <td><%= link_to 'Destroy', vdig, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New vdig', new_vdig_path %> \ No newline at end of file diff --git a/app/views/vdigs/new.html.erb b/app/views/vdigs/new.html.erb new file mode 100644 index 0000000..b909032 --- /dev/null +++ b/app/views/vdigs/new.html.erb @@ -0,0 +1,19 @@ +<h1>New vdig</h1> + +<% form_for(@vdig) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :user_id %><br /> + <%= f.text_field :user_id %> + </p> + <p> + <%= f.label :video_id %><br /> + <%= f.text_field :video_id %> + </p> + <p> + <%= f.submit 'Create' %> + </p> +<% end %> + +<%= link_to 'Back', vdigs_path %> \ No newline at end of file diff --git a/app/views/vdigs/show.html.erb b/app/views/vdigs/show.html.erb new file mode 100644 index 0000000..d7fb134 --- /dev/null +++ b/app/views/vdigs/show.html.erb @@ -0,0 +1,13 @@ +<p> + <b>User:</b> + <%=h @vdig.user_id %> +</p> + +<p> + <b>Video:</b> + <%=h @vdig.video_id %> +</p> + + +<%= link_to 'Edit', edit_vdig_path(@vdig) %> | +<%= link_to 'Back', vdigs_path %> \ No newline at end of file diff --git a/app/views/video_comments/_vcomment.html.erb b/app/views/video_comments/_vcomment.html.erb new file mode 100644 index 0000000..b100bea --- /dev/null +++ b/app/views/video_comments/_vcomment.html.erb @@ -0,0 +1,13 @@ +<% user = vcomment.user %> +<% comment_divid = "comment_#{vcomment.id}" %> + +<div id=<%= comment_divid %>> + <%= user_icon user %> + <%= ftime vcomment.created_at %><br/> + <%= vcomment.content %> + <% if current_user == user %> + <%= link_to_remote 'delete', :complete => "$('#{comment_divid}').remove();", :url => video_comment_url(vcomment.video, vcomment), :method => :delete %> + <% else %> + <%= link_to_function 'comment', "$('vcomment_content').value='reply to #{user.login}: '; $('vcomment_content').focus();"%> + <% end %> +</div> diff --git a/app/views/videos/edit.html.erb b/app/views/videos/edit.html.erb new file mode 100644 index 0000000..b252fe4 --- /dev/null +++ b/app/views/videos/edit.html.erb @@ -0,0 +1,40 @@ +<h1>Editing video</h1> + +<% form_for(@video) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :user_id %><br /> + <%= f.text_field :user_id %> + </p> + <p> + <%= f.label :game_id %><br /> + <%= f.text_field :game_id %> + </p> + <p> + <%= f.label :title %><br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :url %><br /> + <%= f.text_field :url %> + </p> + <p> + <%= f.label :link %><br /> + <%= f.text_area :link %> + </p> + <p> + <%= f.label :digs_count %><br /> + <%= f.text_field :digs_count %> + </p> + <p> + <%= f.label :comments_count %><br /> + <%= f.text_field :comments_count %> + </p> + <p> + <%= f.submit 'Update' %> + </p> +<% end %> + +<%= link_to 'Show', @video %> | +<%= link_to 'Back', videos_path %> \ No newline at end of file diff --git a/app/views/videos/index.html.erb b/app/views/videos/index.html.erb new file mode 100644 index 0000000..4cff017 --- /dev/null +++ b/app/views/videos/index.html.erb @@ -0,0 +1,32 @@ +<h1>Listing videos</h1> + +<table> + <tr> + <th>User</th> + <th>Game</th> + <th>Title</th> + <th>Url</th> + <th>Link</th> + <th>Digs count</th> + <th>Comments count</th> + </tr> + +<% @videos.each do |video| %> + <tr> + <td><%=h video.user_id %></td> + <td><%=h video.game_id %></td> + <td><%=h video.title %></td> + <td><%=h video.url %></td> + <td><%=h video.link %></td> + <td><%=h video.digs_count %></td> + <td><%=h video.comments_count %></td> + <td><%= link_to 'Show', video %></td> + <td><%= link_to 'Edit', edit_video_path(video) %></td> + <td><%= link_to 'Destroy', video, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New video', new_video_path %> \ No newline at end of file diff --git a/app/views/videos/new.html.erb b/app/views/videos/new.html.erb new file mode 100644 index 0000000..538edd7 --- /dev/null +++ b/app/views/videos/new.html.erb @@ -0,0 +1,39 @@ +<h1>New video</h1> + +<% form_for(@video) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :user_id %><br /> + <%= f.text_field :user_id %> + </p> + <p> + <%= f.label :game_id %><br /> + <%= f.text_field :game_id %> + </p> + <p> + <%= f.label :title %><br /> + <%= f.text_field :title %> + </p> + <p> + <%= f.label :url %><br /> + <%= f.text_field :url %> + </p> + <p> + <%= f.label :link %><br /> + <%= f.text_area :link %> + </p> + <p> + <%= f.label :digs_count %><br /> + <%= f.text_field :digs_count %> + </p> + <p> + <%= f.label :comments_count %><br /> + <%= f.text_field :comments_count %> + </p> + <p> + <%= f.submit 'Create' %> + </p> +<% end %> + +<%= link_to 'Back', videos_path %> \ No newline at end of file diff --git a/app/views/videos/show.html.erb b/app/views/videos/show.html.erb new file mode 100644 index 0000000..7148766 --- /dev/null +++ b/app/views/videos/show.html.erb @@ -0,0 +1,38 @@ +<p> + <b>User:</b> + <%=h @video.user_id %> +</p> + +<p> + <b>Game:</b> + <%=h @video.game_id %> +</p> + +<p> + <b>Title:</b> + <%=h @video.title %> +</p> + +<p> + <b>Url:</b> + <%=h @video.url %> +</p> + +<p> + <b>Link:</b> + <%=h @video.link %> +</p> + +<p> + <b>Digs count:</b> + <%=h @video.digs_count %> +</p> + +<p> + <b>Comments count:</b> + <%=h @video.comments_count %> +</p> + + +<%= link_to 'Edit', edit_video_path(@video) %> | +<%= link_to 'Back', videos_path %> \ No newline at end of file diff --git a/app/views/vtags/edit.html.erb b/app/views/vtags/edit.html.erb new file mode 100644 index 0000000..11ff2b2 --- /dev/null +++ b/app/views/vtags/edit.html.erb @@ -0,0 +1,24 @@ +<h1>Editing vtag</h1> + +<% form_for(@vtag) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :user_id %><br /> + <%= f.text_field :user_id %> + </p> + <p> + <%= f.label :tagged_user_id %><br /> + <%= f.text_field :tagged_user_id %> + </p> + <p> + <%= f.label :video_id %><br /> + <%= f.text_field :video_id %> + </p> + <p> + <%= f.submit 'Update' %> + </p> +<% end %> + +<%= link_to 'Show', @vtag %> | +<%= link_to 'Back', vtags_path %> \ No newline at end of file diff --git a/app/views/vtags/index.html.erb b/app/views/vtags/index.html.erb new file mode 100644 index 0000000..dbf889d --- /dev/null +++ b/app/views/vtags/index.html.erb @@ -0,0 +1,24 @@ +<h1>Listing vtags</h1> + +<table> + <tr> + <th>User</th> + <th>Tagged user</th> + <th>Video</th> + </tr> + +<% @vtags.each do |vtag| %> + <tr> + <td><%=h vtag.user_id %></td> + <td><%=h vtag.tagged_user_id %></td> + <td><%=h vtag.video_id %></td> + <td><%= link_to 'Show', vtag %></td> + <td><%= link_to 'Edit', edit_vtag_path(vtag) %></td> + <td><%= link_to 'Destroy', vtag, :confirm => 'Are you sure?', :method => :delete %></td> + </tr> +<% end %> +</table> + +<br /> + +<%= link_to 'New vtag', new_vtag_path %> \ No newline at end of file diff --git a/app/views/vtags/new.html.erb b/app/views/vtags/new.html.erb new file mode 100644 index 0000000..658ae0b --- /dev/null +++ b/app/views/vtags/new.html.erb @@ -0,0 +1,23 @@ +<h1>New vtag</h1> + +<% form_for(@vtag) do |f| %> + <%= f.error_messages %> + + <p> + <%= f.label :user_id %><br /> + <%= f.text_field :user_id %> + </p> + <p> + <%= f.label :tagged_user_id %><br /> + <%= f.text_field :tagged_user_id %> + </p> + <p> + <%= f.label :video_id %><br /> + <%= f.text_field :video_id %> + </p> + <p> + <%= f.submit 'Create' %> + </p> +<% end %> + +<%= link_to 'Back', vtags_path %> \ No newline at end of file diff --git a/app/views/vtags/show.html.erb b/app/views/vtags/show.html.erb new file mode 100644 index 0000000..8047bb8 --- /dev/null +++ b/app/views/vtags/show.html.erb @@ -0,0 +1,18 @@ +<p> + <b>User:</b> + <%=h @vtag.user_id %> +</p> + +<p> + <b>Tagged user:</b> + <%=h @vtag.tagged_user_id %> +</p> + +<p> + <b>Video:</b> + <%=h @vtag.video_id %> +</p> + + +<%= link_to 'Edit', edit_vtag_path(@vtag) %> | +<%= link_to 'Back', vtags_path %> \ No newline at end of file diff --git a/config/.routes.rb.swp b/config/.routes.rb.swp index f5950df..f73a685 100644 Binary files a/config/.routes.rb.swp and b/config/.routes.rb.swp differ diff --git a/config/environment.rb b/config/environment.rb index d906a4c..55fd59f 100755 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,49 +1,49 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') require 'diggable' require 'taggable' require 'commentable' require 'migration_helper' Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de - config.active_record.observers = [:user_observer, :photo_observer] + # config.active_record.observers = [:user_observer, :photo_observer] end require 'will_paginate' diff --git a/config/routes.rb b/config/routes.rb index d21c8ed..61f68ab 100755 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,133 +1,155 @@ ActionController::Routing::Routes.draw do |map| + map.resources :vtags + + map.resources :vdigs + + map.resources :vcomments + + map.resources :videos map.resources :pages map.resources :sessions map.resources :statuses map.resources :wall_messages map.resources :mails map.resources :icons map.resources :ptags map.resources :pdigs map.resources :pcomments map.resources :bdigs map.resources :friendships map.resources :game_characters, :collection => {:edit_new => :get} map.resources :game_races map.resources :game_professions map.resources :game_servers map.resources :game_areas map.resources :games map.root :controller => 'sessions', :action => 'new' map.signup '/signup', :controller => 'users', :action => 'new' map.login '/login', :controller => 'sessions', :action => 'new' map.logout '/logout', :controller => 'sessions', :action => 'destroy' map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate' map.forgot_password '/forgot_password', :controller => 'passwords', :action => 'new' map.reset_password '/reset_password/:password_reset_code', :controller => 'passwords', :action => 'edit' map.change_password '/change_password', :controller => 'accounts', :action => 'edit' map.resources :users, :member => {:enable => :put} do |users| users.resources :characters, :controller => 'user_characters', :member => {:confirm_destroy => :get} users.resources :wall_messages, :controller => 'user_wall_messages' users.resources :mails, :controller => 'mailboxes', :member => {:reply => :post}, :collection => {:read_multiple => :put, :unread_multiple => :put, :destroy_multiple => :delete} users.resources :friends, :collection => {:search => :get} users.resources :statuses, :controller => 'user_statuses' users.resources :blogs, :controller => 'user_blogs', :member => {:confirm_destroy => :get}, :collection => {:destroy_multiple => :delete} users.resources :blog_feeds users.resources :tagged_blogs users.resources :albums, :controller => 'user_albums', :member => {:confirm_destroy => :get} users.resources :album_feeds users.resources :tagged_photos + users.resources :videos, + :controller => 'user_videos', + :member => {:confirm_destroy => :get} + users.resource :profile users.resource :basic_info, :controller => 'basic_info' users.resource :contact_info, :controller => 'contact_info' end map.resources :blogs do |blogs| blogs.resources :comments, :controller => 'blog_comments' blogs.resources :tags, :controller => 'blog_tags' blogs.resources :digs, :controller => 'blog_digs' end map.resources :photos do |photos| photos.resources :comments, :controller => 'photo_comments' photos.resources :tags, :controller => 'photo_tags' photos.resources :digs, :controller => 'photo_digs' end map.resources :albums do |albums| albums.resources :photos, :controller => 'album_photos', :member => {:confirm_destroy => :get, :cover => :post}, :collection => {:update_multiple => :put, :edit_multiple => :get, :create_multiple => :post} end + map.resources :videos do |videos| + videos.resources :comments, + :controller => 'video_comments' + + videos.resources :tags, + :controller => 'video_tags' + + videos.resources :digs, + :controller => 'video_digs' + end + map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end diff --git a/db/buck/20090810062541_add_characters.rb b/db/buck/20090810062541_add_characters.rb new file mode 100755 index 0000000..936966f --- /dev/null +++ b/db/buck/20090810062541_add_characters.rb @@ -0,0 +1,166 @@ +class AddCharacters < ActiveRecord::Migration + def self.up + wow = Game.create( + :name => "world of warcraft", + :sale_date => "2009-5-1", + :company => "blizzard", + :description => "best online game ever") + stone_age = Game.create( + :name => "stone age", + :sale_date => "2008-5-3", + :company => "chinese gamer", + :description => "worst online game ever") + wow_a1 = GameArea.create( + :name => "wow land 1", + :game_id => wow.id) + wow_a2 = GameArea.create( + :name => "wow land 2", + :game_id => wow.id) + sa_a1 = GameArea.create( + :name => "stone age land 1", + :game_id => stone_age.id) + sa_a2 = GameArea.create( + :name => "stone age land 2", + :game_id => stone_age.id) + wow_a1_s1 = GameServer.create( + :name => "land 1 server 1", + :game_id => wow.id, + :area_id => wow_a1.id, + :ip => "59.66.130.101") + wow_a1_s2 = GameServer.create( + :name => "land 1 server 2", + :game_id => wow.id, + :area_id => wow_a1.id, + :ip => "59.66.130.102") + wow_a2_s1 = GameServer.create( + :name => "land 2 server 1", + :game_id => wow.id, + :area_id => wow_a2.id, + :ip => "23.123.34.21") + sa_a1_s1 = GameServer.create( + :name => "land 1 server 1", + :game_id => stone_age.id, + :area_id => sa_a1.id, + :ip => "45.132.64.32") + sa_a2_s1 = GameServer.create( + :name => "land 2 server 1", + :game_id => stone_age.id, + :area_id => sa_a2.id, + :ip => "34.45.56.67") + sa_a2_s2 = GameServer.create( + :name => "land 2 server 2", + :game_id => stone_age.id, + :area_id => sa_a2.id, + :ip => "23.34.45.56") + human = GameRace.create( + :name => "human", + :game_id => wow.id) + undead = GameRace.create( + :name => "undead", + :game_id => wow.id) + elf = GameRace.create( + :name => "elf", + :game_id => wow.id) + orc = GameRace.create( + :name => "orc", + :game_id => wow.id) + dwarf = GameRace.create( + :name => "dwarf", + :game_id => stone_age.id) + peasant = GameRace.create( + :name => "peasant", + :game_id => stone_age.id) + thief = GameProfession.create( + :name => "thief", + :game_id => wow.id) + warrior = GameProfession.create( + :name => "warrior", + :game_id => wow.id) + solider = GameProfession.create( + :name => "solider", + :game_id => stone_age.id) + xman = GameProfession.create( + :name => "xman", + :game_id => stone_age.id) + gaoxh = User.find_by_login("gaoxh") + micai = User.find_by_login('micai') + c1 = GameCharacter.create( + :user_id => gaoxh.id, + :game_id => wow.id, + :server_id => wow_a1_s1.id, + :area_id => wow_a1.id, + :profession_id => thief.id, + :race_id => human.id, + :name => "big boy!", + :level => 25, + :playing => true) + c2 = GameCharacter.create( + :user_id => gaoxh.id, + :game_id => wow.id, + :server_id => wow_a2_s1.id, + :area_id => wow_a2.id, + :profession_id => warrior.id, + :race_id => undead.id, + :name => "cute boy!", + :level => 35, + :playing => false) + c3 = GameCharacter.create( + :user_id => gaoxh.id, + :game_id => stone_age.id, + :server_id => sa_a1_s1.id, + :area_id => sa_a1.id, + :profession_id => xman.id, + :race_id => dwarf.id, + :name => "i am xman!", + :level => 25, + :playing => true) + c2 = GameCharacter.create( + :user_id => micai.id, + :game_id => wow.id, + :server_id => wow_a2_s1.id, + :area_id => wow_a2.id, + :profession_id => warrior.id, + :race_id => undead.id, + :name => "cute boy!", + :level => 35, + :playing => false) + c3 = GameCharacter.create( + :user_id => micai.id, + :game_id => stone_age.id, + :server_id => sa_a1_s1.id, + :area_id => sa_a1.id, + :profession_id => xman.id, + :race_id => dwarf.id, + :name => "i am xman!", + :level => 25, + :playing => true) + 20.times do |i| + c = GameCharacter.create( + :user_id => User.find_by_login("user#{i}").id, + :game_id => wow.id, + :server_id => wow_a2_s1.id, + :area_id => wow_a2.id, + :profession_id => warrior.id, + :race_id => undead.id, + :name => "user#{i}'s character", + :level => i, + :playing => true) + end + 20.times do |i| + c = GameCharacter.create( + :user_id => User.find_by_login("user#{i+10}").id, + :game_id => stone_age.id, + :server_id => sa_a1_s1.id, + :area_id => sa_a1.id, + :profession_id => xman.id, + :race_id => dwarf.id, + :name => "user#{i}'s character", + :level => i, + :playing => true) + end + end + + def self.down + + end +end diff --git a/db/buck/20090810081501_add_blog.rb b/db/buck/20090810081501_add_blog.rb new file mode 100755 index 0000000..2d8feb0 --- /dev/null +++ b/db/buck/20090810081501_add_blog.rb @@ -0,0 +1,16 @@ +class AddBlog < ActiveRecord::Migration + def self.up + wow = Game.find_by_name("world of warcraft") + gaoxh = User.find_by_login('gaoxh') + 20.times do |i| + gaoxh.blogs.create( + :title => "blog #{i}", + :game_id => wow.id, + :draft => false, + :content => "hello, everyone. this is blog #{i}. hope you will enjoy it") + end + end + + def self.down + end +end diff --git a/db/buck/20090810133544_add_friends.rb b/db/buck/20090810133544_add_friends.rb new file mode 100755 index 0000000..e7239ae --- /dev/null +++ b/db/buck/20090810133544_add_friends.rb @@ -0,0 +1,22 @@ +class AddFriends < ActiveRecord::Migration + def self.up + gaoxh = User.find_by_login('gaoxh') + xiexin = User.find_by_login('xiexin') + micai = User.find_by_login('micai') + gaoxh.friendships.create(:friend_id => xiexin.id) + gaoxh.friendships.create(:friend_id => micai.id) + 50.times do |i| + user = User.find_by_login("user#{i}") + gaoxh.friendships.create(:user_id => gaoxh.id, :friend_id => user.id) + end + micai.friendships.create(:friend_id => gaoxh.id) + micai.friendships.create(:friend_id => xiexin.id) + 30.times do |i| + user = User.find_by_login("user#{i}") + micai.friendships.create(:friend_id => user.id) + end + end + + def self.down + end +end diff --git a/db/buck/20090810160345_add_mails.rb b/db/buck/20090810160345_add_mails.rb new file mode 100755 index 0000000..d7d5c33 --- /dev/null +++ b/db/buck/20090810160345_add_mails.rb @@ -0,0 +1,53 @@ +class AddMails < ActiveRecord::Migration + def self.up + gaoxh = User.find_by_login("gaoxh") + micai = User.find_by_login("micai") + mail = Mail.create( + :sender_id => micai.id, + :receiver_id => gaoxh.id, + :title => 'hello', + :content => 'this is mingfei, how are you?') + mail.parent_id = mail.id + mail.save + title = "reply to: hello" + Mail.create( + :sender_id => gaoxh.id, + :receiver_id => micai.id, + :parent_id => mail.id, + :title => title, + :content => 'very good... how\'s it going?') + Mail.create( + :sender_id => gaoxh.id, + :receiver_id => micai.id, + :parent_id => mail.id, + :title => title, + :content => 'by the way... do you have a girl friend') + Mail.create( + :sender_id => micai.id, + :receiver_id => gaoxh.id, + :content => 'not yet.. how about you?', + :title => title, + :parent_id => mail.id) + 30.times do |i| + mail = Mail.create( + :sender_id => gaoxh.id, + :receiver_id => User.find_by_login("user#{i}").id, + :title => "hello user#{i}", + :content => "this is xiahong, how are you user#{i}") + mail.parent_id = mail.id + mail.save + end + 30.times do |i| + mail = Mail.create( + :sender_id => User.find_by_login("user#{i}").id, + :receiver_id => gaoxh.id, + :title => 'hello', + :content => "this is user#{i}, how are you?") + mail.parent_id = mail.id + mail.save + end + end + + def self.down + end +end diff --git a/db/buck/20090811064343_add_wall_messages.rb b/db/buck/20090811064343_add_wall_messages.rb new file mode 100755 index 0000000..3f338c4 --- /dev/null +++ b/db/buck/20090811064343_add_wall_messages.rb @@ -0,0 +1,19 @@ +class AddWallMessages < ActiveRecord::Migration + def self.up + gaoxh = User.find_by_login("gaoxh") + micai = User.find_by_login("micai") + gaoxh.wall_messages.create( + :poster_id => micai.id, + :receiver_id => gaoxh.id, + :content => "hello, i am micai") + 40.times do |i| + gaoxh.wall_messages.create( + :poster_id => User.find_by_login("user#{i}").id, + :receiver_id => gaoxh.id, + :content => "hello, i am user #{i}") + end + end + + def self.down + end +end diff --git a/db/buck/20090811092810_add_drafts.rb b/db/buck/20090811092810_add_drafts.rb new file mode 100755 index 0000000..05d54cd --- /dev/null +++ b/db/buck/20090811092810_add_drafts.rb @@ -0,0 +1,15 @@ +class AddDrafts < ActiveRecord::Migration + def self.up + gaoxh = User.find_by_login('gaoxh') + wow = Game.find_by_name("world of warcraft") + 20.times do |i| + gaoxh.drafts.create( + :title => "draft #{i}", + :game_id => wow.id, + :content => "hello, this is draft #{i}. i will finish it soon") + end + end + + def self.down + end +end diff --git a/db/buck/20090812060413_add_albums.rb b/db/buck/20090812060413_add_albums.rb new file mode 100755 index 0000000..2e56f2e --- /dev/null +++ b/db/buck/20090812060413_add_albums.rb @@ -0,0 +1,18 @@ +class AddAlbums < ActiveRecord::Migration + def self.up + gaoxh = User.find_by_login("gaoxh") + wow = Game.find_by_name("world of warcraft") + 20.times do |i| + gaoxh.albums.create(:game_id => wow.id, :title => "album #{i}") + end + 20.times do |i| + user = User.find_by_login("user#{i}") + 20.times do |i| + user.albums.create(:game_id => wow.id, :title => "album #{i}") + end + end + end + + def self.down + end +end diff --git a/db/migrate/20090818041535_create_videos.rb b/db/migrate/20090818041535_create_videos.rb new file mode 100644 index 0000000..ee83a6e --- /dev/null +++ b/db/migrate/20090818041535_create_videos.rb @@ -0,0 +1,20 @@ +class CreateVideos < ActiveRecord::Migration + def self.up + create_table :videos, :force => true do |t| + t.integer :user_id + t.integer :game_id + t.string :title + t.string :url + t.text :link + t.integer :digs_count, :default => 0 + t.integer :comments_count, :default => 0 + t.integer :tags_count, :default => 0 + t.string :privilege + t.timestamps + end + end + + def self.down + drop_table :videos + end +end diff --git a/db/migrate/20090818041805_create_vcomments.rb b/db/migrate/20090818041805_create_vcomments.rb new file mode 100644 index 0000000..df4a9b0 --- /dev/null +++ b/db/migrate/20090818041805_create_vcomments.rb @@ -0,0 +1,15 @@ +class CreateVcomments < ActiveRecord::Migration + def self.up + create_table :vcomments, :force => true do |t| + t.integer :user_id + t.integer :video_id + t.text :content + t.boolean :whisper, :default => false + t.timestamps + end + end + + def self.down + drop_table :vcomments + end +end diff --git a/db/migrate/20090818041852_create_vdigs.rb b/db/migrate/20090818041852_create_vdigs.rb new file mode 100644 index 0000000..dcc3109 --- /dev/null +++ b/db/migrate/20090818041852_create_vdigs.rb @@ -0,0 +1,14 @@ +class CreateVdigs < ActiveRecord::Migration + def self.up + create_table :vdigs, :force => true do |t| + t.integer :user_id + t.integer :video_id + + t.timestamps + end + end + + def self.down + drop_table :vdigs + end +end diff --git a/db/migrate/20090818041940_create_vtags.rb b/db/migrate/20090818041940_create_vtags.rb new file mode 100644 index 0000000..e36c3eb --- /dev/null +++ b/db/migrate/20090818041940_create_vtags.rb @@ -0,0 +1,15 @@ +class CreateVtags < ActiveRecord::Migration + def self.up + create_table :vtags, :force => true do |t| + t.integer :user_id + t.integer :tagged_user_id + t.integer :video_id + + t.timestamps + end + end + + def self.down + drop_table :vtags + end +end diff --git a/db/schema.rb b/db/schema.rb index b5b252b..dba5039 100755 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,279 +1,327 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20090816174114) do +ActiveRecord::Schema.define(:version => 20090818041940) do create_table "albums", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "photos_count", :default => 0 t.string "title" t.text "description" t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "bcomments", :force => true do |t| t.integer "user_id", :null => false t.integer "blog_id", :null => false t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "bdigs", :force => true do |t| t.integer "user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "blogs", :force => true do |t| t.integer "user_id" t.integer "game_id" t.string "title", :limit => 64 t.text "content", :limit => 16777215 t.integer "digs_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "tags_count", :default => 0 t.boolean "draft", :default => true t.string "privilege" t.datetime "created_at" t.datetime "updated_at" end create_table "btags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "blog_id" t.datetime "created_at" t.datetime "updated_at" end create_table "cities", :force => true do |t| t.string "name" t.integer "city_id" t.datetime "created_at" t.datetime "updated_at" end create_table "countries", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end + create_table "event_wall_messages", :force => true do |t| + t.integer "activity_id" + t.integer "poster_id" + t.integer "receiver_id" + t.text "content" + t.boolean "whisper", :default => false + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "friendships", :force => true do |t| t.integer "user_id" t.integer "friend_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_areas", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_characters", :force => true do |t| t.integer "user_id" t.integer "game_id" t.integer "server_id" t.integer "area_id" t.integer "profession_id" t.integer "race_id" t.string "name" t.integer "level" t.boolean "playing" t.datetime "created_at" t.datetime "updated_at" end create_table "game_professions", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_races", :force => true do |t| t.string "name" t.integer "game_id" t.datetime "created_at" t.datetime "updated_at" end create_table "game_servers", :force => true do |t| t.string "name" t.string "ip" t.integer "game_id" t.integer "area_id" t.datetime "created_at" t.datetime "updated_at" end create_table "games", :force => true do |t| t.string "name" t.string "company" t.datetime "sale_date" t.text "description" t.boolean "no_areas", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "icons", :force => true do |t| t.integer "user_id" t.boolean "current" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "mails", :force => true do |t| t.integer "sender_id" t.integer "receiver_id" t.boolean "delete_by_sender", :default => false t.boolean "delete_by_receiver", :default => false t.boolean "read_by_sender", :default => true t.boolean "read_by_receiver", :default => false t.string "title" t.text "content" t.integer "parent_id" t.datetime "created_at" t.datetime "updated_at" end create_table "pages", :force => true do |t| t.string "title" t.string "permalink" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "pcomments", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end create_table "pdigs", :force => true do |t| t.integer "user_id" t.integer "photo_id" t.datetime "created_at" t.datetime "updated_at" end create_table "permissions", :force => true do |t| t.string "user_id" t.string "role_id" t.datetime "created_at" t.datetime "updated_at" end create_table "photos", :force => true do |t| t.integer "digs_count", :default => 0 t.integer "tags_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "album_id" t.boolean "cover", :default => false t.text "notation" t.integer "parent_id" t.string "content_type" t.string "filename" t.string "thumbnail" t.integer "size" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "provinces", :force => true do |t| t.string "name" t.integer "country_id" t.datetime "created_at" t.datetime "updated_at" end create_table "ptags", :force => true do |t| t.integer "user_id" t.integer "tagged_user_id" t.integer "photo_id" t.integer "x" t.integer "y" t.integer "width" t.integer "height" t.datetime "created_at" t.datetime "updated_at" end create_table "roles", :force => true do |t| t.string "name", :null => false t.datetime "created_at" t.datetime "updated_at" end create_table "statuses", :force => true do |t| t.integer "user_id" t.text "content" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "login", :limit => 64 t.string "email", :limit => 128 t.string "crypted_password", :limit => 64 t.string "salt", :limit => 40 t.string "gender" t.boolean "enabled", :default => true t.string "remember_token" t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "password_reset_code", :limit => 40 t.integer "country_id" t.integer "province_id" t.integer "city_id" t.integer "qq" t.integer "mobile" t.string "website" t.datetime "birthday" t.datetime "created_at" t.datetime "updated_at" end + create_table "vcomments", :force => true do |t| + t.integer "user_id" + t.integer "video_id" + t.text "content" + t.boolean "whisper", :default => false + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "vdigs", :force => true do |t| + t.integer "user_id" + t.integer "video_id" + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "videos", :force => true do |t| + t.integer "user_id" + t.integer "game_id" + t.string "title" + t.string "url" + t.text "link" + t.integer "digs_count", :default => 0 + t.integer "comments_count", :default => 0 + t.integer "tags_count", :default => 0 + t.string "privilege" + t.datetime "created_at" + t.datetime "updated_at" + end + + create_table "vtags", :force => true do |t| + t.integer "user_id" + t.integer "tagged_user_id" + t.integer "video_id" + t.datetime "created_at" + t.datetime "updated_at" + end + create_table "wall_messages", :force => true do |t| t.integer "user_id" t.integer "poster_id" t.integer "receiver_id" t.text "content" t.boolean "whisper", :default => false t.datetime "created_at" t.datetime "updated_at" end end diff --git a/public/images/blank_video.png b/public/images/blank_video.png new file mode 100644 index 0000000..b495405 Binary files /dev/null and b/public/images/blank_video.png differ diff --git a/public/javascripts/blog.js b/public/javascripts/blog.js index 927fb4b..4640ddf 100755 --- a/public/javascripts/blog.js +++ b/public/javascripts/blog.js @@ -1,431 +1,435 @@ PopupManager = Class.create({ /* * initialize */ initialize: function(user_id, options){ this.user_id = user_id; // read options this.options = Object.extend({ popup_class: 'popup-class', user_info_class: 'popup-user-info-class', }, options || {}); }, /* * popup user information */ show: function(user_id, linker){ if(this.popup) this.popup.hide(); else{ // create popup element and close button this.popup = new Element('div', {className: this.options.popup_class}); this.user_info = new Element('div', {className: this.options.user_info_class}); this.close_button = new Element('button'); this.close_button.update('close'); this.popup.appendChild(this.user_info); this.popup.appendChild(this.close_button); // add click event to close button this.close_button.observe('click', function(event){ this.popup.hide(); }.bind(this)); } // record position and user_id this.pos = linker.positionedOffset(); this.pos.left += linker.getWidth(); // send ajax request to server to retrieve user info new Ajax.Request("/user_blogs/show_popup_tag?tagged_user_id="+user_id, { method: 'get', onSuccess: function(transport){ this.user_info.innerHTML = transport.responseText; this.popup.setStyle({ position: 'absolute', left: this.pos.left + 'px', top: this.pos.top + 'px', backgroundColor: '#fff' }); document.body.appendChild(this.popup); this.popup.show(); }.bind(this) }); } }); DraftManager = Class.create({ /* * initialize * just save drafts element */ initialize: function(user_id){ this.drafts = $('my_drafts'); this.user_id = user_id; }, /* * get all selected drafts */ get_selected: function(){ var selected = []; var inputs = $$('input'); for(var i=0;i<inputs.length;i++){ if(inputs[i].type == 'checkbox' && inputs[i].checked){ selected.push(inputs[i]); } } return selected; }, /* * get all drafts */ get_all: function(){ var all = []; var inputs = $$('input'); for(var i=0;i<inputs.length;i++){ if(inputs[i].type == 'checkbox'){ all.push(inputs[i]); } } return all; }, /* * select all drafts * set all checkboxes to true */ select_all: function(){ var all = this.get_all(); for(var i=0;i<all.length;i++){ all[i].checked=true; } }, /* * delete selected drafts */ delete_selected: function(){ var selected = this.get_selected(); // construct ure url = "/users/" + this.user_id + "/blogs/destroy_multiple?"; for(var i=0;i<selected.length;i++){ url += "blogs[]=" + selected[i].readAttribute('blog_id') + "&"; } // send ajax request to remove it from database new Ajax.Request(url, {method: 'delete'}); } }); function after_tag(input_field, selected_li){ blog_builder.new_tag(selected_li.readAttribute('user_id')); $('blog_tags').value = ''; } BlogBuilder = Class.create({ initialize: function(user_id, blog_id){ // save user id and blog id this.user_id = user_id; this.blog_id = blog_id; // this field is only valid when updating blog // save tag input field and set its initial text this.tag_input = $('blog_tags'); this.tag_input.value = 'please tag your friend here'; // add on focus event to tag input this.tag_input.observe('focus', function(event){ this.value = ''; }); // add on blur event to tag input this.tag_input.observe('blur', function(event){ this.value = 'please tag your friends here'; }); // input form this.form = $('blog_input'); // save btags div which displays all current btags this.btags_div = $('btags'); // fold, unfold handler this.unfold = $('unfold'); // we maintain a hash of blog tags this.btags = new Hash(); var current_tags = this.btags_div.childElements(); for(var i=0;i<current_tags.length;i++){ this.btags.set(current_tags[i].readAttribute('tagged_user_id'), current_tags[i]); } }, /* * save as blog or draft which is determined by type */ save: function(type){ // construct url // appending form inputs and tag inputs var url = '/users/' + this.user_id + '/blogs?'; if(type == 'blog') url += "blog[draft]=0&" else url += "blog[draft]=1&" this.btags.each(function(pair){ if(pair.value.readAttribute('new_record') == 'true') url += "tagged_users[]=" + pair.key + "&"; }); url += this.form.serialize(); // send ajax request new Ajax.Request(url, {method: 'post'}); }, /* * update as blog or draft which is determined by type * this function also needs blog id or draft id */ update: function(type, id){ // construct url // appending form inputs and tag inputs var url = '/users/' + this.user_id + '/blogs/' + id + '?'; if(type == 'blog') url += "blog[draft]=0&" else url += "blog[draft]=1&" this.btags.each(function(pair){ if(pair.value.readAttribute('new_record') == 'true') url += "tagged_users[]=" + pair.key + "&"; }); url += this.form.serialize(); // send ajax request new Ajax.Request(url, {method: 'put'}); }, /* * save blog */ save_blog: function(){ this.save('blog'); }, /* * save draft */ save_draft: function(){ this.save('draft'); }, /* * update blog */ update_blog: function(blog_id){ this.update('blog', blog_id); }, /* * update draft */ update_draft: function(draft_id){ this.update('draft', draft_id); }, /* * hide friends list */ hide_friends: function(){ this.popup.hide(); this.unfold.update('unfold'); this.unfold.observe('click', function(){ this.show_friends(); }.bind(this)); }, /* * show friends */ show_friends: function(){ if(this.popup){ this.popup.show(); }else{ // create popup frame with the following html code: // <div> // <div> select friends: <select> select game here </select></div> // <div> friend list </div> // <button> confirm </button> // </div> this.popup = new Element('div'); this.game_category = new Element('div'); this.label = new Element('label').update('select friends: '); this.selector = new Element('select'); this.friends_list = new Element('div'); this.confirm_button = new Element('button').update('confirm'); this.game_category.appendChild(this.label); this.game_category.appendChild(this.selector); this.popup.appendChild(this.game_category); this.popup.appendChild(this.friends_list); this.popup.appendChild(this.confirm_button); // add click event to confirm button this.set_button_event(); // send ajax request to retrieve all the games this.get_games(); // send ajax request to retrieve all friends this.get_friends('all'); // add popup element to document document.body.appendChild(this.popup); this.popup.hide(); // set friend list style this.friends_list.setStyle({ width: '350px', height: '150px', overflow: 'auto' }); // set popup frame position this.popup.setStyle({ position: 'absolute', left: (this.unfold.positionedOffset().left - 350) + 'px', top: this.unfold.positionedOffset().top + 'px', }); this.popup.show(); } this.unfold.update('fold'); this.unfold.observe('click', function(){ this.hide_friends(); }.bind(this)); }, /* * return an array of tagged users id */ get_tagged_users: function(){ var inputs = $$('input'); var length = inputs.length; var tagged_users = []; for(var i = 0; i < length; i++){ - if(inputs[i].type == 'checkbox' && inputs[i].checked){ + if(inputs[i].type == 'checkbox' && inputs[i].checked && !this.btags.get(inputs[i].value)){ tagged_users.push(inputs[i].value); } } return tagged_users; }, /* * add click listener for confirm button */ set_button_event: function(){ this.confirm_button.observe('click', function(event){ var tagged_users = this.get_tagged_users(); // if no one is selected, // remove popup frame and return if(tagged_users.length == 0){ this.hide_friends(); return; } // construct parameters and url var url = '/user_blogs/new_tag?'; for(var i=0;i<tagged_users.length;i++){ url += "tagged_users[]=" + tagged_users[i] + "&"; } // send ajax request to retreive user info // note that at this time, the tags are not stored in database yet new Ajax.Request(url, { method: 'get', onSuccess: function(transport){ this.btags_div.innerHTML = transport.responseText + this.btags_div.innerHTML; this.hide_friends(); var children = this.btags_div.childElements(); - for(var i=0;i<tagged_users.length;i++){ - this.btags.set(tagged_users[i], children[i]); + var length = children.length; + for(var i=0;i<length;i++){ + this.btags.set(children[i].readAttribute('tagged_user_id'), children[i]); } }.bind(this) }); }.bind(this)); }, /* * return relevant games */ get_games: function(){ // send ajax request to retrieve all the games new Ajax.Request('/user_blogs/games_list', { method: 'get', onSuccess: function(transport){ // fill in selecter with retreived game options this.selector.innerHTML = transport.responseText; // add on change listener to selector this.selector.observe('change', function(){ // get friends within the same game this.get_friends($F(this.selector)); }.bind(this)); }.bind(this) }); }, /* * return friends within same game */ get_friends: function(game_id){ new Ajax.Request('/user_blogs/friends_list?game_id=' + game_id, { method: 'get', onSuccess: function(transport){ this.friends_list.innerHTML = transport.responseText; }.bind(this) }); }, /* * new tag * pay attention that this tag is not stored in database until you click 'save' or 'save as draft' */ new_tag: function(tagged_user_id){ // if this user is already tagged, skip it if(this.btags.get(tagged_user_id)) return; // send ajax request to retrieve user information(icon, name ... so on) new Ajax.Request('/user_blogs/new_tag?tagged_users[]=' + tagged_user_id, { method: 'get', onSuccess: function(transport){ this.btags_div.innerHTML = transport.responseText + this.btags_div.innerHTML; this.tag_input.value = ''; - // add this new tag to hash - this.btags.set(tagged_user_id, this.btags_div.childElements().last()); + var children = this.btags_div.childElements(); + var length = children.length; + for(var i=0;i<length;i++){ + this.btags.set(children[i].readAttribute('tagged_user_id'), children[i]); + } }.bind(this) }); }, /* * remove tag */ remove_tag: function(tagged_user_id){ var btag = this.btags.unset(tagged_user_id); if(!btag) return; // if it's not a new record, it means it stores in database, // then do an ajax request to remove it from database if(btag.readAttribute('new_record') != 'true') new Ajax.Request('/blogs/' + this.blog_id + '/tags/' + btag.readAttribute('tag_id'), {method: 'delete'}); btag.remove(); }, }); diff --git a/public/javascripts/blog.js~ b/public/javascripts/blog.js~ new file mode 100644 index 0000000..7dbfb0e --- /dev/null +++ b/public/javascripts/blog.js~ @@ -0,0 +1,431 @@ +PopupManager = Class.create({ + + /* + * initialize + */ + initialize: function(user_id, options){ + this.user_id = user_id; + + // read options + this.options = Object.extend({ + popup_class: 'popup-class', + user_info_class: 'popup-user-info-class', + }, options || {}); + }, + + /* + * popup user information + */ + show: function(user_id, linker){ + if(this.popup) + this.popup.hide(); + else{ + // create popup element and close button + this.popup = new Element('div', {className: this.options.popup_class}); + this.user_info = new Element('div', {className: this.options.user_info_class}); + this.close_button = new Element('button'); + this.close_button.update('close'); + this.popup.appendChild(this.user_info); + this.popup.appendChild(this.close_button); + + // add click event to close button + this.close_button.observe('click', function(event){ + this.popup.hide(); + }.bind(this)); + } + + // record position and user_id + this.pos = linker.positionedOffset(); + this.pos.left += linker.getWidth(); + + // send ajax request to server to retrieve user info + new Ajax.Request("/user_blogs/show_popup_tag?tagged_user_id="+user_id, { + method: 'get', + onSuccess: function(transport){ + this.user_info.innerHTML = transport.responseText; + this.popup.setStyle({ + position: 'absolute', + left: this.pos.left + 'px', + top: this.pos.top + 'px', + backgroundColor: '#fff' + }); + document.body.appendChild(this.popup); + this.popup.show(); + }.bind(this) + }); + } + +}); + + +DraftManager = Class.create({ + /* + * initialize + * just save drafts element + */ + initialize: function(user_id){ + this.drafts = $('my_drafts'); + this.user_id = user_id; + }, + + /* + * get all selected drafts + */ + get_selected: function(){ + var selected = []; + var inputs = $$('input'); + for(var i=0;i<inputs.length;i++){ + if(inputs[i].type == 'checkbox' && inputs[i].checked){ + selected.push(inputs[i]); + } + } + return selected; + }, + + /* + * get all drafts + */ + get_all: function(){ + var all = []; + var inputs = $$('input'); + for(var i=0;i<inputs.length;i++){ + if(inputs[i].type == 'checkbox'){ + all.push(inputs[i]); + } + } + return all; + }, + + /* + * select all drafts + * set all checkboxes to true + */ + select_all: function(){ + var all = this.get_all(); + for(var i=0;i<all.length;i++){ + all[i].checked=true; + } + }, + + /* + * delete selected drafts + */ + delete_selected: function(){ + var selected = this.get_selected(); + + // construct ure + url = "/users/" + this.user_id + "/blogs/destroy_multiple?"; + for(var i=0;i<selected.length;i++){ + url += "blogs[]=" + selected[i].readAttribute('blog_id') + "&"; + } + + // send ajax request to remove it from database + new Ajax.Request(url, {method: 'delete'}); + } +}); + +function after_tag(input_field, selected_li){ + blog_builder.new_tag(selected_li.readAttribute('user_id')); + $('blog_tags').value = ''; +} + +BlogBuilder = Class.create({ + + initialize: function(user_id, blog_id){ + // save user id and blog id + this.user_id = user_id; + this.blog_id = blog_id; // this field is only valid when updating blog + + // save tag input field and set its initial text + this.tag_input = $('blog_tags'); + this.tag_input.value = 'please tag your friend here'; + + // add on focus event to tag input + this.tag_input.observe('focus', function(event){ + this.value = ''; + }); + + // add on blur event to tag input + this.tag_input.observe('blur', function(event){ + this.value = 'please tag your friends here'; + }); + + // input form + this.form = $('blog_input'); + + // save btags div which displays all current btags + this.btags_div = $('btags'); + + // fold, unfold handler + this.unfold = $('unfold'); + + // we maintain a hash of blog tags + this.btags = new Hash(); + var current_tags = this.btags_div.childElements(); + for(var i=0;i<current_tags.length;i++){ + this.btags.set(current_tags[i].readAttribute('tagged_user_id'), current_tags[i]); + + } + }, + + /* + * save as blog or draft which is determined by type + */ + save: function(type){ + // construct url + // appending form inputs and tag inputs + var url = '/users/' + this.user_id + '/blogs?'; + if(type == 'blog') + url += "blog[draft]=0&" + else + url += "blog[draft]=1&" + this.btags.each(function(pair){ + if(pair.value.readAttribute('new_record') == 'true') + url += "tagged_users[]=" + pair.key + "&"; + }); + url += this.form.serialize(); + + // send ajax request + new Ajax.Request(url, {method: 'post'}); + }, + + /* + * update as blog or draft which is determined by type + * this function also needs blog id or draft id + */ + update: function(type, id){ + // construct url + // appending form inputs and tag inputs + var url = '/users/' + this.user_id + '/blogs/' + id + '?'; + if(type == 'blog') + url += "blog[draft]=0&" + else + url += "blog[draft]=1&" + this.btags.each(function(pair){ + if(pair.value.readAttribute('new_record') == 'true') + url += "tagged_users[]=" + pair.key + "&"; + }); + url += this.form.serialize(); + + // send ajax request + new Ajax.Request(url, {method: 'put'}); + }, + + /* + * save blog + */ + save_blog: function(){ + this.save('blog'); + }, + + /* + * save draft + */ + save_draft: function(){ + this.save('draft'); + }, + + /* + * update blog + */ + update_blog: function(blog_id){ + this.update('blog', blog_id); + }, + + /* + * update draft + */ + update_draft: function(draft_id){ + this.update('draft', draft_id); + }, + + /* + * hide friends list + */ + hide_friends: function(){ + this.popup.hide(); + this.unfold.update('unfold'); + this.unfold.observe('click', function(){ + this.show_friends(); + }.bind(this)); + }, + + /* + * show friends + */ + show_friends: function(){ + if(this.popup){ + this.popup.show(); + }else{ + // create popup frame with the following html code: + // <div> + // <div> select friends: <select> select game here </select></div> + // <div> friend list </div> + // <button> confirm </button> + // </div> + this.popup = new Element('div'); + this.game_category = new Element('div'); + this.label = new Element('label').update('select friends: '); + this.selector = new Element('select'); + this.friends_list = new Element('div'); + this.confirm_button = new Element('button').update('confirm'); + this.game_category.appendChild(this.label); + this.game_category.appendChild(this.selector); + this.popup.appendChild(this.game_category); + this.popup.appendChild(this.friends_list); + this.popup.appendChild(this.confirm_button); + + // add click event to confirm button + this.set_button_event(); + + // send ajax request to retrieve all the games + this.get_games(); + + // send ajax request to retrieve all friends + this.get_friends('all'); + + // add popup element to document + document.body.appendChild(this.popup); + this.popup.hide(); + + // set friend list style + this.friends_list.setStyle({ + width: '350px', + height: '150px', + overflow: 'auto' + }); + + // set popup frame position + this.popup.setStyle({ + position: 'absolute', + left: (this.unfold.positionedOffset().left - 350) + 'px', + top: this.unfold.positionedOffset().top + 'px', + }); + + this.popup.show(); + } + + this.unfold.update('fold'); + this.unfold.observe('click', function(){ + this.hide_friends(); + }.bind(this)); + }, + + /* + * return an array of tagged users id + */ + get_tagged_users: function(){ + var inputs = $$('input'); + var length = inputs.length; + var tagged_users = []; + for(var i = 0; i < length; i++){ + if(inputs[i].type == 'checkbox' && inputs[i].checked && this.btags.get(inputs[i].value)){ + tagged_users.push(inputs[i].value); + } + } + return tagged_users; + }, + + /* + * add click listener for confirm button + */ + set_button_event: function(){ + this.confirm_button.observe('click', function(event){ + var tagged_users = this.get_tagged_users(); + + // if no one is selected, + // remove popup frame and return + if(tagged_users.length == 0){ + this.hide_friends(); + return; + } + + // construct parameters and url + var url = '/user_blogs/new_tag?'; + for(var i=0;i<tagged_users.length;i++){ + url += "tagged_users[]=" + tagged_users[i] + "&"; + } + + // send ajax request to retreive user info + // note that at this time, the tags are not stored in database yet + new Ajax.Request(url, { + method: 'get', + onSuccess: function(transport){ + this.btags_div.innerHTML = transport.responseText + this.btags_div.innerHTML; + this.hide_friends(); + var children = this.btags_div.childElements(); + for(var i=0;i<tagged_users.length;i++){ + this.btags.set(tagged_users[i], children[i]); + } + }.bind(this) + }); + }.bind(this)); + }, + + /* + * return relevant games + */ + get_games: function(){ + // send ajax request to retrieve all the games + new Ajax.Request('/user_blogs/games_list', { + method: 'get', + onSuccess: function(transport){ + // fill in selecter with retreived game options + this.selector.innerHTML = transport.responseText; + + // add on change listener to selector + this.selector.observe('change', function(){ + // get friends within the same game + this.get_friends($F(this.selector)); + }.bind(this)); + }.bind(this) + }); + }, + + /* + * return friends within same game + */ + get_friends: function(game_id){ + new Ajax.Request('/user_blogs/friends_list?game_id=' + game_id, { + method: 'get', + onSuccess: function(transport){ + this.friends_list.innerHTML = transport.responseText; + }.bind(this) + }); + }, + + /* + * new tag + * pay attention that this tag is not stored in database until you click 'save' or 'save as draft' + */ + new_tag: function(tagged_user_id){ + // if this user is already tagged, skip it + if(this.btags.get(tagged_user_id)) return; + + // send ajax request to retrieve user information(icon, name ... so on) + new Ajax.Request('/user_blogs/new_tag?tagged_users[]=' + tagged_user_id, { + method: 'get', + onSuccess: function(transport){ + this.btags_div.innerHTML = transport.responseText + this.btags_div.innerHTML; + this.tag_input.value = ''; + // add this new tag to hash + this.btags.set(tagged_user_id, this.btags_div.childElements().first()); + }.bind(this) + }); + }, + + /* + * remove tag + */ + remove_tag: function(tagged_user_id){ + var btag = this.btags.unset(tagged_user_id); + if(!btag) return; + + // if it's not a new record, it means it stores in database, + // then do an ajax request to remove it from database + if(btag.readAttribute('new_record') != 'true') + new Ajax.Request('/blogs/' + this.blog_id + '/tags/' + btag.readAttribute('tag_id'), {method: 'delete'}); + + btag.remove(); + }, +}); diff --git a/public/javascripts/video.js b/public/javascripts/video.js new file mode 100644 index 0000000..0bad8de --- /dev/null +++ b/public/javascripts/video.js @@ -0,0 +1,282 @@ +VideoBuilder = Class.create({ + + initialize: function(user_id, video_id){ + // save user id and video id + this.user_id = user_id; + this.video_id = video_id; + + // save tag input field and set its initial text + this.tag_input = $('video_tags'); + this.tag_input.value = 'please tag your friend here'; + + // add on focus event to tag input + this.tag_input.observe('focus', function(event){ + this.value = ''; + }); + + // add on blur event to tag input + this.tag_input.observe('blur', function(event){ + this.value = 'please tag your friends here'; + }); + + // input form + this.form = $('video_input'); + + // save btags div which displays all current btags + this.vtags_div = $('vtags'); + + // fold, unfold handler + this.unfold = $('unfold'); + + // we maintain a hash of blog tags + this.vtags = new Hash(); + var vtags = this.vtags_div.childElements(); + for(var i=0;i<vtags.length;i++){ + this.vtags.set(vtags[i].readAttribute('tagged_user_id'), vtags[i]); + } + + alert('done'); + }, + + /* + * hide friends list + */ + hide_friends: function(){ + this.popup.hide(); + this.unfold.update('unfold'); + this.unfold.observe('click', function(){ + this.show_friends(); + }.bind(this)); + }, + + /* + * show friends + */ + show_friends: function(){ + if(this.popup){ + this.popup.show(); + }else{ + // create popup frame with the following html code: + // <div> + // <div> select friends: <select> select game here </select></div> + // <div> friend list </div> + // <button> confirm </button> + // </div> + this.popup = new Element('div'); + this.game_category = new Element('div'); + this.label = new Element('label').update('select friends: '); + this.selector = new Element('select'); + this.friends_list = new Element('div'); + this.confirm_button = new Element('button').update('confirm'); + this.game_category.appendChild(this.label); + this.game_category.appendChild(this.selector); + this.popup.appendChild(this.game_category); + this.popup.appendChild(this.friends_list); + this.popup.appendChild(this.confirm_button); + + // add click event to confirm button + this.set_button_event(); + + // send ajax request to retrieve all the games + this.get_games(); + + // send ajax request to retrieve all friends + this.get_friends('all'); + + // add popup element to document + document.body.appendChild(this.popup); + this.popup.hide(); + + // set friend list style + this.friends_list.setStyle({ + width: '350px', + height: '150px', + overflow: 'auto' + }); + + // set popup frame position + this.popup.setStyle({ + position: 'absolute', + left: (this.unfold.positionedOffset().left - 350) + 'px', + top: this.unfold.positionedOffset().top + 'px' + }); + + this.popup.show(); + } + + this.unfold.update('fold'); + this.unfold.observe('click', function(){ + this.hide_friends(); + }.bind(this)); + }, + + /* + * return an array of tagged users id + */ + get_tagged_users: function(){ + var inputs = $$('input'); + var length = inputs.length; + var tagged_users = []; + for(var i = 0; i < length; i++){ + if(inputs[i].type == 'checkbox' && inputs[i].checked && !this.vtags.get(inputs[i].value)){ + tagged_users.push(inputs[i].value); + } + } + return tagged_users; + }, + + /* + * add click listener for confirm button + */ + set_button_event: function(){ + this.confirm_button.observe('click', function(event){ + var tagged_users = this.get_tagged_users(); + + // if no one is selected, + // remove popup frame and return + if(tagged_users.length == 0){ + this.hide_friends(); + return; + } + + // construct parameters and url + var url = '/user_videos/new_tag?'; + for(var i=0;i<tagged_users.length;i++){ + url += "tagged_users[]=" + tagged_users[i] + "&"; + } + + // send ajax request to retreive user info + // note that at this time, the tags are not stored in database yet + new Ajax.Request(url, { + method: 'get', + onSuccess: function(transport){ + this.vtags_div.innerHTML = transport.responseText + this.vtags_div.innerHTML; + this.hide_friends(); + var children = this.vtags_div.childElements(); + var length = children.length; + for(var i=0;i<length;i++){ + this.vtags.set(children[i].readAttribute('tagged_user_id'), children[i]); + } + }.bind(this) + }); + }.bind(this)); + }, + + /* + * return relevant games + */ + get_games: function(){ + // send ajax request to retrieve all the games + new Ajax.Request('/user_blogs/games_list', { + method: 'get', + onSuccess: function(transport){ + // fill in selecter with retreived game options + this.selector.innerHTML = transport.responseText; + + // add on change listener to selector + this.selector.observe('change', function(){ + // get friends within the same game + this.get_friends($F(this.selector)); + }.bind(this)); + }.bind(this) + }); + }, + + /* + * return friends within same game + */ + get_friends: function(game_id){ + new Ajax.Request('/user_blogs/friends_list?game_id=' + game_id, { + method: 'get', + onSuccess: function(transport){ + this.friends_list.innerHTML = transport.responseText; + }.bind(this) + }); + }, + + /* + * new tag + * pay attention that this tag is not stored in database until you click 'save' or 'save as draft' + */ + new_tag: function(tagged_user_id){ + // if this user is already tagged, skip it + if(this.vtags.get(tagged_user_id)) return; + + // send ajax request to retrieve user information(icon, name ... so on) + new Ajax.Request('/user_videos/new_tag?tagged_users[]=' + tagged_user_id, { + method: 'get', + onSuccess: function(transport){ + this.vtags_div.innerHTML = transport.responseText + this.vtags_div.innerHTML; + this.tag_input.value = ''; + var children = this.vtags_div.childElements(); + var length = children.length; + for(var i=0;i<length;i++){ + this.vtags.set(children[i].readAttribute('tagged_user_id'), children[i]); + } + }.bind(this) + }); + }, + + /* + * remove tag + */ + remove_tag: function(tagged_user_id){ + var vtag = this.vtags.unset(tagged_user_id); + if(!vtag) return; + // if it's not a new record, it means it stores in database, + // then do an ajax request to remove it from database + if(vtag.readAttribute('new_record') != 'true') + new Ajax.Request('/videos/' + this.video_id + '/tags/' + vtag.readAttribute('tag_id'), {method: 'delete'}); + + vtag.remove(); + }, + + /* + * save + */ + save: function(){ + // construct url + // appending form inputs and tag inputs + var url = '/users/' + this.user_id + '/videos?'; + this.vtags.each(function(pair){ + if(pair.value.readAttribute('new_record') == 'true') + url += "tagged_users[]=" + pair.key + "&"; + }); + url += this.form.serialize(); + + // send ajax request + new Ajax.Request(url, {method: 'post'}); + }, + + /* + * update as blog or draft which is determined by type + * this function also needs blog id or draft id + */ + update: function(id){ + // construct url + // appending form inputs and tag inputs + var url = '/users/' + this.user_id + '/videos/' + id + '?'; + this.vtags.each(function(pair){ + if(pair.value.readAttribute('new_record') == 'true') + url += "tagged_users[]=" + pair.key + "&"; + }); + url += this.form.serialize(); + + // send ajax request + new Ajax.Request(url, {method: 'put'}); + }, + +}) + +function after_tag(input_field, selected_li){ + video_builder.new_tag(selected_li.readAttribute('user_id')); + video_builder.tag_input.value = ''; +} + +function play_video(video_id, video_link){ + $('video_' + video_id).innerHTML = video_link; +} + + + + diff --git a/public/photos/0000/0001/1.jpg b/public/photos/0000/0001/1.jpg old mode 100755 new mode 100644 diff --git a/public/photos/0000/0001/1_large.jpg b/public/photos/0000/0001/1_large.jpg old mode 100755 new mode 100644 diff --git a/public/photos/0000/0001/1_medium.jpg b/public/photos/0000/0001/1_medium.jpg old mode 100755 new mode 100644 diff --git a/public/photos/0000/0001/1_small.jpg b/public/photos/0000/0001/1_small.jpg old mode 100755 new mode 100644 diff --git a/public/photos/0000/0001/3.jpg b/public/photos/0000/0001/3.jpg new file mode 100644 index 0000000..929433c Binary files /dev/null and b/public/photos/0000/0001/3.jpg differ diff --git a/public/photos/0000/0001/3_large.jpg b/public/photos/0000/0001/3_large.jpg new file mode 100644 index 0000000..33b72aa Binary files /dev/null and b/public/photos/0000/0001/3_large.jpg differ diff --git a/public/photos/0000/0001/3_medium.jpg b/public/photos/0000/0001/3_medium.jpg new file mode 100644 index 0000000..b46e5c3 Binary files /dev/null and b/public/photos/0000/0001/3_medium.jpg differ diff --git a/public/photos/0000/0001/3_small.jpg b/public/photos/0000/0001/3_small.jpg new file mode 100644 index 0000000..e7a2c91 Binary files /dev/null and b/public/photos/0000/0001/3_small.jpg differ diff --git a/test/fixtures/vcomments.yml b/test/fixtures/vcomments.yml new file mode 100644 index 0000000..63c980c --- /dev/null +++ b/test/fixtures/vcomments.yml @@ -0,0 +1,11 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +one: + user_id: 1 + video_id: 1 + content: MyText + +two: + user_id: 1 + video_id: 1 + content: MyText diff --git a/test/fixtures/vdigs.yml b/test/fixtures/vdigs.yml new file mode 100644 index 0000000..370aa98 --- /dev/null +++ b/test/fixtures/vdigs.yml @@ -0,0 +1,9 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +one: + user_id: 1 + video_id: 1 + +two: + user_id: 1 + video_id: 1 diff --git a/test/fixtures/videos.yml b/test/fixtures/videos.yml new file mode 100644 index 0000000..815d537 --- /dev/null +++ b/test/fixtures/videos.yml @@ -0,0 +1,19 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +one: + user_id: 1 + game_id: 1 + title: MyString + url: MyString + link: MyText + digs_count: 1 + comments_count: 1 + +two: + user_id: 1 + game_id: 1 + title: MyString + url: MyString + link: MyText + digs_count: 1 + comments_count: 1 diff --git a/test/fixtures/vtags.yml b/test/fixtures/vtags.yml new file mode 100644 index 0000000..e36d633 --- /dev/null +++ b/test/fixtures/vtags.yml @@ -0,0 +1,11 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +one: + user_id: 1 + tagged_user_id: 1 + video_id: 1 + +two: + user_id: 1 + tagged_user_id: 1 + video_id: 1 diff --git a/test/functional/user_videos_controller_test.rb b/test/functional/user_videos_controller_test.rb new file mode 100644 index 0000000..d39c033 --- /dev/null +++ b/test/functional/user_videos_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class UserVideosControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/vcomments_controller_test.rb b/test/functional/vcomments_controller_test.rb new file mode 100644 index 0000000..a05184a --- /dev/null +++ b/test/functional/vcomments_controller_test.rb @@ -0,0 +1,45 @@ +require 'test_helper' + +class VcommentsControllerTest < ActionController::TestCase + test "should get index" do + get :index + assert_response :success + assert_not_nil assigns(:vcomments) + end + + test "should get new" do + get :new + assert_response :success + end + + test "should create vcomment" do + assert_difference('Vcomment.count') do + post :create, :vcomment => { } + end + + assert_redirected_to vcomment_path(assigns(:vcomment)) + end + + test "should show vcomment" do + get :show, :id => vcomments(:one).to_param + assert_response :success + end + + test "should get edit" do + get :edit, :id => vcomments(:one).to_param + assert_response :success + end + + test "should update vcomment" do + put :update, :id => vcomments(:one).to_param, :vcomment => { } + assert_redirected_to vcomment_path(assigns(:vcomment)) + end + + test "should destroy vcomment" do + assert_difference('Vcomment.count', -1) do + delete :destroy, :id => vcomments(:one).to_param + end + + assert_redirected_to vcomments_path + end +end diff --git a/test/functional/vdigs_controller_test.rb b/test/functional/vdigs_controller_test.rb new file mode 100644 index 0000000..1ffaf71 --- /dev/null +++ b/test/functional/vdigs_controller_test.rb @@ -0,0 +1,45 @@ +require 'test_helper' + +class VdigsControllerTest < ActionController::TestCase + test "should get index" do + get :index + assert_response :success + assert_not_nil assigns(:vdigs) + end + + test "should get new" do + get :new + assert_response :success + end + + test "should create vdig" do + assert_difference('Vdig.count') do + post :create, :vdig => { } + end + + assert_redirected_to vdig_path(assigns(:vdig)) + end + + test "should show vdig" do + get :show, :id => vdigs(:one).to_param + assert_response :success + end + + test "should get edit" do + get :edit, :id => vdigs(:one).to_param + assert_response :success + end + + test "should update vdig" do + put :update, :id => vdigs(:one).to_param, :vdig => { } + assert_redirected_to vdig_path(assigns(:vdig)) + end + + test "should destroy vdig" do + assert_difference('Vdig.count', -1) do + delete :destroy, :id => vdigs(:one).to_param + end + + assert_redirected_to vdigs_path + end +end diff --git a/test/functional/video_comments_controller_test.rb b/test/functional/video_comments_controller_test.rb new file mode 100644 index 0000000..6c88226 --- /dev/null +++ b/test/functional/video_comments_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class VideoCommentsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/video_digs_controller_test.rb b/test/functional/video_digs_controller_test.rb new file mode 100644 index 0000000..f50c957 --- /dev/null +++ b/test/functional/video_digs_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class VideoDigsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/video_tags_controller_test.rb b/test/functional/video_tags_controller_test.rb new file mode 100644 index 0000000..294a8a5 --- /dev/null +++ b/test/functional/video_tags_controller_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class VideoTagsControllerTest < ActionController::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/functional/videos_controller_test.rb b/test/functional/videos_controller_test.rb new file mode 100644 index 0000000..e15ae7a --- /dev/null +++ b/test/functional/videos_controller_test.rb @@ -0,0 +1,45 @@ +require 'test_helper' + +class VideosControllerTest < ActionController::TestCase + test "should get index" do + get :index + assert_response :success + assert_not_nil assigns(:videos) + end + + test "should get new" do + get :new + assert_response :success + end + + test "should create video" do + assert_difference('Video.count') do + post :create, :video => { } + end + + assert_redirected_to video_path(assigns(:video)) + end + + test "should show video" do + get :show, :id => videos(:one).to_param + assert_response :success + end + + test "should get edit" do + get :edit, :id => videos(:one).to_param + assert_response :success + end + + test "should update video" do + put :update, :id => videos(:one).to_param, :video => { } + assert_redirected_to video_path(assigns(:video)) + end + + test "should destroy video" do + assert_difference('Video.count', -1) do + delete :destroy, :id => videos(:one).to_param + end + + assert_redirected_to videos_path + end +end diff --git a/test/functional/vtags_controller_test.rb b/test/functional/vtags_controller_test.rb new file mode 100644 index 0000000..11434a6 --- /dev/null +++ b/test/functional/vtags_controller_test.rb @@ -0,0 +1,45 @@ +require 'test_helper' + +class VtagsControllerTest < ActionController::TestCase + test "should get index" do + get :index + assert_response :success + assert_not_nil assigns(:vtags) + end + + test "should get new" do + get :new + assert_response :success + end + + test "should create vtag" do + assert_difference('Vtag.count') do + post :create, :vtag => { } + end + + assert_redirected_to vtag_path(assigns(:vtag)) + end + + test "should show vtag" do + get :show, :id => vtags(:one).to_param + assert_response :success + end + + test "should get edit" do + get :edit, :id => vtags(:one).to_param + assert_response :success + end + + test "should update vtag" do + put :update, :id => vtags(:one).to_param, :vtag => { } + assert_redirected_to vtag_path(assigns(:vtag)) + end + + test "should destroy vtag" do + assert_difference('Vtag.count', -1) do + delete :destroy, :id => vtags(:one).to_param + end + + assert_redirected_to vtags_path + end +end diff --git a/test/unit/helpers/user_videos_helper_test.rb b/test/unit/helpers/user_videos_helper_test.rb new file mode 100644 index 0000000..2a82b0b --- /dev/null +++ b/test/unit/helpers/user_videos_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class UserVideosHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/vcomments_helper_test.rb b/test/unit/helpers/vcomments_helper_test.rb new file mode 100644 index 0000000..0b6bbec --- /dev/null +++ b/test/unit/helpers/vcomments_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class VcommentsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/vdigs_helper_test.rb b/test/unit/helpers/vdigs_helper_test.rb new file mode 100644 index 0000000..04ea052 --- /dev/null +++ b/test/unit/helpers/vdigs_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class VdigsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/video_comments_helper_test.rb b/test/unit/helpers/video_comments_helper_test.rb new file mode 100644 index 0000000..f0590f7 --- /dev/null +++ b/test/unit/helpers/video_comments_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class VideoCommentsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/video_digs_helper_test.rb b/test/unit/helpers/video_digs_helper_test.rb new file mode 100644 index 0000000..69f9374 --- /dev/null +++ b/test/unit/helpers/video_digs_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class VideoDigsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/video_tags_helper_test.rb b/test/unit/helpers/video_tags_helper_test.rb new file mode 100644 index 0000000..fd760ac --- /dev/null +++ b/test/unit/helpers/video_tags_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class VideoTagsHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/videos_helper_test.rb b/test/unit/helpers/videos_helper_test.rb new file mode 100644 index 0000000..d046bf4 --- /dev/null +++ b/test/unit/helpers/videos_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class VideosHelperTest < ActionView::TestCase +end diff --git a/test/unit/helpers/vtags_helper_test.rb b/test/unit/helpers/vtags_helper_test.rb new file mode 100644 index 0000000..4060f85 --- /dev/null +++ b/test/unit/helpers/vtags_helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class VtagsHelperTest < ActionView::TestCase +end diff --git a/test/unit/vcomment_test.rb b/test/unit/vcomment_test.rb new file mode 100644 index 0000000..c6586d3 --- /dev/null +++ b/test/unit/vcomment_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class VcommentTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/vdig_test.rb b/test/unit/vdig_test.rb new file mode 100644 index 0000000..86a138b --- /dev/null +++ b/test/unit/vdig_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class VdigTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/video_test.rb b/test/unit/video_test.rb new file mode 100644 index 0000000..b0bc6fe --- /dev/null +++ b/test/unit/video_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class VideoTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/vtag_test.rb b/test/unit/vtag_test.rb new file mode 100644 index 0000000..5d4ff1e --- /dev/null +++ b/test/unit/vtag_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class VtagTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end
goodxiexin/dayday3
8b4e27b483db9d921aca742f20c78d1cd3a1cf18
little test
diff --git a/test1 b/test1 new file mode 100644 index 0000000..e69de29
goodxiexin/dayday3
243622b673f7768baf24cf5093668e3b94f1ee2f
photo tag completion
diff --git a/.TODO.swp b/.TODO.swp old mode 100644 new mode 100755 index 0005486..d13a1ec Binary files a/.TODO.swp and b/.TODO.swp differ diff --git a/README b/README old mode 100644 new mode 100755 diff --git a/Rakefile b/Rakefile old mode 100644 new mode 100755 diff --git a/TODO b/TODO old mode 100644 new mode 100755 index 637f25a..9867c66 --- a/TODO +++ b/TODO @@ -1,9 +1,11 @@ 1. profile (get javascript work) DONE -2. show tag +2. show tag DONE -3. video +3. think about resources:game_characters and user_characters -4. blog +4. video -5. view friends' pages +5. blog + +6. view friends' pages diff --git a/app/controllers/admin/pages_controller.rb b/app/controllers/admin/pages_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/album_feeds_controller.rb b/app/controllers/album_feeds_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/album_photos_controller.rb b/app/controllers/album_photos_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/albums_controller.rb b/app/controllers/albums_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/basic_info_controller.rb b/app/controllers/basic_info_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/bcomments_controller.rb b/app/controllers/bcomments_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/bdigs_controller.rb b/app/controllers/bdigs_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/blog_comments_controller.rb b/app/controllers/blog_comments_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/blog_digs_controller.rb b/app/controllers/blog_digs_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/blog_feeds_controller.rb b/app/controllers/blog_feeds_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/blog_tags_controller.rb b/app/controllers/blog_tags_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/blogs_controller.rb b/app/controllers/blogs_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/btags_controller.rb b/app/controllers/btags_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/cities_controller.rb b/app/controllers/cities_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/contact_info_controller.rb b/app/controllers/contact_info_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/countries_controller.rb b/app/controllers/countries_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/friends_controller.rb b/app/controllers/friends_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/friendships_controller.rb b/app/controllers/friendships_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/game_areas_controller.rb b/app/controllers/game_areas_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/game_characters_controller.rb b/app/controllers/game_characters_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/game_professions_controller.rb b/app/controllers/game_professions_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/game_races_controller.rb b/app/controllers/game_races_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/game_servers_controller.rb b/app/controllers/game_servers_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/games_controller.rb b/app/controllers/games_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/icons_controller.rb b/app/controllers/icons_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/mailboxes_controller.rb b/app/controllers/mailboxes_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/mails_controller.rb b/app/controllers/mails_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/pcomments_controller.rb b/app/controllers/pcomments_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/pdigs_controller.rb b/app/controllers/pdigs_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/photo_comments_controller.rb b/app/controllers/photo_comments_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/photo_digs_controller.rb b/app/controllers/photo_digs_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/photo_tags_controller.rb b/app/controllers/photo_tags_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/photos_controller.rb b/app/controllers/photos_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/provinces_controller.rb b/app/controllers/provinces_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/ptags_controller.rb b/app/controllers/ptags_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/root_controller.rb b/app/controllers/root_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/statuses_controller.rb b/app/controllers/statuses_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/tagged_blogs_controller.rb b/app/controllers/tagged_blogs_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/tagged_photos_controller.rb b/app/controllers/tagged_photos_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/user_albums_controller.rb b/app/controllers/user_albums_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/user_blogs_controller.rb b/app/controllers/user_blogs_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/user_characters_controller.rb b/app/controllers/user_characters_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/user_statuses_controller.rb b/app/controllers/user_statuses_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/user_wall_messages_controller.rb b/app/controllers/user_wall_messages_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/validator_controller.rb b/app/controllers/validator_controller.rb old mode 100644 new mode 100755 diff --git a/app/controllers/wall_messages_controller.rb b/app/controllers/wall_messages_controller.rb old mode 100644 new mode 100755 diff --git a/app/helpers/album_feeds_helper.rb b/app/helpers/album_feeds_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/album_photos_helper.rb b/app/helpers/album_photos_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/albums_helper.rb b/app/helpers/albums_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/basic_info_helper.rb b/app/helpers/basic_info_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/bcomments_helper.rb b/app/helpers/bcomments_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/bdigs_helper.rb b/app/helpers/bdigs_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/blog_comments_helper.rb b/app/helpers/blog_comments_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/blog_digs_helper.rb b/app/helpers/blog_digs_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/blog_feeds_helper.rb b/app/helpers/blog_feeds_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/blog_tags_helper.rb b/app/helpers/blog_tags_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/blogs_helper.rb b/app/helpers/blogs_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/btags_helper.rb b/app/helpers/btags_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/cities_helper.rb b/app/helpers/cities_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/contact_info_helper.rb b/app/helpers/contact_info_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/countries_helper.rb b/app/helpers/countries_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/friends_helper.rb b/app/helpers/friends_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/friendships_helper.rb b/app/helpers/friendships_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/game_areas_helper.rb b/app/helpers/game_areas_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/game_characters_helper.rb b/app/helpers/game_characters_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/game_professions_helper.rb b/app/helpers/game_professions_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/game_races_helper.rb b/app/helpers/game_races_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/game_servers_helper.rb b/app/helpers/game_servers_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/games_helper.rb b/app/helpers/games_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/icons_helper.rb b/app/helpers/icons_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/mailboxes_helper.rb b/app/helpers/mailboxes_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/mails_helper.rb b/app/helpers/mails_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/pages_helper.rb b/app/helpers/pages_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/passwords_helper.rb b/app/helpers/passwords_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/pcomments_helper.rb b/app/helpers/pcomments_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/pdigs_helper.rb b/app/helpers/pdigs_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/photo_comments_helper.rb b/app/helpers/photo_comments_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/photo_digs_helper.rb b/app/helpers/photo_digs_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/photo_tags_helper.rb b/app/helpers/photo_tags_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/photos_helper.rb b/app/helpers/photos_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/profile_helper.rb b/app/helpers/profile_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/provinces_helper.rb b/app/helpers/provinces_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/ptags_helper.rb b/app/helpers/ptags_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/remote_link_renderer.rb b/app/helpers/remote_link_renderer.rb old mode 100644 new mode 100755 diff --git a/app/helpers/root_helper.rb b/app/helpers/root_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/sessions_helper.rb b/app/helpers/sessions_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/statuses_helper.rb b/app/helpers/statuses_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/tagged_blogs_helper.rb b/app/helpers/tagged_blogs_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/tagged_photos_helper.rb b/app/helpers/tagged_photos_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/user_albums_helper.rb b/app/helpers/user_albums_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/user_blogs_helper.rb b/app/helpers/user_blogs_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/user_characters_helper.rb b/app/helpers/user_characters_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/user_statuses_helper.rb b/app/helpers/user_statuses_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/user_wall_messages_helper.rb b/app/helpers/user_wall_messages_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/validator_helper.rb b/app/helpers/validator_helper.rb old mode 100644 new mode 100755 diff --git a/app/helpers/wall_messages_helper.rb b/app/helpers/wall_messages_helper.rb old mode 100644 new mode 100755 diff --git a/app/models/album.rb b/app/models/album.rb old mode 100644 new mode 100755 diff --git a/app/models/bcomment.rb b/app/models/bcomment.rb old mode 100644 new mode 100755 diff --git a/app/models/bdig.rb b/app/models/bdig.rb old mode 100644 new mode 100755 diff --git a/app/models/blog.rb b/app/models/blog.rb old mode 100644 new mode 100755 diff --git a/app/models/btag.rb b/app/models/btag.rb old mode 100644 new mode 100755 diff --git a/app/models/city.rb b/app/models/city.rb old mode 100644 new mode 100755 diff --git a/app/models/country.rb b/app/models/country.rb old mode 100644 new mode 100755 diff --git a/app/models/event_wall_message.rb b/app/models/event_wall_message.rb new file mode 100644 index 0000000..d9daf4d --- /dev/null +++ b/app/models/event_wall_message.rb @@ -0,0 +1,2 @@ +class EventWallMessage < ActiveRecord::Base +end diff --git a/app/models/friendship.rb b/app/models/friendship.rb old mode 100644 new mode 100755 diff --git a/app/models/game.rb b/app/models/game.rb old mode 100644 new mode 100755 diff --git a/app/models/game_area.rb b/app/models/game_area.rb old mode 100644 new mode 100755 diff --git a/app/models/game_character.rb b/app/models/game_character.rb old mode 100644 new mode 100755 diff --git a/app/models/game_profession.rb b/app/models/game_profession.rb old mode 100644 new mode 100755 diff --git a/app/models/game_race.rb b/app/models/game_race.rb old mode 100644 new mode 100755 diff --git a/app/models/game_server.rb b/app/models/game_server.rb old mode 100644 new mode 100755 diff --git a/app/models/icon.rb b/app/models/icon.rb old mode 100644 new mode 100755 diff --git a/app/models/mail.rb b/app/models/mail.rb old mode 100644 new mode 100755 diff --git a/app/models/page.rb b/app/models/page.rb old mode 100644 new mode 100755 diff --git a/app/models/pcomment.rb b/app/models/pcomment.rb old mode 100644 new mode 100755 diff --git a/app/models/pdig.rb b/app/models/pdig.rb old mode 100644 new mode 100755 diff --git a/app/models/permission.rb b/app/models/permission.rb old mode 100644 new mode 100755 diff --git a/app/models/photo.rb b/app/models/photo.rb old mode 100644 new mode 100755 diff --git a/app/models/photo_observer.rb b/app/models/photo_observer.rb old mode 100644 new mode 100755 diff --git a/app/models/province.rb b/app/models/province.rb old mode 100644 new mode 100755 diff --git a/app/models/ptag.rb b/app/models/ptag.rb old mode 100644 new mode 100755 diff --git a/app/models/role.rb b/app/models/role.rb old mode 100644 new mode 100755 diff --git a/app/models/status.rb b/app/models/status.rb old mode 100644 new mode 100755 diff --git a/app/models/user.rb b/app/models/user.rb old mode 100644 new mode 100755 diff --git a/app/models/user_mailer.rb b/app/models/user_mailer.rb old mode 100644 new mode 100755 diff --git a/app/models/user_observer.rb b/app/models/user_observer.rb old mode 100644 new mode 100755 diff --git a/app/models/validation_image.rb b/app/models/validation_image.rb old mode 100644 new mode 100755 diff --git a/app/models/wall_message.rb b/app/models/wall_message.rb old mode 100644 new mode 100755 diff --git a/app/views/admin/pages/edit.html.erb b/app/views/admin/pages/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/admin/pages/index.html.erb b/app/views/admin/pages/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/admin/pages/new.html.erb b/app/views/admin/pages/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/admin/pages/show.html.erb b/app/views/admin/pages/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_feeds/index.html.erb b/app/views/album_feeds/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/_edition.html.erb b/app/views/album_photos/_edition.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/_friends.html.erb b/app/views/album_photos/_friends.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/_pcomment.html.erb b/app/views/album_photos/_pcomment.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/_photo_menu.html.erb b/app/views/album_photos/_photo_menu.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/_photo_upload_form.html.erb b/app/views/album_photos/_photo_upload_form.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/_ptag.html.erb b/app/views/album_photos/_ptag.html.erb old mode 100644 new mode 100755 index 5f9ac3f..d6b2a87 --- a/app/views/album_photos/_ptag.html.erb +++ b/app/views/album_photos/_ptag.html.erb @@ -1,4 +1,4 @@ -<span id=<%= "tag_#{ptag.id}" %> tag_id=<%= ptag.id %> x=<%= ptag.x %> y=<%= ptag.y %> width=<%= ptag.width %> height=<%= ptag.height %>> +<span id=<%= "tag_#{ptag.id}" %> name=<%= ptag.tagged_user.login %> tag_id=<%= ptag.id %> x=<%= ptag.x %> y=<%= ptag.y %> width=<%= ptag.width %> height=<%= ptag.height %>> <%= link_to ptag.tagged_user.login, user_url(ptag.tagged_user), :onmouseover => "photo_tag.show_tag(#{ptag.id})", :onmouseout => "photo_tag.hide_tag(#{ptag.id})" %> <%= link_to_remote "(delete)", :complete => "photo_tag.delete(#{ptag.id})", :url => photo_tag_url(ptag.photo, ptag), :method => :delete %> </span> diff --git a/app/views/album_photos/confirm_cover.html.erb b/app/views/album_photos/confirm_cover.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/confirm_destroy.html.erb b/app/views/album_photos/confirm_destroy.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/edit.html.erb b/app/views/album_photos/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/edit_multiple.html.erb b/app/views/album_photos/edit_multiple.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/new.html.erb b/app/views/album_photos/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/album_photos/show.html.erb b/app/views/album_photos/show.html.erb old mode 100644 new mode 100755 index 4670e07..b7feeb3 --- a/app/views/album_photos/show.html.erb +++ b/app/views/album_photos/show.html.erb @@ -1,55 +1,56 @@ <%= javascript_include_tag 'photo.js' %> <%= stylesheet_link_tag 'photo_tag.css' %> <% ret = @album.next_prev_photo(@photo) @cur_photo_idx = ret[2] @next_photo = ret[0] @prev_photo = ret[1] %> <p> <%= "#{@cur_photo_idx} of #{@album.photos.count} photos" %> | <%= link_to 'back to album', user_album_url(@user, @album) %> | <%= link_to 'my albums', user_albums_url(@user)%> </p> <p> <%= link_to 'prev', album_photo_url(@album, @prev_photo) %> | <%= link_to 'next', album_photo_url(@album, @next_photo) %> </p> +<div align='center'> +<%= image_tag @photo.public_filename, :id => "photo_#{@photo.id}" %> +</div> + <div id='complete_panel' style="display:none"> After you finish tagging, close this<%= button_to_function 'complete', "photo_tag.complete();" %> </div> -<p align='center'> -<%= image_tag @photo.public_filename, :id => "photo_#{@photo.id}" %> -</p> notation: <%= @photo.notation %> <div id='photo_tags'> Tags: <%= render :partial => 'ptag', :collection => @photo.tags %> </div> <%= render :partial => 'photo_menu' %> <div> <%= link_to_function "Comment", "$('comment_content').focus();" %>(<%= label_tag 'nil', "#{@photo.comments.count}", :id => 'comments_count' %>) | <%= link_to_remote "Dig", :url => photo_digs_url(:photo_id => @photo) %>(<%= label_tag nil, "#{@photo.digs.count}", :id => 'digs_count' %>) </div> <hr/> <div id='comments'> <%= render :partial => 'pcomment', :collection => @photo.comments %> </div> <% form_remote_for :comment, :position => :bottom, :update => 'comments', :complete => "$('comment_content').value='';", :url => photo_comments_url(:photo_id => @photo) do |form| %> <p><%= form.text_area 'content', :cols => 70, :rows => 6 %></p> <p><%= form.label "whisper?" %><%= form.check_box 'whisper' %></p> <%= form.submit 'comment' %> <% end %> <%= javascript_tag "var photo_tag = new PhotoTag(#{@photo.id}, #{@user.id});" %> diff --git a/app/views/albums/edit.html.erb b/app/views/albums/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/albums/index.html.erb b/app/views/albums/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/albums/new.html.erb b/app/views/albums/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/albums/show.html.erb b/app/views/albums/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/basic_info/_show.html.erb b/app/views/basic_info/_show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/basic_info/edit.html.erb b/app/views/basic_info/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/bcomments/edit.html.erb b/app/views/bcomments/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/bcomments/index.html.erb b/app/views/bcomments/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/bcomments/new.html.erb b/app/views/bcomments/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/bcomments/show.html.erb b/app/views/bcomments/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/bdigs/edit.html.erb b/app/views/bdigs/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/bdigs/index.html.erb b/app/views/bdigs/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/bdigs/new.html.erb b/app/views/bdigs/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/bdigs/show.html.erb b/app/views/bdigs/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blog_comments/create.html.erb b/app/views/blog_comments/create.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blog_comments/destroy.html.erb b/app/views/blog_comments/destroy.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blog_feeds/index.html.erb b/app/views/blog_feeds/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blog_tags/create.html.erb b/app/views/blog_tags/create.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blog_tags/destroy.html.erb b/app/views/blog_tags/destroy.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blogs/edit.html.erb b/app/views/blogs/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blogs/index.html.erb b/app/views/blogs/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blogs/new.html.erb b/app/views/blogs/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/blogs/show.html.erb b/app/views/blogs/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/btags/edit.html.erb b/app/views/btags/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/btags/index.html.erb b/app/views/btags/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/btags/new.html.erb b/app/views/btags/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/btags/show.html.erb b/app/views/btags/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/cities/edit.html.erb b/app/views/cities/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/cities/index.html.erb b/app/views/cities/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/cities/new.html.erb b/app/views/cities/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/cities/show.html.erb b/app/views/cities/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/contact_info/_show.html.erb b/app/views/contact_info/_show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/contact_info/edit.html.erb b/app/views/contact_info/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/countries/edit.html.erb b/app/views/countries/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/countries/index.html.erb b/app/views/countries/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/countries/new.html.erb b/app/views/countries/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/countries/show.html.erb b/app/views/countries/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/friends/_friend_menu.html.erb b/app/views/friends/_friend_menu.html.erb old mode 100644 new mode 100755 diff --git a/app/views/friends/_friends.html.erb b/app/views/friends/_friends.html.erb old mode 100644 new mode 100755 diff --git a/app/views/friends/index.html.erb b/app/views/friends/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/friendships/edit.html.erb b/app/views/friendships/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/friendships/index.html.erb b/app/views/friendships/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/friendships/new.html.erb b/app/views/friendships/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/friendships/show.html.erb b/app/views/friendships/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_areas/edit.html.erb b/app/views/game_areas/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_areas/index.html.erb b/app/views/game_areas/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_areas/new.html.erb b/app/views/game_areas/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_areas/show.html.erb b/app/views/game_areas/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_characters/_character.html.erb b/app/views/game_characters/_character.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_characters/edit.html.erb b/app/views/game_characters/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_characters/edit_new.html.erb b/app/views/game_characters/edit_new.html.erb old mode 100644 new mode 100755 index ec11392..c71284d --- a/app/views/game_characters/edit_new.html.erb +++ b/app/views/game_characters/edit_new.html.erb @@ -1,59 +1,60 @@ <h2> Edit Game Character </h2> <% game_array = [['---', '---']] %> <% @games.each { |game| game_array << [game.name, game.id] } %> <% server_array = [['---', '---']] %> <% @servers.each { |server| server_array << [server.name, server.id] } %> <% unless @game.no_areas %> <% area_array = [['---','---']] %> <% @areas.each { |area| area_array << [area.name, area.id] } %> <% end %> <% race_array = [['---', '---']] %> <% @races.each { |race| race_array << [race.name, race.id] } %> <% profession_array = [['---', '---']] %> <% @professions.each { |profession| profession_array << [profession.name, profession.id] } %> +<% form_for :character, @game_character, :html => {:id => 'character_form'} do |f| %> <div> <%= label 'game_id', "Game Name: " %> - <%= select_tag 'game_id', options_for_select(game_array, @game_character.game_id), :onchange => "validate_game_id(this.value)"%> + <%= select_tag 'character[game_id]', options_for_select(game_array, @game_character.game_id), :onchange => "validate_game_id(this.value)"%> <div id='game_id_info'></div> </div> <div> <%= label '', "Character ID: " %> - <%= text_field_tag 'name', @game_character.name, :size => 10, :onfocus => "show_name_requirement()", :onblur => "validate_name(this.value)" %> + <%= f.text_field 'name', :size => 10, :onfocus => "show_name_requirement()", :onblur => "validate_name(this.value)" %> <div id='name_info'></div> </div> <div> <%= label_tag '', "Character level: " %> - <%= text_field_tag 'level', @game_character.level, :size => 10, :onfocus => "show_level_requirement()", :onblur => "validate_level(this.value)" %> + <%= f.text_field 'level', :size => 10, :onfocus => "show_level_requirement()", :onblur => "validate_level(this.value)" %> <div id='level_info'></div> </div> <div id=details> <% unless @game.no_areas %> <div id='areas'> <%= label_tag '', 'Game Area: '%> - <%= select_tag 'area_id', options_for_select(area_array, @game_character.area_id), :onchange => "validate_area_id(this.value)" %> + <%= select_tag 'character[area_id]', options_for_select(area_array, @game_character.area_id), :onchange => "validate_area_id(this.value)" %> <div id='area_id_info'></div> </div> <% end %> <div id='servers'> <%= label_tag '', 'Game Server: '%> - <%= select_tag 'server_id', options_for_select(server_array, @game_character.server_id), :onchange => "validate_server_id(this.value)"%> + <%= select_tag 'character[server_id]', options_for_select(server_array, @game_character.server_id), :onchange => "validate_server_id(this.value)"%> <div id='server_id_info'></div> </div> <div id='races'> <%= label_tag '', 'Game Race: '%> - <%= select_tag 'race_id', options_for_select(race_array, @game_character.race_id), :onchange => "validate_race_id(this.value)" %> + <%= select_tag 'character[race_id]', options_for_select(race_array, @game_character.race_id), :onchange => "validate_race_id(this.value)" %> <div id='race_id_info'></div> </div> <div id='professions'> <%= label_tag '', 'profession: '%> - <%= select_tag 'profession_id', options_for_select(profession_array, @game_character.profession_id), :onchange => "validate_profession_id(this.value)" %> + <%= select_tag 'character[profession_id]', options_for_select(profession_array, @game_character.profession_id), :onchange => "validate_profession_id(this.value)" %> <div id='profession_id_info'></div> </div> </div> - +<% end %> <%= link_to_function 'update', "update_character(#{params[:id]})" %> diff --git a/app/views/game_characters/game_character.html.erb b/app/views/game_characters/game_character.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_characters/index.html.erb b/app/views/game_characters/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_characters/new.html.erb b/app/views/game_characters/new.html.erb old mode 100644 new mode 100755 index d030dbb..b0fccd6 --- a/app/views/game_characters/new.html.erb +++ b/app/views/game_characters/new.html.erb @@ -1,22 +1,24 @@ <h2> New Game Character </h2> +<% form_for :character, :html => {:id => 'character_form'} do |f| %> <div> <%= label 'game_id', "Game Name: " %> <% game_array = [['---', '---']] %> <% @games.each { |game| game_array << [game.name, game.id] } %> - <%= select_tag 'game_id', options_for_select(game_array), :onchange => "validate_game_id(this.value);game_onchange(this.value)"%> + <%= select_tag 'character[game_id]', options_for_select(game_array), :onchange => "validate_game_id(this.value);game_onchange(this.value)"%> <a id='game_id_info'></a> </div> <div> <%= label '', "Character ID: " %> - <%= text_field_tag 'name', '', :size => 10, :onfocus => "show_name_requirement()", :onblur => "validate_name(this.value)" %> + <%= f.text_field 'name', :size => 10, :onfocus => "show_name_requirement()", :onblur => "validate_name(this.value)" %> <div id='name_info'></div> </div> <div> <%= label_tag '', "Character level: " %> - <%= text_field_tag 'level', '', :size => 10, :onfocus => "show_level_requirement()", :onblur => "validate_level(this.value)" %> + <%= f.text_field 'level', :size => 10, :onfocus => "show_level_requirement()", :onblur => "validate_level(this.value)" %> <div id='level_info'></div> </div> <div id=details></div> +<% end %> <%= link_to_function 'complete', "add_character()" %> diff --git a/app/views/game_characters/show.html.erb b/app/views/game_characters/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_professions/edit.html.erb b/app/views/game_professions/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_professions/index.html.erb b/app/views/game_professions/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_professions/new.html.erb b/app/views/game_professions/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_professions/show.html.erb b/app/views/game_professions/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_races/edit.html.erb b/app/views/game_races/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_races/index.html.erb b/app/views/game_races/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_races/new.html.erb b/app/views/game_races/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_races/show.html.erb b/app/views/game_races/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_servers/edit.html.erb b/app/views/game_servers/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_servers/index.html.erb b/app/views/game_servers/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_servers/new.html.erb b/app/views/game_servers/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/game_servers/show.html.erb b/app/views/game_servers/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/games/edit.html.erb b/app/views/games/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/games/index.html.erb b/app/views/games/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/games/new.html.erb b/app/views/games/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/games/show.html.erb b/app/views/games/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/icons/edit.html.erb b/app/views/icons/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/icons/index.html.erb b/app/views/icons/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/icons/new.html.erb b/app/views/icons/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/icons/show.html.erb b/app/views/icons/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/_admin_menu.html.erb b/app/views/layouts/_admin_menu.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/_root_menu.html.erb b/app/views/layouts/_root_menu.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/_user_menus.html.erb b/app/views/layouts/_user_menus.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/admin.html.erb b/app/views/layouts/admin.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/albums.html.erb b/app/views/layouts/albums.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/bcomments.html.erb b/app/views/layouts/bcomments.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/bdigs.html.erb b/app/views/layouts/bdigs.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/blogs.html.erb b/app/views/layouts/blogs.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/btags.html.erb b/app/views/layouts/btags.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/cities.html.erb b/app/views/layouts/cities.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/countries.html.erb b/app/views/layouts/countries.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/friendships.html.erb b/app/views/layouts/friendships.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/game_areas.html.erb b/app/views/layouts/game_areas.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/game_characters.html.erb b/app/views/layouts/game_characters.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/game_professions.html.erb b/app/views/layouts/game_professions.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/game_races.html.erb b/app/views/layouts/game_races.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/game_servers.html.erb b/app/views/layouts/game_servers.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/games.html.erb b/app/views/layouts/games.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/icons.html.erb b/app/views/layouts/icons.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/mails.html.erb b/app/views/layouts/mails.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/pages.html.erb b/app/views/layouts/pages.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/pcomments.html.erb b/app/views/layouts/pcomments.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/pdigs.html.erb b/app/views/layouts/pdigs.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/photos.html.erb b/app/views/layouts/photos.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/provinces.html.erb b/app/views/layouts/provinces.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/ptags.html.erb b/app/views/layouts/ptags.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/root.html.erb b/app/views/layouts/root.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/statuses.html.erb b/app/views/layouts/statuses.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/user.html.erb b/app/views/layouts/user.html.erb old mode 100644 new mode 100755 diff --git a/app/views/layouts/wall_messages.html.erb b/app/views/layouts/wall_messages.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/_friend.html.erb b/app/views/mailboxes/_friend.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/_mail.html.erb b/app/views/mailboxes/_mail.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/_mailbox_menu.html.erb b/app/views/mailboxes/_mailbox_menu.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/_recv_mails.html.erb b/app/views/mailboxes/_recv_mails.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/_sent_mails.html.erb b/app/views/mailboxes/_sent_mails.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/new.html.erb b/app/views/mailboxes/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/recv_index.html.erb b/app/views/mailboxes/recv_index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/sent_index.html.erb b/app/views/mailboxes/sent_index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mailboxes/show.html.erb b/app/views/mailboxes/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mails/edit.html.erb b/app/views/mails/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mails/index.html.erb b/app/views/mails/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mails/new.html.erb b/app/views/mails/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/mails/show.html.erb b/app/views/mails/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/passwords/edit.html.erb b/app/views/passwords/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/passwords/new.html.erb b/app/views/passwords/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/pcomments/edit.html.erb b/app/views/pcomments/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/pcomments/index.html.erb b/app/views/pcomments/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/pcomments/new.html.erb b/app/views/pcomments/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/pcomments/show.html.erb b/app/views/pcomments/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/pdigs/edit.html.erb b/app/views/pdigs/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/pdigs/index.html.erb b/app/views/pdigs/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/pdigs/new.html.erb b/app/views/pdigs/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/pdigs/show.html.erb b/app/views/pdigs/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/personal/_menu.html.erb b/app/views/personal/_menu.html.erb old mode 100644 new mode 100755 diff --git a/app/views/photos/edit.html.erb b/app/views/photos/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/photos/index.html.erb b/app/views/photos/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/photos/new.html.erb b/app/views/photos/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/photos/show.html.erb b/app/views/photos/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/profiles/show.html.erb b/app/views/profiles/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/provinces/edit.html.erb b/app/views/provinces/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/provinces/index.html.erb b/app/views/provinces/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/provinces/new.html.erb b/app/views/provinces/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/provinces/show.html.erb b/app/views/provinces/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/ptags/edit.html.erb b/app/views/ptags/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/ptags/index.html.erb b/app/views/ptags/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/ptags/new.html.erb b/app/views/ptags/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/ptags/show.html.erb b/app/views/ptags/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/root/index.html.erb b/app/views/root/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/statuses/edit.html.erb b/app/views/statuses/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/statuses/index.html.erb b/app/views/statuses/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/statuses/new.html.erb b/app/views/statuses/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/statuses/show.html.erb b/app/views/statuses/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/tagged_blogs/index.html.erb b/app/views/tagged_blogs/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/tagged_photos/index.html.erb b/app/views/tagged_photos/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_albums/_album_menu.html.erb b/app/views/user_albums/_album_menu.html.erb old mode 100644 new mode 100755 index 9589134..b3eb653 --- a/app/views/user_albums/_album_menu.html.erb +++ b/app/views/user_albums/_album_menu.html.erb @@ -1,4 +1,4 @@ <%= link_to "my albums", user_albums_url(@user) %> <%= link_to "friends' albums", :controller => 'album_feeds', :action => 'index', :user_id =>(@user) %> <%= link_to "my tagged photos", :controller => 'tagged_photos', :action => 'index', :user_id => @user %> -<%= link_to "upload photo", new_user_album_url(@user) %> +<%= link_to "upload photo", new_user_album_url(@user), :style => "float:right" %> diff --git a/app/views/user_albums/_albums.html.erb b/app/views/user_albums/_albums.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_albums/_edit_menu.html.erb b/app/views/user_albums/_edit_menu.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_albums/_photos.html.erb b/app/views/user_albums/_photos.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_albums/confirm_destroy.html.erb b/app/views/user_albums/confirm_destroy.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_albums/edit.html.erb b/app/views/user_albums/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_albums/index.html.erb b/app/views/user_albums/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_albums/new.html.erb b/app/views/user_albums/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_albums/show.html.erb b/app/views/user_albums/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_bcomment.html.erb b/app/views/user_blogs/_bcomment.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_blog_menu.html.erb b/app/views/user_blogs/_blog_menu.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_blogs.html.erb b/app/views/user_blogs/_blogs.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_btag.html.erb b/app/views/user_blogs/_btag.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_drafts.html.erb b/app/views/user_blogs/_drafts.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_friends.html.erb b/app/views/user_blogs/_friends.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_friends_list.html.erb b/app/views/user_blogs/_friends_list.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_games_list.html.erb b/app/views/user_blogs/_games_list.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_name_tag.html.erb b/app/views/user_blogs/_name_tag.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/_popup_tag.html.erb b/app/views/user_blogs/_popup_tag.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/blogs_index.html.erb b/app/views/user_blogs/blogs_index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/confirm_destroy.html.erb b/app/views/user_blogs/confirm_destroy.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/create.html.erb b/app/views/user_blogs/create.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/destroy.html.erb b/app/views/user_blogs/destroy.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/drafts_index.html.erb b/app/views/user_blogs/drafts_index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/edit.html.erb b/app/views/user_blogs/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/index.html.erb b/app/views/user_blogs/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/new.html.erb b/app/views/user_blogs/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/show.html.erb b/app/views/user_blogs/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_blogs/update.html.erb b/app/views/user_blogs/update.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_characters/_character.html.erb b/app/views/user_characters/_character.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_characters/confirm_destroy.html.erb b/app/views/user_characters/confirm_destroy.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_characters/edit.html.erb b/app/views/user_characters/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_characters/new.html.erb b/app/views/user_characters/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_mailer/activation.html.erb b/app/views/user_mailer/activation.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_mailer/forgot_password.erb b/app/views/user_mailer/forgot_password.erb old mode 100644 new mode 100755 diff --git a/app/views/user_mailer/reset_password.html.erb b/app/views/user_mailer/reset_password.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_mailer/signup_notification.html.erb b/app/views/user_mailer/signup_notification.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_statuses/create.html.erb b/app/views/user_statuses/create.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_statuses/destroy.html.erb b/app/views/user_statuses/destroy.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_statuses/edit.html.erb b/app/views/user_statuses/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_statuses/index.html.erb b/app/views/user_statuses/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_statuses/new.html.erb b/app/views/user_statuses/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_statuses/show.html.erb b/app/views/user_statuses/show.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_statuses/update.html.erb b/app/views/user_statuses/update.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_wall_messages/_input.html.erb b/app/views/user_wall_messages/_input.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_wall_messages/_wall_message.html.erb b/app/views/user_wall_messages/_wall_message.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_wall_messages/index.html.erb b/app/views/user_wall_messages/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/user_wall_messages/new.html.erb b/app/views/user_wall_messages/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/users/index.html.erb b/app/views/users/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/wall_messages/edit.html.erb b/app/views/wall_messages/edit.html.erb old mode 100644 new mode 100755 diff --git a/app/views/wall_messages/index.html.erb b/app/views/wall_messages/index.html.erb old mode 100644 new mode 100755 diff --git a/app/views/wall_messages/new.html.erb b/app/views/wall_messages/new.html.erb old mode 100644 new mode 100755 diff --git a/app/views/wall_messages/show.html.erb b/app/views/wall_messages/show.html.erb old mode 100644 new mode 100755 diff --git a/config/amazon_s3.yml b/config/amazon_s3.yml old mode 100644 new mode 100755 diff --git a/config/boot.rb b/config/boot.rb old mode 100644 new mode 100755 diff --git a/config/database.yml b/config/database.yml old mode 100644 new mode 100755 index 3ec9566..944db3d --- a/config/database.yml +++ b/config/database.yml @@ -1,48 +1,48 @@ # MySQL. Versions 4.1 and 5.0 are recommended. # # Install the MySQL driver: # gem install mysql # On Mac OS X: # sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql # On Mac OS X Leopard: # sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config # This sets the ARCHFLAGS environment variable to your native architecture # On Windows: # gem install mysql # Choose the win32 build. # Install MySQL and put its /bin directory on your path. # # And be sure to use new-style password hashing: # http://dev.mysql.com/doc/refman/5.0/en/old-client.html development: adapter: mysql encoding: utf8 reconnect: false database: dayday3_development pool: 5 username: root - password: 123456 + password: 20041065 socket: /var/run/mysqld/mysqld.sock # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: mysql encoding: utf8 reconnect: false database: dayday3_test pool: 5 username: root - password: 123456 + password: socket: /var/run/mysqld/mysqld.sock production: adapter: mysql encoding: utf8 reconnect: false database: dayday3_production pool: 5 username: root - password: 123456 + password: socket: /var/run/mysqld/mysqld.sock diff --git a/config/environment.rb b/config/environment.rb old mode 100644 new mode 100755 index 403b407..d906a4c --- a/config/environment.rb +++ b/config/environment.rb @@ -1,49 +1,49 @@ # Be sure to restart your server when you modify this file # Specifies gem version of Rails to use when vendor/rails is not present RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION # Bootstrap the Rails environment, frameworks, and default configuration require File.join(File.dirname(__FILE__), 'boot') require 'diggable' require 'taggable' require 'commentable' require 'migration_helper' Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Activate observers that should always be running # config.active_record.observers = :cacher, :garbage_collector, :forum_observer # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de - #config.active_record.observers = [:user_observer, :photo_observer] + config.active_record.observers = [:user_observer, :photo_observer] end require 'will_paginate' diff --git a/config/environments/development.rb b/config/environments/development.rb old mode 100644 new mode 100755 diff --git a/config/environments/production.rb b/config/environments/production.rb old mode 100644 new mode 100755 diff --git a/config/environments/test.rb b/config/environments/test.rb old mode 100644 new mode 100755 diff --git a/config/initializers/backtrace_silencers.rb b/config/initializers/backtrace_silencers.rb old mode 100644 new mode 100755 diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb old mode 100644 new mode 100755 diff --git a/config/initializers/mail.rb b/config/initializers/mail.rb old mode 100644 new mode 100755 diff --git a/config/initializers/mime_types.rb b/config/initializers/mime_types.rb old mode 100644 new mode 100755 diff --git a/config/initializers/new_rails_defaults.rb b/config/initializers/new_rails_defaults.rb old mode 100644 new mode 100755 diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb old mode 100644 new mode 100755 diff --git a/config/locales/en.yml b/config/locales/en.yml old mode 100644 new mode 100755 diff --git a/config/rackspace_cloudfiles.yml b/config/rackspace_cloudfiles.yml old mode 100644 new mode 100755 diff --git a/config/routes.rb b/config/routes.rb old mode 100644 new mode 100755 diff --git a/config/routes.rb.backup b/config/routes.rb.backup old mode 100644 new mode 100755 diff --git a/db/migrate/20090809142545_create_pages.rb b/db/migrate/20090809142545_create_pages.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090809145132_create_users.rb b/db/migrate/20090809145132_create_users.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090809145941_create_permissions.rb b/db/migrate/20090809145941_create_permissions.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090809145949_create_roles.rb b/db/migrate/20090809145949_create_roles.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090809150047_add_admin.rb b/db/migrate/20090809150047_add_admin.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090809161923_add_user.rb b/db/migrate/20090809161923_add_user.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090809181728_create_statuses.rb b/db/migrate/20090809181728_create_statuses.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810045504_create_blogs.rb b/db/migrate/20090810045504_create_blogs.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810053845_create_bcomments.rb b/db/migrate/20090810053845_create_bcomments.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810061507_create_games.rb b/db/migrate/20090810061507_create_games.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810061539_create_game_areas.rb b/db/migrate/20090810061539_create_game_areas.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810061726_create_game_servers.rb b/db/migrate/20090810061726_create_game_servers.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810061840_create_game_professions.rb b/db/migrate/20090810061840_create_game_professions.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810061931_create_game_races.rb b/db/migrate/20090810061931_create_game_races.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810062110_create_game_characters.rb b/db/migrate/20090810062110_create_game_characters.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810062541_add_characters.rb b/db/migrate/20090810062541_add_characters.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810063924_create_btags.rb b/db/migrate/20090810063924_create_btags.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810065551_create_friendships.rb b/db/migrate/20090810065551_create_friendships.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810065714_create_albums.rb b/db/migrate/20090810065714_create_albums.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810070045_create_photos.rb b/db/migrate/20090810070045_create_photos.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810070158_create_bdigs.rb b/db/migrate/20090810070158_create_bdigs.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810070251_create_pcomments.rb b/db/migrate/20090810070251_create_pcomments.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810070335_create_pdigs.rb b/db/migrate/20090810070335_create_pdigs.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810070440_create_ptags.rb b/db/migrate/20090810070440_create_ptags.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810070804_create_icons.rb b/db/migrate/20090810070804_create_icons.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810081501_add_blog.rb b/db/migrate/20090810081501_add_blog.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810133544_add_friends.rb b/db/migrate/20090810133544_add_friends.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810155959_create_mails.rb b/db/migrate/20090810155959_create_mails.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090810160345_add_mails.rb b/db/migrate/20090810160345_add_mails.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090811064247_create_wall_messages.rb b/db/migrate/20090811064247_create_wall_messages.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090811064343_add_wall_messages.rb b/db/migrate/20090811064343_add_wall_messages.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090811092810_add_drafts.rb b/db/migrate/20090811092810_add_drafts.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090812060413_add_albums.rb b/db/migrate/20090812060413_add_albums.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090816174043_create_countries.rb b/db/migrate/20090816174043_create_countries.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090816174055_create_provinces.rb b/db/migrate/20090816174055_create_provinces.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090816174114_create_cities.rb b/db/migrate/20090816174114_create_cities.rb old mode 100644 new mode 100755 diff --git a/db/migrate/20090818030745_create_event_wall_messages.rb b/db/migrate/20090818030745_create_event_wall_messages.rb new file mode 100644 index 0000000..9e8c370 --- /dev/null +++ b/db/migrate/20090818030745_create_event_wall_messages.rb @@ -0,0 +1,16 @@ +class CreateEventWallMessages < ActiveRecord::Migration + def self.up + create_table :event_wall_messages do |t| + t.integer :activity_id + t.integer :poster_id + t.integer :receiver_id + t.text :content + t.boolean :whisper, :default => false + t.timestamps + end + end + + def self.down + drop_table :event_wall_messages + end +end diff --git a/db/schema.rb b/db/schema.rb old mode 100644 new mode 100755 diff --git a/doc/README_FOR_APP b/doc/README_FOR_APP old mode 100644 new mode 100755 diff --git a/lib/authenticated_system.rb b/lib/authenticated_system.rb old mode 100644 new mode 100755 diff --git a/lib/authenticated_test_helper.rb b/lib/authenticated_test_helper.rb old mode 100644 new mode 100755 diff --git a/lib/commentable.rb b/lib/commentable.rb old mode 100644 new mode 100755 diff --git a/lib/diggable.rb b/lib/diggable.rb old mode 100644 new mode 100755 diff --git a/lib/migration_helper.rb b/lib/migration_helper.rb old mode 100644 new mode 100755 diff --git a/lib/model_helper.rb b/lib/model_helper.rb old mode 100644 new mode 100755 diff --git a/lib/taggable.rb b/lib/taggable.rb old mode 100644 new mode 100755 diff --git a/public/404.html b/public/404.html old mode 100644 new mode 100755 diff --git a/public/422.html b/public/422.html old mode 100644 new mode 100755 diff --git a/public/500.html b/public/500.html old mode 100644 new mode 100755 diff --git a/public/blog.js b/public/blog.js old mode 100644 new mode 100755 diff --git a/public/favicon.ico b/public/favicon.ico old mode 100644 new mode 100755 diff --git a/public/icons/0000/0001/1.jpg b/public/icons/0000/0001/1.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0001/1_large.jpg b/public/icons/0000/0001/1_large.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0001/1_medium.jpg b/public/icons/0000/0001/1_medium.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0001/1_small.jpg b/public/icons/0000/0001/1_small.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0005/1.jpg b/public/icons/0000/0005/1.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0005/12.jpg b/public/icons/0000/0005/12.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0005/12_large.jpg b/public/icons/0000/0005/12_large.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0005/12_medium.jpg b/public/icons/0000/0005/12_medium.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0005/12_small.jpg b/public/icons/0000/0005/12_small.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0005/1_large.jpg b/public/icons/0000/0005/1_large.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0005/1_medium.jpg b/public/icons/0000/0005/1_medium.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0005/1_small.jpg b/public/icons/0000/0005/1_small.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0009/14.jpg b/public/icons/0000/0009/14.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0009/14_large.jpg b/public/icons/0000/0009/14_large.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0009/14_medium.jpg b/public/icons/0000/0009/14_medium.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0009/14_small.jpg b/public/icons/0000/0009/14_small.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0009/2.jpg b/public/icons/0000/0009/2.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0009/2_large.jpg b/public/icons/0000/0009/2_large.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0009/2_medium.jpg b/public/icons/0000/0009/2_medium.jpg old mode 100644 new mode 100755 diff --git a/public/icons/0000/0009/2_small.jpg b/public/icons/0000/0009/2_small.jpg old mode 100644 new mode 100755 diff --git a/public/images/b.png b/public/images/b.png old mode 100644 new mode 100755 diff --git a/public/images/bl.png b/public/images/bl.png old mode 100644 new mode 100755 diff --git a/public/images/br.png b/public/images/br.png old mode 100644 new mode 100755 diff --git a/public/images/default.png b/public/images/default.png old mode 100644 new mode 100755 diff --git a/public/images/default_cover.jpg b/public/images/default_cover.jpg old mode 100644 new mode 100755 diff --git a/public/images/default_cover_large.jpg b/public/images/default_cover_large.jpg old mode 100644 new mode 100755 diff --git a/public/images/default_cover_medium.jpg b/public/images/default_cover_medium.jpg old mode 100644 new mode 100755 diff --git a/public/images/default_cover_small.jpg b/public/images/default_cover_small.jpg old mode 100644 new mode 100755 diff --git a/public/images/default_large.png b/public/images/default_large.png old mode 100644 new mode 100755 diff --git a/public/images/default_medium.png b/public/images/default_medium.png old mode 100644 new mode 100755 diff --git a/public/images/default_small.png b/public/images/default_small.png old mode 100644 new mode 100755 diff --git a/public/images/rails.png b/public/images/rails.png old mode 100644 new mode 100755 diff --git a/public/images/tl.png b/public/images/tl.png old mode 100644 new mode 100755 diff --git a/public/images/tr.png b/public/images/tr.png old mode 100644 new mode 100755 diff --git a/public/javascripts/application.js b/public/javascripts/application.js old mode 100644 new mode 100755 diff --git a/public/javascripts/blog.js b/public/javascripts/blog.js old mode 100644 new mode 100755 diff --git a/public/javascripts/controls.js b/public/javascripts/controls.js old mode 100644 new mode 100755 diff --git a/public/javascripts/dragdrop.js b/public/javascripts/dragdrop.js old mode 100644 new mode 100755 diff --git a/public/javascripts/effects.js b/public/javascripts/effects.js old mode 100644 new mode 100755 diff --git a/public/javascripts/facebox.js b/public/javascripts/facebox.js old mode 100644 new mode 100755 diff --git a/public/javascripts/mailbox.js b/public/javascripts/mailbox.js old mode 100644 new mode 100755 diff --git a/public/javascripts/photo.js b/public/javascripts/photo.js old mode 100644 new mode 100755 index ceeb451..c98c0e4 --- a/public/javascripts/photo.js +++ b/public/javascripts/photo.js @@ -1,811 +1,917 @@ PhotoTag = Class.create({ /* * initialize */ initialize: function(photo_id, user_id, options){ // save user id, photo element and its position this.user_id = user_id; this.photo_id = photo_id; this.photo = $('photo_' + this.photo_id); this.pos = this.photo.positionedOffset(); // save complete panel this.complete_panel = $('complete_panel'); // log, this is only used for debugging this.log = $('log'); // get the area where tags are shown this.tags_area = $('photo_tags'); // photo tag options this.options = Object.extend({ square_size: '15%', square_class: 'square-class', tag_input_class: 'tag-input', tag_class: 'tag_class', friends_list_class: 'friends_list_class', lang: { // name for two buttons add: 'Add', close: 'Close' }, }, options || {}); // calculate square size this.square_size = this.photo.getWidth() * this.options.square_size.sub('%', '', 1)/100; this.friends = []; // set window resize handler // reset photo position if resize event happens Event.observe(document.onresize? document : window, 'resize', function(){ this.pos = this.photo.positionedOffset(); }.bind(this)); // get all current tags this.ptags = new Hash(); var ptags = $('photo_tags').childElements(); var length = ptags.length; for(var i=0;i<length;i++){ this.ptags.set(ptags[i].readAttribute('tag_id'), ptags[i]); } // set photo mouseover event - this.photo.observe('mouseover', function(event){ - + this.photo.observe('mousemove', function(event){ + this.show_nearest_tag_with_name(event); }.bind(this)); }, /* * add info to log * this function is only used for debugging */ add_log: function(str){ - this.log.innerHTML += (str + '<br/>'); + this.log.innerHTML += (str+ ' '); }, /* * init: begin tagging */ init: function(){ // show complete panel this.complete_panel.show(); // I dont know if this field is needed, // because sometimes mouse up event would happen two times( i dont know why) // this would cause "new draggable()" called twice this.draggable_count = 0; // if square and tag input exist, we dont need to create them // just hide them if(this.square && this.tag_input){ this.hide_square(); this.hide_tag_input(); }else{ // create square and input box this.create_square(); this.create_tag_input(); } + // stop listening to mousemove event on photo + this.photo.stopObserving('mousemove'); + // add onClick event to photo Event.observe(this.photo, 'click', function(event){ this.set_square(event); }.bind(this)); }, /* * create square * this function just creates square element but doesn't set its position */ create_square: function(){ // create square this.square = new Element('div', {className: this.options.square_class}); // set square style this.square.setStyle({ position: 'absolute', left: '0px', top: '0px', height: this.square_size + 'px', width: this.square_size + 'px'}); // create leftup corner this.create_leftup_corner(); // create leftdown corner this.create_leftdown_corner(); // create rightup corner this.create_rightup_corner(); // create rightdown corner this.create_rightdown_corner(); // hide square and add it to this.hide_square(); document.body.appendChild(this.square); }, /* * create leftup corner of square * this function just creates square element but doesn't set its position */ create_leftup_corner: function(){ // create div element this.leftup_corner = new Element('div', {id: 'leftup-corner'}); this.square.appendChild(this.leftup_corner); // set mouse over listener to change cursor icon this.leftup_corner.observe('mouseover', function(event){ document.body.setStyle({cursor: 'nw-resize'}); }); // set mouse out listener to change cursor icon to default one this.leftup_corner.observe('mouseout', function(event){ document.body.setStyle({cursor: 'default'}); }); // set mouse down listener to start resize this.leftup_corner.observe('mousedown', function(event){ // save original position and size this.start_x = event.pointerX(); this.start_y = event.pointerY(); this.original_height = this.square.getHeight(); this.original_width = this.square.getWidth(); // disable dragging while resizing this.disable_drag(); // start listening for mouse move event document.body.observe('mousemove', function(event){ var width = this.square.getWidth(); var height = this.square.getHeight(); // recording end position and make sure that it stays in photo var xy = this.stay_in_photo(event.pointerX(), event.pointerY()); var x = xy[0]; var y = xy[1]; // resize square this.square.setStyle({ left: x + 'px', top: y + 'px', width: (this.original_width + this.start_x - x) + 'px', height: (this.original_height + this.start_y - y) + 'px', }); // reset positions of 4 corners this.set_corners(); // reset position of tag input this.set_tag_input(); }.bind(this)); document.body.observe('mouseup', function(event){ this.enable_drag(); Event.stopObserving(document.body, 'mousemove'); Event.stopObserving(document.body, 'mouseup'); }.bind(this)); }.bind(this)); }, /* * create leftdown corner of square * this function just creates square element but doesn't set its position */ create_leftdown_corner: function(){ // create div element this.leftdown_corner = new Element('div', {id: 'leftdown-corner'}); this.square.appendChild(this.leftdown_corner); // set mouse over listener to change cursor icon this.leftdown_corner.observe('mouseover', function(event){ document.body.setStyle({cursor: 'sw-resize'}); }); // set mouse out listener to change cursor icon to default one this.leftdown_corner.observe('mouseout', function(event){ document.body.setStyle({cursor: 'default'}); }); // set mouse down listener to start resize this.leftdown_corner.observe('mousedown', function(event){ // save original position and size this.start_x = event.pointerX(); this.start_y = event.pointerY(); this.original_height = this.square.getHeight(); this.original_width = this.square.getWidth(); // disable dragging while resizing this.disable_drag(); // start listening for mouse move event document.body.observe('mousemove', function(event){ var width = this.square.getWidth(); var height = this.square.getHeight(); // recording end position and make sure that it stays in photo var xy = this.stay_in_photo(event.pointerX(), event.pointerY() - height); var x = xy[0]; var y = xy[1] + height;; // resize square this.square.setStyle({ left: x + 'px', width: (this.original_width + this.start_x - x) + 'px', height: (this.original_height + y - this.start_y) + 'px', }); // reset positions of 4 corners this.set_corners(); // reset position of tag input this.set_tag_input(); }.bind(this)); document.body.observe('mouseup', function(event){ this.enable_drag(); Event.stopObserving(document.body, 'mousemove'); Event.stopObserving(document.body, 'mouseup'); }.bind(this)); }.bind(this)); }, /* * create rightup corner of square * this function just creates square element but doesn't set its position */ create_rightup_corner: function(){ // create div element this.rightup_corner = new Element('div', {id: 'rightup-corner'}); this.square.appendChild(this.rightup_corner); // set mouse over listener to change cursor icon this.rightup_corner.observe('mouseover', function(event){ document.body.setStyle({cursor: 'ne-resize'}); }); // set mouse out listener to change cursor icon to default one this.rightup_corner.observe('mouseout', function(event){ document.body.setStyle({cursor: 'default'}); }); // set mouse down listener to start resize this.rightup_corner.observe('mousedown', function(event){ // save original position and size this.start_x = event.pointerX(); this.start_y = event.pointerY(); this.original_height = this.square.getHeight(); this.original_width = this.square.getWidth(); // disable dragging while resizing this.disable_drag(); // start listening for mouse move event document.body.observe('mousemove', function(event){ var width = this.square.getWidth(); var height = this.square.getHeight(); // recording end position and make sure that it stays in photo var xy = this.stay_in_photo(event.pointerX() - width, event.pointerY()); var x = xy[0] + width; var y = xy[1]; // resize square this.square.setStyle({ top: y + 'px', width: (this.original_width + x - this.start_x) + 'px', height: (this.original_height + this.start_y - y) + 'px', }); // reset positions of 4 corners this.set_corners(); // reset position of tag input this.set_tag_input(); }.bind(this)); document.body.observe('mouseup', function(event){ this.enable_drag(); Event.stopObserving(document.body, 'mousemove'); Event.stopObserving(document.body, 'mouseup'); }.bind(this)); }.bind(this)); }, /* * create rightdown corner of square * this function just creates square element but doesn't set its position */ create_rightdown_corner: function(){ // create div element this.rightdown_corner = new Element('div', {id: 'rightdown-corner'}); this.square.appendChild(this.rightdown_corner); // set mouse over listener to change cursor icon this.rightdown_corner.observe('mouseover', function(event){ document.body.setStyle({cursor: 'se-resize'}); }); // set mouse out listener to change cursor icon to default one this.rightdown_corner.observe('mouseout', function(event){ document.body.setStyle({cursor: 'default'}); }); // set mouse down listener to start resize this.rightdown_corner.observe('mousedown', function(event){ // save original position and size this.start_x = event.pointerX(); this.start_y = event.pointerY(); this.original_height = this.square.getHeight(); this.original_width = this.square.getWidth(); // disable dragging while resizing this.disable_drag(); // start listening for mouse move event document.body.observe('mousemove', function(event){ var width = this.square.getWidth(); var height = this.square.getHeight(); // recording end position and make sure that it stays in photo var xy = this.stay_in_photo(event.pointerX() - width, event.pointerY() - height); var x = xy[0] + width; var y = xy[1] + height; // resize square this.square.setStyle({ width: (this.original_width + x - this.start_x) + 'px', height: (this.original_height + y - this.start_y) + 'px', }); // reset positions of 4 corners this.set_corners(); // reset position of tag input this.set_tag_input(); }.bind(this)); document.body.observe('mouseup', function(event){ this.enable_drag(); Event.stopObserving(document.body, 'mousemove'); Event.stopObserving(document.body, 'mouseup'); }.bind(this)); }.bind(this)); }, /* * hide square */ hide_square: function(){ this.square.hide(); }, /* * show square */ show_square: function(){ this.square.show(); }, /* * hide tag input */ hide_tag_input: function(){ this.inner_textfield.value = ''; this.tag_input.hide(); }, /* * show tag input */ show_tag_input: function(){ this.tag_input.show(); this.inner_textfield.focus(); }, /* * this function guarantees that the square stays in photo area * take care when invoking this function: (x, y) is (left, top) of square * thus do the convertion before invoking this function */ stay_in_photo: function(x, y){ // lb: left bound, rb: right bound, ub: upper bound, bb: lower bound var lb = this.pos.left - this.square.getWidth()/2; var rb = this.pos.left + this.photo.getWidth() - this.square.getWidth()/2; var ub = this.pos.top - this.square.getHeight()/2; var bb = this.pos.top + this.photo.getHeight() - this.square.getHeight()/2; // make sure the square stays in photo area if(x < lb) x = lb; if(x > rb) x = rb; if(y < ub) y = ub; if(y > bb) y = bb; return [x,y]; }, /* * enable draggable */ enable_drag: function(){ // if there is no draggable object if(this.draggable_count == 0){ this.draggable_count += 1; this.draggable = new Draggable(this.square, { snap: function(x, y, draggable){ var xy = this.stay_in_photo(x, y); this.square.setStyle({ left: xy[0] + 'px', top: xy[1] + 'px' }); this.set_tag_input(); return xy; }.bind(this) }); } }, /* * disable draggable */ disable_drag: function(){ // if there is one draggable object if(this.draggable_count == 1){ this.draggable.destroy(); this.draggable_count -= 1; } }, /* * create tag input but not show it * this function just creates tag input but doesn't set its position * html code looks like: * <div> * <div> hidden text field which stores tagged user id </div> * <div> * Input your friend: <br/> * <text_field> * </div> * <div> friend list </div> * <div> 2 buttons </div> * </div> */ create_tag_input: function(){ // create tag input this.tag_input = new Element('div', {className: this.options.tag_input_class}); this.tag_input_hidden = new Element('div'); this.hidden_textfield = new Element('input', {type: 'text', id: 'tagged_user_id'}); this.tag_input_top = new Element('div'); this.label = new Element('label').update('Input your friend here:<br/>'); this.inner_textfield = new Element('input', {type: 'text', id: 'tagged_user_name'}); this.friend_list = new Element('div'); this.tag_input_bot = new Element('div'); - //this.confirm_button = new Element('button').update('confirm'); this.cancel_button = new Element('button').update('cancel'); this.tag_input_hidden.appendChild(this.hidden_textfield); this.tag_input_top.appendChild(this.label); this.tag_input_top.appendChild(this.inner_textfield); - //this.tag_input_bot.appendChild(this.confirm_button); this.tag_input_bot.appendChild(this.cancel_button); this.tag_input.appendChild(this.tag_input_hidden); this.tag_input.appendChild(this.tag_input_top); this.tag_input.appendChild(this.friend_list); this.tag_input.appendChild(this.tag_input_bot); this.tag_input_hidden.hide(); this.friend_list.setStyle({ height: '200px', overflow: 'auto' }); this.tag_input_top.setStyle({ margin: '10px' }); this.tag_input_bot.setStyle({ margin: '10px', align: 'center' }); this.tag_input.setStyle({ background: 'white' }); // get all friends this.get_friends(); // set button events this.set_button_events(); // set text field observer this.set_textfield_observer(); // hide the element and add it to document.body // hide_tag_input() should be invoked after tag_input.inner_textfield is created this.hide_tag_input(); document.body.appendChild(this.tag_input); }, get_selected_friend_id: function(){ var length = this.friends.length; for(var i=0;i<length;i++){ var friend = this.friends[i]; var checkbox = friend.childElements()[0]; if(checkbox.checked){ checkbox.checked = false; return friend.readAttribute('id'); } } }, /* * get all friends */ get_friends: function(){ new Ajax.Request('/album_photos/friends', { method: 'get', onSuccess: function(transport){ this.friend_list.innerHTML = transport.responseText; var friends = this.friend_list.childElements(); var length = friends.length; for(var i=0;i<length;i++){ var checkbox = friends[i].childElements()[0]; checkbox.observe('click', function(event){ var id = this.get_selected_friend_id(); this.submit_tag(id); }.bind(this)); this.friends.push(friends[i]); } }.bind(this) }); }, /* * set textfield observer */ set_textfield_observer: function(){ new Form.Element.Observer(this.inner_textfield, 1, function(element, value){ var length = this.friends.length; for(var i=0;i<length;i++){ friend = this.friends[i]; if(friend.readAttribute('name').indexOf(value) < 0){ friend.hide(); }else{ friend.show(); } } }.bind(this)); }, /* * set add/close button events */ set_button_events: function(){ this.cancel_button.observe('click', function(event){ this.hide_square(); this.hide_tag_input(); }.bind(this)); }, /* * submit tag */ submit_tag: function(tagged_user_id){ // get square position var left = this.square.positionedOffset().left; var top = this.square.positionedOffset().top; // construct parameters url = '/photos/' + this.photo_id + '/tags?' + 'tag[x]=' + (left - this.pos.left) + '&' + 'tag[y]=' + (top - this.pos.top) + '&' + 'tag[width]=' + this.square.getWidth() + '&' + 'tag[height]=' + this.square.getHeight() + '&' + 'tag[tagged_user_id]=' + tagged_user_id + '&' + 'tag[photo_id]=' + this.photo_id; - // send ajax request to store photo tag new Ajax.Request(url, { method: 'post', onSuccess: function(transport){ this.tags_area.innerHTML += transport.responseText; this.hide_square(); this.hide_tag_input(); var ptags = this.tags_area.childElements(); var length = ptags.length; for(var i=0;i<length;i++){ this.ptags.set(ptags[i].readAttribute('tag_id'), ptags[i]) } }.bind(this) }); }, /* * set the location of square */ set_square: function(event){ // get mouse location var mouse_x = event.pointerX(); var mouse_y = event.pointerY(); // calculate square location var square_top = mouse_y - this.square_size/2; var square_left = mouse_x - this.square_size/2; // pay attention to the orders // first set square position, then 4 corners and tag input // set square location and show it this.square.setStyle({ position: 'absolute', width: this.square_size + 'px', height: this.square_size + 'px', top: square_top + 'px', left: square_left + 'px', zIndex: 4}); // show square this.show_square(); // set 4 corners this.set_corners(); // set tag input this.set_tag_input(); // enable draggable this.enable_drag(); }, /* * set positions of 4 corners */ set_corners: function(){ // get x, y, width, height of square and corner size var width = this.square.getWidth(); var height = this.square.getHeight(); var corner_size = 10; // set position of 4 corners this.leftup_corner.setStyle({ position: 'absolute', backgroundColor: '#000', left: '0px', top: '0px', width: corner_size + 'px', height: corner_size + 'px', zIndex: 4}); this.leftdown_corner.setStyle({ position: 'absolute', backgroundColor: '#000', left: '0px', top: (height - corner_size) + 'px', width: corner_size + 'px', height: corner_size + 'px', zIndex: 4}); this.rightup_corner.setStyle({ position: 'absolute', backgroundColor: '#000', left: (width - corner_size) + 'px', top: '0px', width: corner_size + 'px', height: corner_size + 'px', zIndex: 4}); this.rightdown_corner.setStyle({ position: 'absolute', backgroundColor: '#000', left: (width - corner_size) + 'px', top: (height - corner_size) + 'px', width: corner_size + 'px', height: corner_size + 'px', zIndex: 4}); }, /* * show tag input according to the position of square */ set_tag_input: function(event){ // calculate the position of tag input var top = this.square.positionedOffset().top; var left = this.square.positionedOffset().left + this.square.getWidth() + 10; // set style this.tag_input.setStyle({ position: 'absolute', top: top + 'px', left: left + 'px', zIndex: 4}); // show tag input and set the focus of inner text field this.show_tag_input(); }, /* * delete one tag */ delete: function(tag_id){ + if(!this.ptags.unset(tag_id)) return; + var square = $('square_' + tag_id); var tag_link = $('tag_'+tag_id); + var name = $('name_' + tag_id); - // delete square if(square) square.remove(); - - // delete tag link + if(name) + name.remove(); tag_link.remove(); }, /* * hide one tag */ hide_tag: function(tag_id){ var square = $('square_' + tag_id); if(square) square.hide(); }, + /* + * hide tag with name + */ + hide_tag_with_name: function(tag_id){ + var square = $('square_' + tag_id); + var name = $('name_' + tag_id); + if(square) square.hide(); + if(name) name.hide(); + }, + /* * show one tag */ show_tag: function(tag_id){ var square = $('square_'+tag_id); - // if it's first time we visit this tag, create a new square // otherwise, just show the old square if(square){ square.show(); return; } // calculate x, y, width, height // here, we just save these values as element attributes // rather than connect server var ptag = this.ptags.get(tag_id); if(!ptag) return; var x = ptag.readAttribute('x'); var y = ptag.readAttribute('y'); var width = ptag.readAttribute('width'); var height = ptag.readAttribute('height'); var top = parseInt(y) + this.pos.top; var left = parseInt(x) + this.pos.left; - // create new square square = new Element('div', {className: 'square-class', id: 'square_' + tag_id}); // set square style square.setStyle({ position: 'absolute', width: width + 'px', height: height + 'px', left: left + 'px', top: top + 'px', zIndex: 3}); // append square document.body.appendChild(square); - // add mouseout event to tag link - Event.observe(tag_link, 'mouseout', function(){ - var square = $('square_' + tag_id); - square.hide(); - }); + }, + + /* + * show tag with name next to it + */ + show_tag_with_name: function(tag_id){ + var ptag = this.ptags.get(tag_id); + if(!ptag) return; + + var square = $('square_'+tag_id); + + if(square){ + square.show(); + }else{ + // calculate x, y, width, height + // here, we just save these values as element attributes + // rather than connect server + var x = ptag.readAttribute('x'); + var y = ptag.readAttribute('y'); + var width = ptag.readAttribute('width'); + var height = ptag.readAttribute('height'); + var top = parseInt(y) + this.pos.top; + var left = parseInt(x) + this.pos.left; + + // create new square + square = new Element('div', {className: 'square-class', id: 'square_' + tag_id}); + square.setStyle({ + position: 'absolute', + width: width + 'px', + height: height + 'px', + left: left + 'px', + top: top + 'px', + zIndex: 3}); + + // append square + document.body.appendChild(square); + } + + var name = $('name_' + tag_id); + + if(name){ + name.show(); + }else{ + var left = parseInt(ptag.readAttribute('x')) + parseInt(ptag.readAttribute('width')) + this.pos.left + 10; + var top = parseInt(ptag.readAttribute('y')) + this.pos.top; + + // create new element + name = new Element('div', {id: 'name_' + tag_id}).update(ptag.readAttribute('name')); + name.setStyle({ + position: 'absolute', + color: 'white', + background: 'black', + left: left + 'px', + top: top + 'px', + zIndex: 3}); + document.body.appendChild(name); + } + + }, + + /* + * show nearest tag with name + */ + show_nearest_tag_with_name: function(event){ + var distance = 100000000; + var tag_id = -1; + var photo_x = this.pos.left; + var photo_y = this.pos.top; + var mouse_x = event.pointerX(); + var mouse_y = event.pointerY(); + + this.ptags.each(function(pair){ + var x = photo_x + parseInt(pair.value.readAttribute('x')); + var width = parseInt(pair.value.readAttribute('width')); + var y = photo_y + parseInt(pair.value.readAttribute('y')); + var height = parseInt(pair.value.readAttribute('height')); + if(mouse_x >= x && mouse_x <= x + width && mouse_y >=y && mouse_y <= y + height){ + var delta_x = (x + width/2) - mouse_x; //alert(delta_x); + var delta_y = (y + height/2) - mouse_y; //alert(delta_y); + var delta = ((x + width/2) - mouse_x) * ((x + width/2) - mouse_x) + ((y + height/2) - mouse_y) * ((y + height/2) - mouse_y); + if(delta < distance){ + distance = delta; + tag_id = pair.key; + } + }else{ + if(pair.key == this.current_tag_id){ + this.hide_tag_with_name(this.current_tag_id); + this.current_tag_id = -1; + } + } + }.bind(this)); + + if(tag_id >= 0){ + this.current_tag_id = tag_id; + this.show_tag_with_name(tag_id); + } }, /* * complete tagging */ complete: function(){ // hide complete panel this.complete_panel.hide(); // hide square and tag input this.hide_square(); this.hide_tag_input(); // stop listening for photo click event - this.photo.stopObserving('click'); + this.photo.stopObserving('click'); + + // start listening for mousemove event + this.photo.observe('mousemove', function(event){ + this.show_nearest_tag_with_name(event); + }.bind(this)); } }); diff --git a/public/javascripts/prototype.js b/public/javascripts/prototype.js old mode 100644 new mode 100755 diff --git a/public/javascripts/status.js b/public/javascripts/status.js old mode 100644 new mode 100755 diff --git a/public/javascripts/util.js b/public/javascripts/util.js old mode 100644 new mode 100755 diff --git a/public/javascripts/validator.js b/public/javascripts/validator.js old mode 100644 new mode 100755 index 3c2d1a4..dfb978b --- a/public/javascripts/validator.js +++ b/public/javascripts/validator.js @@ -1,523 +1,523 @@ function show_qq_requirement(){ $('qq_info').innerHTML = '<span style="color:grey">input your real qq</span>'; } function validate_qq(qq){ var info = $('qq_info'); if(qq == '') return true; //qq is not mandatory if(qq.length < 6 || qq.length > 11){ info.innerHTML = '<span style="color: red">this qq number is not valid</span>'; return false; } if(parseInt(qq)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits are allowed here</span>'; return false; } } function show_webiste_requirement(){ $('website_info').innerHTML = '<span style="color:grey">input your personal website</span>'; } function validate_website(website){ var info = $('website_info'); info.innerHTML = '<span style="color: green">valid</span>'; return true; } function show_mobile_requirement(){ $('mobile_info').innerHTML = '<span style="color:grey">input your mobile number</span>'; } function validate_mobile(mobile){ var info = $('mobile_info'); if(mobile == '') return true; //qq is not mandatory if(mobile.length != 11){ info.innerHTML = '<span style="color: red">this mobile phone number is not valid</span>'; return false; } if(parseInt(mobile)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits are allowed here</span>'; return false; } } function validate_contact_info(){ var error = false; var qq = $('user_qq').value; var mobile = $('user_mobile').value; var website = $('user_website').value; if(!validate_qq(qq)) error = true; if(!validate_mobile(mobile)) error = true; if(!validate_website(website)) error = true; return error; } function update_contact_info(user_id){ if(validate_contact_info()) return; var form = $('contact_form'); var url = '/users/' + user_id + '/contact_info?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function validate_basic_info(){ var error = false; var login = $('user_login').value; if(!validate_login(login)) error = true; return error; } function update_basic_info(user_id){ if(validate_basic_info()) return; var form = $('basic_form'); var url = '/users/' + user_id + '/basic_info?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function show_login_requirement(){ $('login_info').setStyle({color: 'grey'}); $('login_info').innerHTML = 'only digits, letters and underscore are allowed, range 4..16'; } function validate_login(name){ var info = $('login_info'); // check presence if(name == ''){ info.innerHTML = '<span style="color: red">login cannot be blank</span>'; return false; } // check length if(name.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(name.length > 16){ info.innerHTML = '<span style="color: red">too long, at most 16 characters</span>'; return false; } // check pattern first = name[0]; if((first >= 'a' && first <= 'z') || (first >= 'A' && first <= 'Z')){ if(name.match(/[A-Za-z0-9\_]+/)){ info.innerHTML = '<span style="color: green">valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">only digits, letters and underscore are allowed</span>'; return false; } }else{ info.innerHTML = '<span style="color: red">must start with A-Z or a-z</span>'; return false; } } function show_email_requirement(){ $('email_info').setStyle({color: 'grey'}); $('email_info').innerHTML = 'please input valid email box' } function validate_email(email){ var info = $('email_info'); // check presence if(email == ''){ info.innerHTML = '<span style="color: red">email cannot be blank</span>'; return false; } // check length if(email.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(email.length > 100){ info.innerHTML = '<span style="color: red">too long, at most 100 characters</span>'; return false; } // check pattern if(email.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)){ // send ajax request to check uniqueness new Ajax.Request('/validator/validates_email_uniqueness?email='+email, { method: 'get', onSuccess: function(transport){ var info = $('email_info'); if(transport.responseText == 'yes'){ info.innerHTML = '<span style="color: green">valid</span>'; }else{ info.innerHTML = '<span style="color: red">this email has already been occupied</span>'; } } }); return true; }else{ info.innderHTML = '<span style="color: red">invalid email format</span>'; return false; } } function show_password_requirement(){ $('password_info').setStyle({color: 'grey'}); $('password_info').innerHTML = 'password consists of 6-20 characters' } function validate_password(password){ var info = $('password_info') var strongReg = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g"); var mediumReg = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g"); // check length if(password.length < 6){ info.innerHTML = '<span style="color: red">too short, at least 6 characters</span>'; return false; } if(password.length > 20){ info.innerHTML = '<span style="color: red">too long, at most 20 characters</span>'; return false; } // check strength if(password.match(strongReg)){ info.innerHTML = '<span style="color: green">Valid: Strong Strength!</span>'; return true; }else if(password.match(mediumReg)){ info.innerHTML = '<span style="color: orange">Valid: Medium Strength!</span>'; return true; }else{ info.innerHTML = '<span style="color: red"> Valid: Weak Strength!</span>'; return true; } } function show_password_confirm_requirement(){ $('password_confirmation_info').setStyle({color: 'grey'}); $('password_confirmation_info').innerHTML = 'confirm your password' } function validate_password_confirmation(password_confirmation){ var info = $('password_confirmation_info'); var password = $('user_password').value; if(password == ''){ info.innerHTML = '<span style="color: red"> password cannot be blank </span>'; return false; } if(password == password_confirmation){ info.innerHTML = '<span style="color: green">Valid</span>'; return true; }else{ info.innerHTML = '<span style="color: red">Two passwords are not consistent</span>'; return false; } } function validate_register_info(){ var error = false; var login = $('user_login').value; var email = $('user_email').value; var password = $('user_password').value; var password_confirmation = $('user_password_confirmation').value; if(!validate_login(login)) error = true; if(!validate_email(email)) error = true; if(!validate_password(password)) error = true; if(!validate_password_confirmation(password_confirmation)) error = true; var form = $('register_form'); var cs = $('characters').childElements(); var length = cs.length; if(length == 0){ $('character_info').innerHTML = '<span style="color:red">You must specify at least one game character</span>' error = true; } return error; } function validate_game_id(game_id){ var info = $('game_id_info'); if(game_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> game cannot be blank </span>'; return false; } } function game_onchange(game_id){ if(game_id == '---'){ $('details').innerHTML = ''; }else{ new Ajax.Updater('details', '/games/' + game_id, {method: 'get'}); } } function show_name_requirement(){ var info = $('name_info'); info.innerHTML = '<span style="color: grey"> Input your character name </span>'; } function validate_name(name){ var info = $('name_info'); if(name == ''){ info.innerHTML = '<span style="color: red"> name cannot be blank </span>'; return false; }else{ info.innerHTML = '<span style="color: green"> valid </span>'; return true; } } function show_level_requirement(){ var info = $('level_info'); info.innerHTML = '<span style="color: grey"> Input your character level </span>'; } function validate_level(level){ var info = $('level_info'); if(level == ''){ info.innerHTML = '<span style="color: red"> level cannot be blank </span>'; return false; }else{ if(parseInt(level)){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> level should be an integer </span>'; return false; } } } function validate_server_id(server_id){ var info = $('server_id_info'); if(server_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> server cannot be blank </span>'; return false; } } function validate_area_id(area_id){ var info = $('area_id_info'); if(area_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> area cannot be blank </span>'; return false; } } function area_onchange(area_id){ if(area_id == '---'){ $('servers').innerHTML = '<label style="width:125px;float:left">Game Server:</label><select id="server_id" name="server_id"><option value="---">---</option></select>'; }else{ new Ajax.Updater('servers', '/game_areas/' + area_id, {method: 'get'}); } } function validate_race_id(race_id){ var info = $('race_id_info'); if(race_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> race cannot be blank </span>'; return false; } } function validate_profession_id(profession_id){ var info = $('profession_id_info'); if(profession_id != '---'){ info.innerHTML = '<span style="color: green"> valid </span>'; return true; }else{ info.innerHTML = '<span style="color: red"> profession cannot be blank </span>'; return false; } } var nr=0; function validate_game_character(){ // check all parameters var error = false; var game_id = $('character_game_id').value; var name = $('character_name').value; var level = $('character_level').value; if(!validate_name(name)) error = true; if(!validate_level(level)) error = true; if(!validate_game_id(game_id)) error = true; if(game_id == '---') return true; var server_id = $('character_server_id').value; var race_id = $('character_race_id').value; var profession_id = $('character_profession_id').value; var area_id = null; if(!validate_server_id(server_id)) error = true; + alert(1); if(!validate_race_id(race_id)) error = true; + alert(2); if(!validate_profession_id(profession_id)) error = true; - if($('area_id') != null){ - area_id = $('area_id').value; + alert(3); + if($('character_area_id') != null){ + area_id = $('character_area_id').value; if(!validate_area_id(area_id)) error = true; } - + alert(4); return error; } function construct_game_character_element(){ - var error = false; - var game_id = $('game_id').value; - var name = $('name').value; - var level = $('level').value; - var server_id = $('server_id').value; - var race_id = $('race_id').value; - var profession_id = $('profession_id').value; + var game_id = $('character_game_id').value; + var name = $('character_name').value; + var level = $('character_level').value; + var server_id = $('character_server_id').value; + var race_id = $('character_race_id').value; + var profession_id = $('character_profession_id').value; var area_id = null; - + // construct a character element that will show on registration page // html code looks like: // <li character_attributes> character_name <a href='#' onClick='edit_character'>edit</a> <a href='#' onClick='delete_character'>edit</a></li> var li = new Element('li', {id: 'character'+nr, game_id: game_id, name: name, level: level, server_id: server_id, race_id: race_id, profession_id: profession_id}); - if($('area_id') != null){ - area_id = $('area_id').value; + if($('character_area_id') != null){ + area_id = $('character_area_id').value; li.writeAttribute({area_id: area_id}); } // construct label var label = new Element('label').update(name); // construct url - var parameters = 'id='+nr+'&character[game_id]='+game_id+'&character[name]='+name+'&character[level]='+level+'&character[server_id]='+server_id+'&character[race_id]='+race_id+'&character[profession_id]='+profession_id; - if(area_id != null) - parameters += '&character[area_id]=' + area_id; + var parameters = 'id='+nr+'&' +$('character_form').serialize(); var url = '/game_characters/edit_new?' + parameters; var edit_link = new Element('a', { href: url, rel: 'facebox'}).update('edit'); - + alert(url); // construct delete link and its event var delete_link = new Element('a', { href: '#'}).update('delete'); delete_link.observe('click', function(event){ this.parentNode.remove(); }); // append elements to li li.appendChild(label); li.appendChild(edit_link); li.appendChild(delete_link); nr++; return li; } function add_character(){ if(validate_game_character()) return; $('characters').insert(construct_game_character_element()); // close current facebox facebox.watchClickEvents(); facebox.close(); } function add_user_character(user_id){ if(validate_game_character()) return; var form = $('character_form'); var url = '/users/' + user_id + '/characters?' + form.serialize(); new Ajax.Request(url, {method: 'post'}); } function update_character(id){ if(validate_game_character()) return; $('character'+id).replace(construct_game_character_element()); // close current facebox facebox.watchClickEvents(); facebox.close(); } function update_user_character(user_id, id){ if(validate_game_character()) return; var form = $('character_form'); var url = '/users/' + user_id + '/characters/' + id + '?' + form.serialize(); new Ajax.Request(url, {method: 'put'}); } function validate_and_request(){ if(validate_register_info()) return; // check if user has input at least one game character var form = $('register_form'); var cs = $('characters').childElements(); var length = cs.length; // construct url and parameter var parameters = ''; for(var i=0;i<length;i++){ var game_id = cs[i].readAttribute('game_id'); var name = cs[i].readAttribute('name'); var level = cs[i].readAttribute('level'); var area_id = cs[i].readAttribute('area_id'); var server_id = cs[i].readAttribute('server_id'); var race_id = cs[i].readAttribute('race_id'); var profession_id = cs[i].readAttribute('profession_id'); parameters += 'cs[][game_id]='+game_id+'&cs[][name]='+name+'&cs[][level]='+level+'&cs[][server_id]='+server_id+'&cs[][race_id]='+race_id+'&cs[][profession_id]='+profession_id; if(area_id != null) parameters += '&cs[][area_id]=' + area_id; parameters += '&'; } parameters += form.serialize(); url = '/users?' + parameters; // send request to server new Ajax.Request(url, {method: 'post'}); } diff --git a/public/photos/0000/0001/1.jpg b/public/photos/0000/0001/1.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0001/1_large.jpg b/public/photos/0000/0001/1_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0001/1_medium.jpg b/public/photos/0000/0001/1_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0001/1_small.jpg b/public/photos/0000/0001/1_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0001/2.jpg b/public/photos/0000/0001/2.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0001/2_large.jpg b/public/photos/0000/0001/2_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0001/2_medium.jpg b/public/photos/0000/0001/2_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0001/2_small.jpg b/public/photos/0000/0001/2_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0001/lin.wallpaper.jpg b/public/photos/0000/0001/lin.wallpaper.jpg new file mode 100644 index 0000000..c232fb5 Binary files /dev/null and b/public/photos/0000/0001/lin.wallpaper.jpg differ diff --git a/public/photos/0000/0001/lin.wallpaper_large.jpg b/public/photos/0000/0001/lin.wallpaper_large.jpg new file mode 100644 index 0000000..85bf7d4 Binary files /dev/null and b/public/photos/0000/0001/lin.wallpaper_large.jpg differ diff --git a/public/photos/0000/0001/lin.wallpaper_medium.jpg b/public/photos/0000/0001/lin.wallpaper_medium.jpg new file mode 100644 index 0000000..8cd1cc5 Binary files /dev/null and b/public/photos/0000/0001/lin.wallpaper_medium.jpg differ diff --git a/public/photos/0000/0001/lin.wallpaper_small.jpg b/public/photos/0000/0001/lin.wallpaper_small.jpg new file mode 100644 index 0000000..5da6a86 Binary files /dev/null and b/public/photos/0000/0001/lin.wallpaper_small.jpg differ diff --git a/public/photos/0000/0005/2719063547_7c0249508a_o.png b/public/photos/0000/0005/2719063547_7c0249508a_o.png new file mode 100644 index 0000000..fb8e5e4 Binary files /dev/null and b/public/photos/0000/0005/2719063547_7c0249508a_o.png differ diff --git a/public/photos/0000/0005/2719063547_7c0249508a_o_large.png b/public/photos/0000/0005/2719063547_7c0249508a_o_large.png new file mode 100644 index 0000000..f4e26be Binary files /dev/null and b/public/photos/0000/0005/2719063547_7c0249508a_o_large.png differ diff --git a/public/photos/0000/0005/2719063547_7c0249508a_o_medium.png b/public/photos/0000/0005/2719063547_7c0249508a_o_medium.png new file mode 100644 index 0000000..163f588 Binary files /dev/null and b/public/photos/0000/0005/2719063547_7c0249508a_o_medium.png differ diff --git a/public/photos/0000/0005/2719063547_7c0249508a_o_small.png b/public/photos/0000/0005/2719063547_7c0249508a_o_small.png new file mode 100644 index 0000000..0a8649f Binary files /dev/null and b/public/photos/0000/0005/2719063547_7c0249508a_o_small.png differ diff --git a/public/photos/0000/0005/8.jpg b/public/photos/0000/0005/8.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0005/8_large.jpg b/public/photos/0000/0005/8_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0005/8_medium.jpg b/public/photos/0000/0005/8_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0005/8_small.jpg b/public/photos/0000/0005/8_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0009/14.jpg b/public/photos/0000/0009/14.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0009/14_large.jpg b/public/photos/0000/0009/14_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0009/14_medium.jpg b/public/photos/0000/0009/14_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0009/14_small.jpg b/public/photos/0000/0009/14_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0009/4.jpg b/public/photos/0000/0009/4.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0009/4_large.jpg b/public/photos/0000/0009/4_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0009/4_medium.jpg b/public/photos/0000/0009/4_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0009/4_small.jpg b/public/photos/0000/0009/4_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0013/14.jpg b/public/photos/0000/0013/14.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0013/14_large.jpg b/public/photos/0000/0013/14_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0013/14_medium.jpg b/public/photos/0000/0013/14_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0013/14_small.jpg b/public/photos/0000/0013/14_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0013/5.jpg b/public/photos/0000/0013/5.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0013/5_large.jpg b/public/photos/0000/0013/5_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0013/5_medium.jpg b/public/photos/0000/0013/5_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0013/5_small.jpg b/public/photos/0000/0013/5_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0017/14.jpg b/public/photos/0000/0017/14.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0017/14_large.jpg b/public/photos/0000/0017/14_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0017/14_medium.jpg b/public/photos/0000/0017/14_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0017/14_small.jpg b/public/photos/0000/0017/14_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0021/1.jpg b/public/photos/0000/0021/1.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0021/1_large.jpg b/public/photos/0000/0021/1_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0021/1_medium.jpg b/public/photos/0000/0021/1_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0021/1_small.jpg b/public/photos/0000/0021/1_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0021/5.jpg b/public/photos/0000/0021/5.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0021/5_large.jpg b/public/photos/0000/0021/5_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0021/5_medium.jpg b/public/photos/0000/0021/5_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0021/5_small.jpg b/public/photos/0000/0021/5_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0025/12.jpg b/public/photos/0000/0025/12.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0025/12_large.jpg b/public/photos/0000/0025/12_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0025/12_medium.jpg b/public/photos/0000/0025/12_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0025/12_small.jpg b/public/photos/0000/0025/12_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0025/4.jpg b/public/photos/0000/0025/4.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0025/4_large.jpg b/public/photos/0000/0025/4_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0025/4_medium.jpg b/public/photos/0000/0025/4_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0025/4_small.jpg b/public/photos/0000/0025/4_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0029/12.jpg b/public/photos/0000/0029/12.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0029/12_large.jpg b/public/photos/0000/0029/12_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0029/12_medium.jpg b/public/photos/0000/0029/12_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0029/12_small.jpg b/public/photos/0000/0029/12_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0177/1.jpg b/public/photos/0000/0177/1.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0177/1_large.jpg b/public/photos/0000/0177/1_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0177/1_medium.jpg b/public/photos/0000/0177/1_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0177/1_small.jpg b/public/photos/0000/0177/1_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0189/8.jpg b/public/photos/0000/0189/8.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0189/8_large.jpg b/public/photos/0000/0189/8_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0189/8_medium.jpg b/public/photos/0000/0189/8_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0189/8_small.jpg b/public/photos/0000/0189/8_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0193/10.jpg b/public/photos/0000/0193/10.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0193/10_large.jpg b/public/photos/0000/0193/10_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0193/10_medium.jpg b/public/photos/0000/0193/10_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0193/10_small.jpg b/public/photos/0000/0193/10_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0201/1.jpg b/public/photos/0000/0201/1.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0201/1_large.jpg b/public/photos/0000/0201/1_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0201/1_medium.jpg b/public/photos/0000/0201/1_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0201/1_small.jpg b/public/photos/0000/0201/1_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0205/14.jpg b/public/photos/0000/0205/14.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0205/14_large.jpg b/public/photos/0000/0205/14_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0205/14_medium.jpg b/public/photos/0000/0205/14_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0205/14_small.jpg b/public/photos/0000/0205/14_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0213/2.jpg b/public/photos/0000/0213/2.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0213/2_large.jpg b/public/photos/0000/0213/2_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0213/2_medium.jpg b/public/photos/0000/0213/2_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0213/2_small.jpg b/public/photos/0000/0213/2_small.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0217/3.jpg b/public/photos/0000/0217/3.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0217/3_large.jpg b/public/photos/0000/0217/3_large.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0217/3_medium.jpg b/public/photos/0000/0217/3_medium.jpg old mode 100644 new mode 100755 diff --git a/public/photos/0000/0217/3_small.jpg b/public/photos/0000/0217/3_small.jpg old mode 100644 new mode 100755 diff --git a/public/robots.txt b/public/robots.txt old mode 100644 new mode 100755 diff --git a/public/stylesheets/admin.css b/public/stylesheets/admin.css old mode 100644 new mode 100755 diff --git a/public/stylesheets/facebox.css b/public/stylesheets/facebox.css old mode 100644 new mode 100755 diff --git a/public/stylesheets/facebox.css~ b/public/stylesheets/facebox.css~ old mode 100644 new mode 100755 diff --git a/public/stylesheets/photo_tag.css b/public/stylesheets/photo_tag.css old mode 100644 new mode 100755 diff --git a/public/stylesheets/popup.css b/public/stylesheets/popup.css old mode 100644 new mode 100755 diff --git a/public/stylesheets/root.css b/public/stylesheets/root.css old mode 100644 new mode 100755 diff --git a/public/stylesheets/scaffold.css b/public/stylesheets/scaffold.css old mode 100644 new mode 100755 diff --git a/public/stylesheets/user.css b/public/stylesheets/user.css old mode 100644 new mode 100755 diff --git a/test/fixtures/albums.yml b/test/fixtures/albums.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/bcomments.yml b/test/fixtures/bcomments.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/bdigs.yml b/test/fixtures/bdigs.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/blogs.yml b/test/fixtures/blogs.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/btags.yml b/test/fixtures/btags.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/cities.yml b/test/fixtures/cities.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/countries.yml b/test/fixtures/countries.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/event_wall_messages.yml b/test/fixtures/event_wall_messages.yml new file mode 100644 index 0000000..5bf0293 --- /dev/null +++ b/test/fixtures/event_wall_messages.yml @@ -0,0 +1,7 @@ +# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html + +# one: +# column: value +# +# two: +# column: value diff --git a/test/fixtures/friendships.yml b/test/fixtures/friendships.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/game_areas.yml b/test/fixtures/game_areas.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/game_characters.yml b/test/fixtures/game_characters.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/game_professions.yml b/test/fixtures/game_professions.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/game_races.yml b/test/fixtures/game_races.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/game_servers.yml b/test/fixtures/game_servers.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/games.yml b/test/fixtures/games.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/icons.yml b/test/fixtures/icons.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/mails.yml b/test/fixtures/mails.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/pages.yml b/test/fixtures/pages.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/pcomments.yml b/test/fixtures/pcomments.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/pdigs.yml b/test/fixtures/pdigs.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/permissions.yml b/test/fixtures/permissions.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/photos.yml b/test/fixtures/photos.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/provinces.yml b/test/fixtures/provinces.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/ptags.yml b/test/fixtures/ptags.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/roles.yml b/test/fixtures/roles.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/statuses.yml b/test/fixtures/statuses.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml old mode 100644 new mode 100755 diff --git a/test/fixtures/wall_messages.yml b/test/fixtures/wall_messages.yml old mode 100644 new mode 100755 diff --git a/test/functional/album_feeds_controller_test.rb b/test/functional/album_feeds_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/album_photos_controller_test.rb b/test/functional/album_photos_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/albums_controller_test.rb b/test/functional/albums_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/basic_info_controller_test.rb b/test/functional/basic_info_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/bcomments_controller_test.rb b/test/functional/bcomments_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/bdigs_controller_test.rb b/test/functional/bdigs_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/blog_comments_controller_test.rb b/test/functional/blog_comments_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/blog_digs_controller_test.rb b/test/functional/blog_digs_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/blog_feeds_controller_test.rb b/test/functional/blog_feeds_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/blog_tags_controller_test.rb b/test/functional/blog_tags_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/blogs_controller_test.rb b/test/functional/blogs_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/btags_controller_test.rb b/test/functional/btags_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/cities_controller_test.rb b/test/functional/cities_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/contact_info_controller_test.rb b/test/functional/contact_info_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/countries_controller_test.rb b/test/functional/countries_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/friends_controller_test.rb b/test/functional/friends_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/friendships_controller_test.rb b/test/functional/friendships_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/game_areas_controller_test.rb b/test/functional/game_areas_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/game_characters_controller_test.rb b/test/functional/game_characters_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/game_professions_controller_test.rb b/test/functional/game_professions_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/game_races_controller_test.rb b/test/functional/game_races_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/game_servers_controller_test.rb b/test/functional/game_servers_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/games_controller_test.rb b/test/functional/games_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/icons_controller_test.rb b/test/functional/icons_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/mailboxes_controller_test.rb b/test/functional/mailboxes_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/mails_controller_test.rb b/test/functional/mails_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/pages_controller_test.rb b/test/functional/pages_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/passwords_controller_test.rb b/test/functional/passwords_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/pcomments_controller_test.rb b/test/functional/pcomments_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/pdigs_controller_test.rb b/test/functional/pdigs_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/photo_comments_controller_test.rb b/test/functional/photo_comments_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/photo_digs_controller_test.rb b/test/functional/photo_digs_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/photo_tags_controller_test.rb b/test/functional/photo_tags_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/photos_controller_test.rb b/test/functional/photos_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/profile_controller_test.rb b/test/functional/profile_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/provinces_controller_test.rb b/test/functional/provinces_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/ptags_controller_test.rb b/test/functional/ptags_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/root_controller_test.rb b/test/functional/root_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/sessions_controller_test.rb b/test/functional/sessions_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/statuses_controller_test.rb b/test/functional/statuses_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/tagged_blogs_controller_test.rb b/test/functional/tagged_blogs_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/tagged_photos_controller_test.rb b/test/functional/tagged_photos_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/user_albums_controller_test.rb b/test/functional/user_albums_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/user_blogs_controller_test.rb b/test/functional/user_blogs_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/user_characters_controller_test.rb b/test/functional/user_characters_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/user_statuses_controller_test.rb b/test/functional/user_statuses_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/user_wall_messages_controller_test.rb b/test/functional/user_wall_messages_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/users_controller_test.rb b/test/functional/users_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/validator_controller_test.rb b/test/functional/validator_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/functional/wall_messages_controller_test.rb b/test/functional/wall_messages_controller_test.rb old mode 100644 new mode 100755 diff --git a/test/performance/browsing_test.rb b/test/performance/browsing_test.rb old mode 100644 new mode 100755 diff --git a/test/test_helper.rb b/test/test_helper.rb old mode 100644 new mode 100755 diff --git a/test/unit/album_test.rb b/test/unit/album_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/bcomment_test.rb b/test/unit/bcomment_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/bdig_test.rb b/test/unit/bdig_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/blog_test.rb b/test/unit/blog_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/btag_test.rb b/test/unit/btag_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/city_test.rb b/test/unit/city_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/country_test.rb b/test/unit/country_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/event_wall_message_test.rb b/test/unit/event_wall_message_test.rb new file mode 100644 index 0000000..6bdfc63 --- /dev/null +++ b/test/unit/event_wall_message_test.rb @@ -0,0 +1,8 @@ +require 'test_helper' + +class EventWallMessageTest < ActiveSupport::TestCase + # Replace this with your real tests. + test "the truth" do + assert true + end +end diff --git a/test/unit/friendship_test.rb b/test/unit/friendship_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/game_area_test.rb b/test/unit/game_area_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/game_character_test.rb b/test/unit/game_character_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/game_profession_test.rb b/test/unit/game_profession_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/game_race_test.rb b/test/unit/game_race_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/game_server_test.rb b/test/unit/game_server_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/game_test.rb b/test/unit/game_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/album_feeds_helper_test.rb b/test/unit/helpers/album_feeds_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/album_photos_helper_test.rb b/test/unit/helpers/album_photos_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/albums_helper_test.rb b/test/unit/helpers/albums_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/basic_info_helper_test.rb b/test/unit/helpers/basic_info_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/bcomments_helper_test.rb b/test/unit/helpers/bcomments_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/bdigs_helper_test.rb b/test/unit/helpers/bdigs_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/blog_comments_helper_test.rb b/test/unit/helpers/blog_comments_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/blog_digs_helper_test.rb b/test/unit/helpers/blog_digs_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/blog_feeds_helper_test.rb b/test/unit/helpers/blog_feeds_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/blog_tags_helper_test.rb b/test/unit/helpers/blog_tags_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/blogs_helper_test.rb b/test/unit/helpers/blogs_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/btags_helper_test.rb b/test/unit/helpers/btags_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/cities_helper_test.rb b/test/unit/helpers/cities_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/contact_info_helper_test.rb b/test/unit/helpers/contact_info_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/countries_helper_test.rb b/test/unit/helpers/countries_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/friends_helper_test.rb b/test/unit/helpers/friends_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/friendships_helper_test.rb b/test/unit/helpers/friendships_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/game_areas_helper_test.rb b/test/unit/helpers/game_areas_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/game_characters_helper_test.rb b/test/unit/helpers/game_characters_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/game_professions_helper_test.rb b/test/unit/helpers/game_professions_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/game_races_helper_test.rb b/test/unit/helpers/game_races_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/game_servers_helper_test.rb b/test/unit/helpers/game_servers_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/games_helper_test.rb b/test/unit/helpers/games_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/icons_helper_test.rb b/test/unit/helpers/icons_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/mailboxes_helper_test.rb b/test/unit/helpers/mailboxes_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/mails_helper_test.rb b/test/unit/helpers/mails_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/pages_helper_test.rb b/test/unit/helpers/pages_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/passwords_helper_test.rb b/test/unit/helpers/passwords_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/pcomments_helper_test.rb b/test/unit/helpers/pcomments_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/pdigs_helper_test.rb b/test/unit/helpers/pdigs_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/photo_comments_helper_test.rb b/test/unit/helpers/photo_comments_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/photo_digs_helper_test.rb b/test/unit/helpers/photo_digs_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/photo_tags_helper_test.rb b/test/unit/helpers/photo_tags_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/photos_helper_test.rb b/test/unit/helpers/photos_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/profile_helper_test.rb b/test/unit/helpers/profile_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/provinces_helper_test.rb b/test/unit/helpers/provinces_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/ptags_helper_test.rb b/test/unit/helpers/ptags_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/root_helper_test.rb b/test/unit/helpers/root_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/statuses_helper_test.rb b/test/unit/helpers/statuses_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/tagged_blogs_helper_test.rb b/test/unit/helpers/tagged_blogs_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/tagged_photos_helper_test.rb b/test/unit/helpers/tagged_photos_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/user_albums_helper_test.rb b/test/unit/helpers/user_albums_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/user_blogs_helper_test.rb b/test/unit/helpers/user_blogs_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/user_characters_helper_test.rb b/test/unit/helpers/user_characters_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/user_statuses_helper_test.rb b/test/unit/helpers/user_statuses_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/user_wall_messages_helper_test.rb b/test/unit/helpers/user_wall_messages_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/validator_helper_test.rb b/test/unit/helpers/validator_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/helpers/wall_messages_helper_test.rb b/test/unit/helpers/wall_messages_helper_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/icon_test.rb b/test/unit/icon_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/mail_test.rb b/test/unit/mail_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/page_test.rb b/test/unit/page_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/pcomment_test.rb b/test/unit/pcomment_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/pdig_test.rb b/test/unit/pdig_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/permission_test.rb b/test/unit/permission_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/photo_test.rb b/test/unit/photo_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/province_test.rb b/test/unit/province_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/ptag_test.rb b/test/unit/ptag_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/role_test.rb b/test/unit/role_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/status_test.rb b/test/unit/status_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/user_mailer_test.rb b/test/unit/user_mailer_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb old mode 100644 new mode 100755 diff --git a/test/unit/wall_message_test.rb b/test/unit/wall_message_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/CHANGELOG b/vendor/plugins/attachment_fu/CHANGELOG old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/README b/vendor/plugins/attachment_fu/README old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/Rakefile b/vendor/plugins/attachment_fu/Rakefile old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/amazon_s3.yml.tpl b/vendor/plugins/attachment_fu/amazon_s3.yml.tpl old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/init.rb b/vendor/plugins/attachment_fu/init.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/install.rb b/vendor/plugins/attachment_fu/install.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/geometry.rb b/vendor/plugins/attachment_fu/lib/geometry.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/db_file_backend.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/db_file_backend.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/backends/db_file_test.rb b/vendor/plugins/attachment_fu/test/backends/db_file_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/backends/file_system_test.rb b/vendor/plugins/attachment_fu/test/backends/file_system_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb b/vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/base_attachment_tests.rb b/vendor/plugins/attachment_fu/test/base_attachment_tests.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/basic_test.rb b/vendor/plugins/attachment_fu/test/basic_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/database.yml b/vendor/plugins/attachment_fu/test/database.yml old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/extra_attachment_test.rb b/vendor/plugins/attachment_fu/test/extra_attachment_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/fixtures/attachment.rb b/vendor/plugins/attachment_fu/test/fixtures/attachment.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/fixtures/files/fake/rails.png b/vendor/plugins/attachment_fu/test/fixtures/files/fake/rails.png old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/fixtures/files/foo.txt b/vendor/plugins/attachment_fu/test/fixtures/files/foo.txt old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/fixtures/files/rails.png b/vendor/plugins/attachment_fu/test/fixtures/files/rails.png old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/geometry_test.rb b/vendor/plugins/attachment_fu/test/geometry_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/processors/core_image_test.rb b/vendor/plugins/attachment_fu/test/processors/core_image_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/processors/gd2_test.rb b/vendor/plugins/attachment_fu/test/processors/gd2_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/processors/image_science_test.rb b/vendor/plugins/attachment_fu/test/processors/image_science_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb b/vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/processors/rmagick_test.rb b/vendor/plugins/attachment_fu/test/processors/rmagick_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/schema.rb b/vendor/plugins/attachment_fu/test/schema.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/test_helper.rb b/vendor/plugins/attachment_fu/test/test_helper.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/test/validation_test.rb b/vendor/plugins/attachment_fu/test/validation_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/color.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/color.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/effects.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/effects.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/quality.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/quality.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/scale.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/scale.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/processor.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/processor.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/auto_complete/README b/vendor/plugins/auto_complete/README old mode 100644 new mode 100755 diff --git a/vendor/plugins/auto_complete/Rakefile b/vendor/plugins/auto_complete/Rakefile old mode 100644 new mode 100755 diff --git a/vendor/plugins/auto_complete/init.rb b/vendor/plugins/auto_complete/init.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/auto_complete/lib/auto_complete.rb b/vendor/plugins/auto_complete/lib/auto_complete.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/auto_complete/lib/auto_complete_macros_helper.rb b/vendor/plugins/auto_complete/lib/auto_complete_macros_helper.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/auto_complete/test/auto_complete_test.rb b/vendor/plugins/auto_complete/test/auto_complete_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/README.txt b/vendor/plugins/facebox-for-prototype/README.txt old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/b.png b/vendor/plugins/facebox-for-prototype/b.png old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/bl.png b/vendor/plugins/facebox-for-prototype/bl.png old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/br.png b/vendor/plugins/facebox-for-prototype/br.png old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/facebox.css b/vendor/plugins/facebox-for-prototype/facebox.css old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/facebox.js b/vendor/plugins/facebox-for-prototype/facebox.js old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/facebox.js~ b/vendor/plugins/facebox-for-prototype/facebox.js~ old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/tl.png b/vendor/plugins/facebox-for-prototype/tl.png old mode 100644 new mode 100755 diff --git a/vendor/plugins/facebox-for-prototype/tr.png b/vendor/plugins/facebox-for-prototype/tr.png old mode 100644 new mode 100755 diff --git a/vendor/plugins/imagemagick_tag/README b/vendor/plugins/imagemagick_tag/README old mode 100644 new mode 100755 diff --git a/vendor/plugins/imagemagick_tag/init.rb b/vendor/plugins/imagemagick_tag/init.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/imagemagick_tag/lib/image_magick.rb b/vendor/plugins/imagemagick_tag/lib/image_magick.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/imagemagick_tag/lib/image_magick_macro_helper.rb b/vendor/plugins/imagemagick_tag/lib/image_magick_macro_helper.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/imagemagick_tag/test/image_magick_macro_helper_test.rb b/vendor/plugins/imagemagick_tag/test/image_magick_macro_helper_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/imagemagick_tag/test/image_magick_macro_test.rb b/vendor/plugins/imagemagick_tag/test/image_magick_macro_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/README b/vendor/plugins/restful_authentication/README old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/Rakefile b/vendor/plugins/restful_authentication/Rakefile old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/USAGE b/vendor/plugins/restful_authentication/generators/authenticated/USAGE old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/authenticated_generator.rb b/vendor/plugins/restful_authentication/generators/authenticated/authenticated_generator.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/activation.html.erb b/vendor/plugins/restful_authentication/generators/authenticated/templates/activation.html.erb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/authenticated_system.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/authenticated_system.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/authenticated_test_helper.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/authenticated_test_helper.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/controller.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/controller.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/fixtures.yml b/vendor/plugins/restful_authentication/generators/authenticated/templates/fixtures.yml old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/functional_spec.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/functional_spec.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/functional_test.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/functional_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/helper.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/helper.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/login.html.erb b/vendor/plugins/restful_authentication/generators/authenticated/templates/login.html.erb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/mailer.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/mailer.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/mailer_test.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/mailer_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/migration.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/migration.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/model.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/model.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/model_controller.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/model_controller.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/model_functional_spec.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/model_functional_spec.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/model_functional_test.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/model_functional_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/model_helper.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/model_helper.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/observer.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/observer.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/signup.html.erb b/vendor/plugins/restful_authentication/generators/authenticated/templates/signup.html.erb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/signup_notification.html.erb b/vendor/plugins/restful_authentication/generators/authenticated/templates/signup_notification.html.erb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/unit_spec.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/unit_spec.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/generators/authenticated/templates/unit_test.rb b/vendor/plugins/restful_authentication/generators/authenticated/templates/unit_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/install.rb b/vendor/plugins/restful_authentication/install.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/restful_authentication/lib/restful_authentication/rails_commands.rb b/vendor/plugins/restful_authentication/lib/restful_authentication/rails_commands.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/.manifest b/vendor/plugins/will_paginate/.manifest old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/CHANGELOG.rdoc b/vendor/plugins/will_paginate/CHANGELOG.rdoc old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/LICENSE b/vendor/plugins/will_paginate/LICENSE old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/README.rdoc b/vendor/plugins/will_paginate/README.rdoc old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/Rakefile b/vendor/plugins/will_paginate/Rakefile old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/examples/apple-circle.gif b/vendor/plugins/will_paginate/examples/apple-circle.gif old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/examples/index.haml b/vendor/plugins/will_paginate/examples/index.haml old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/examples/index.html b/vendor/plugins/will_paginate/examples/index.html old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/examples/pagination.css b/vendor/plugins/will_paginate/examples/pagination.css old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/examples/pagination.sass b/vendor/plugins/will_paginate/examples/pagination.sass old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/init.rb b/vendor/plugins/will_paginate/init.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate.rb b/vendor/plugins/will_paginate/lib/will_paginate.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate/array.rb b/vendor/plugins/will_paginate/lib/will_paginate/array.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate/collection.rb b/vendor/plugins/will_paginate/lib/will_paginate/collection.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb b/vendor/plugins/will_paginate/lib/will_paginate/core_ext.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate/finder.rb b/vendor/plugins/will_paginate/lib/will_paginate/finder.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb b/vendor/plugins/will_paginate/lib/will_paginate/named_scope.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb b/vendor/plugins/will_paginate/lib/will_paginate/named_scope_patch.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate/version.rb b/vendor/plugins/will_paginate/lib/will_paginate/version.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb b/vendor/plugins/will_paginate/lib/will_paginate/view_helpers.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/boot.rb b/vendor/plugins/will_paginate/test/boot.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/collection_test.rb b/vendor/plugins/will_paginate/test/collection_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/database.yml b/vendor/plugins/will_paginate/test/database.yml old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/finder_test.rb b/vendor/plugins/will_paginate/test/finder_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/admin.rb b/vendor/plugins/will_paginate/test/fixtures/admin.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/developer.rb b/vendor/plugins/will_paginate/test/fixtures/developer.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml b/vendor/plugins/will_paginate/test/fixtures/developers_projects.yml old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/project.rb b/vendor/plugins/will_paginate/test/fixtures/project.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/projects.yml b/vendor/plugins/will_paginate/test/fixtures/projects.yml old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/replies.yml b/vendor/plugins/will_paginate/test/fixtures/replies.yml old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/reply.rb b/vendor/plugins/will_paginate/test/fixtures/reply.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/schema.rb b/vendor/plugins/will_paginate/test/fixtures/schema.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/topic.rb b/vendor/plugins/will_paginate/test/fixtures/topic.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/topics.yml b/vendor/plugins/will_paginate/test/fixtures/topics.yml old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/user.rb b/vendor/plugins/will_paginate/test/fixtures/user.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/fixtures/users.yml b/vendor/plugins/will_paginate/test/fixtures/users.yml old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/helper.rb b/vendor/plugins/will_paginate/test/helper.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/lib/activerecord_test_case.rb b/vendor/plugins/will_paginate/test/lib/activerecord_test_case.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb b/vendor/plugins/will_paginate/test/lib/activerecord_test_connector.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/lib/load_fixtures.rb b/vendor/plugins/will_paginate/test/lib/load_fixtures.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/lib/view_test_process.rb b/vendor/plugins/will_paginate/test/lib/view_test_process.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/tasks.rake b/vendor/plugins/will_paginate/test/tasks.rake old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/test/view_test.rb b/vendor/plugins/will_paginate/test/view_test.rb old mode 100644 new mode 100755 diff --git a/vendor/plugins/will_paginate/will_paginate.gemspec b/vendor/plugins/will_paginate/will_paginate.gemspec old mode 100644 new mode 100755
erlware/erlcron
f235f1a2b47f6c51e20aaff4e13265637c97857d
v1.2.3
diff --git a/src/erlcron.app.src b/src/erlcron.app.src index 4d73e34..77a5d22 100644 --- a/src/erlcron.app.src +++ b/src/erlcron.app.src @@ -1,9 +1,9 @@ {application,erlcron, [{description,"Scheduled execution of Erlang functions"}, - {vsn,"1.2.2"}, + {vsn,"1.2.3"}, {modules,[]}, {registered,[ecrn_agent]}, {applications,[kernel,stdlib]}, {mod,{ecrn_app,[]}}, {licenses,["BSD"]}, {links,[{"Github","https://github.com/erlware/erlcron"}]}]}.
erlware/erlcron
e74f7c19aa2fa229fe201a23b8176548ce5d8e46
Add badges
diff --git a/README.md b/README.md index 7aaff58..fc249ea 100644 --- a/README.md +++ b/README.md @@ -1,208 +1,212 @@ Erlcron ======= +[![Build Status](https://github.com/erlware/erlcron/actions/workflows/ci.yml/badge.svg)](https://github.com/erlware/erlcron/actions/workflows/ci.yml) +[![Hex pm](https://img.shields.io/hexpm/v/erlcron.svg)](https://hex.pm/packages/erlcron) +[![Docs](https://img.shields.io/badge/hex-docs-green.svg?style=flat)](https://hexdocs.pm/erlcron) + Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The syntax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. Unlike cron's one-minute resolution, erlcron has a millisecond resolution. It does handle Daylight Savings Time changes (but not the cases when the system clock is altered by small increments, in which case the next execution of a scheduled task may be imprecise). Cron Job Description Examples: ```erlang {{once, {3, 30, pm}, fun() -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}, fun(JobRef, CurrDateTime) -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, fun(_JobRef, _DateTime) -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, {fun(_JobRef, _DateTime) -> io:fwrite("It's 2 Wednesday morning~n") end} {{weekly, [tue,wed], {2, am}}, {fun(_, Now) -> io:format("Now is ~p~n", [Now]) end} {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} {{monthly, [1, 7, 14], {2, am}}, {io, fwrite, ["Every 1st, 7th, 14th of the month!~n"]}} {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} {{monthly, [0, -1], {2, am}}, {io, fwrite, ["Last two days of the month!~n"]}} {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} %% Days of month less or equal to zero are subtracted from the end of the month {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} ``` Adding a cron to the system: ```erlang Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job). ``` Cron jobs can be given named atom references: ```erlang erlcron:cron(test_job1, {{once, {3,pm}}, {io, fwrite, "It's 3pm"}}). ``` A simple way to add a daily cron: erlcron:daily({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. ```erlang erlcron:at(300, Fun). ``` Cancel a running job. ```erlang erlcron:cancel(JobRef). ``` Get the current reference (universal) date time of the system. ```erlang erlcron:datetime(). ``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:set_datetime(DateTime). ``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(DateTime). ``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(Nodes, DateTime). ``` The application cron can be pre-configured through environment variables in the config file that all applications can load in the Erlang VM start. The app.config file can be as follow: ```erlang [ {erlcron, [ {crontab, [ {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, %% A job may be specified to be run only if the current host %% is in the list of given hostnames. If default crontab %% options are provided in the `defaults` setting, %% the job-specific options will override corresponding %% default options. See erlcron:job_opts() for available %% options. {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}, #{hostnames => ["somehost"]}, {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}}, %% A job spec can be defined as a map, where the `interval' and %% `execute' keys are mandatory: #{id => test_job, interval => {daily, {1, 0, pm}}, execute => {io, fwrite, ["Hello, world!~n"]}}, %% If defined as a map, the map can contain any `erlcron:job_opts()' %% options: #{id => another_job, interval => {daily, {1, 0, pm}}, execute => {io, fwrite, ["Hello, world!~n"]}, hostnames => ["myhost"]} ]}, %% Instead of specifying individual options for each job, you can %% define default options here. {defaults, #{ %% Limit jobs to run only on the given list of hosts hostnames => ["myhost"], %% Function `fun((Ref) -> ignore | any())` to call before a job is started. %% If the function returns `ignore`, the job will not be executed, and the %% `on_job_end` callback will not be executed. on_job_start => {some_module, function}, %% Function `fun((Ref, Status :: {ok, Result}|{error, {Reason, StackTrace}}) -> ok)` %% to call after a job has ended on_job_end => {some_module, function} }} ]} ]. ``` So, when the app will be started, all configurations will be loaded. Note that the limitation is that in the config file is impossible load an anonymous function (or lambda function) so, you only can use {M,F,A} format. If an `on_job_start` or `on_job_end` functions are provided for any job or as default settings, it's the responsibility of a developer to make sure that those functions handle exceptions, since the failure in those functions will cause the supervisor to restart the job up until the supervisor reaches its maximum restart intensity.
erlware/erlcron
7e056e84c4435536e132cdb595cb1c981a718171
Modify .gitignore
diff --git a/.gitignore b/.gitignore index 02d1d7a..343cfd8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ ebin/*.beam ebin/*.app -deps/* +deps/ +doc/ _build rebar3 TEST*.xml .deps_plt .eunit/ .rebar/
erlware/erlcron
2677fb7c495cbe91c12741352b83c19c25b09c9d
Add missing option
diff --git a/Makefile b/Makefile index d50621c..18e45d0 100644 --- a/Makefile +++ b/Makefile @@ -1,92 +1,92 @@ # Copyright Erlware, LLC. All Rights Reserved. # # This file is provided to you under the BSD License; you may not use # this file except in compliance with the License. You may obtain a # copy of the License. ERLFLAGS= -pa $(CURDIR)/.eunit -pa $(CURDIR)/ebin -pa $(CURDIR)/deps/*/ebin DEPS_PLT=$(CURDIR)/.deps_plt # ============================================================================= # Verify that the programs we need to run are installed on this system # ============================================================================= ERL = $(shell which erl) ifeq ($(ERL),) $(error "Erlang not available on this system") endif REBAR=$(shell which rebar3) ifeq ($(REBAR),) $(error "Rebar not available on this system") endif .PHONY: all compile doc clean test dialyzer typer shell distclean pdf \ get-deps escript clean-common-test-data rebuild all: compile dialyzer test # ============================================================================= # Rules to build the system # ============================================================================= get-deps: $(REBAR) get-deps $(REBAR) compile compile: $(REBAR) compile doc: $(REBAR) skip_deps=true doc eunit: compile clean-common-test-data $(REBAR) eunit ct: compile clean-common-test-data $(REBAR) ct test: compile eunit $(DEPS_PLT): @echo Building local plt at $(DEPS_PLT) @echo dialyzer --output_plt $(DEPS_PLT) --build_plt \ --apps erts kernel stdlib dialyzer: $(DEPS_PLT) $(REBAR) $@ typer: - typer --plt $(DEPS_PLT) -r ./src + typer --plt $(DEPS_PLT) -I include -r ./src shell: get-deps compile # You often want *rebuilt* rebar tests to be available to the # shell you have to call eunit (to get the tests # rebuilt). However, eunit runs the tests, which probably # fails (that's probably why You want them in the shell). This # runs eunit but tells make to ignore the result. - @$(REBAR) eunit @$(ERL) $(ERLFLAGS) pdf: pandoc README.md -o README.pdf clean-common-test-data: # We have to do this because of the unique way we generate test # data. Without this rebar eunit gets very confused @rm -rf $(CURDIR)/test/*_SUITE_data clean: clean-common-test-data - rm -rf $(CURDIR)/test/*.beam - rm -rf $(CURDIR)/{.eunit,_build,logs} - rm -fr TEST-* $(REBAR) clean distclean: clean - rm -rf $(DEPS_PLT) - rm -rvf $(CURDIR)/deps/* rebuild: distclean get-deps compile dialyzer test
erlware/erlcron
082bb334b3097dda3938c2bd8f0685e333c8819f
Adjust log format
diff --git a/rebar.config b/rebar.config index 047d793..75c5504 100644 --- a/rebar.config +++ b/rebar.config @@ -1,23 +1,25 @@ %% -*- mode: Erlang; fill-column: 80; comment-column: 75; -*- %% Dependencies ================================================================ {deps, []}. %% Rebar Plugins =============================================================== -{plugins, [{rebar3_git_vsn, {git, "https://github.com/saleyn/rebar3_git_vsn.git"}}]}. +{plugins, [{rebar3_git_vsn, + {git, "https://github.com/saleyn/rebar3_git_vsn.git", + {branch, "master"}}}]}. %% rebar3_git_vsn plugin: {provider_hooks, [{post, [{compile, git_vsn}]}]}. -{git_vsn, [{vsn_type, gitver}]}. +{git_vsn, [{vsn_type, gitver}, {env_key, ignore}]}. %% Compiler Options ============================================================ {erl_opts, [debug_info, warnings_as_errors]}. %% EUnit ======================================================================= {eunit_opts, [%verbose, %{report, {eunit_surefire, [{dir, "."}]}}]}. no_tty]}. {cover_enabled, true}. {cover_print_enabled, true}. diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index 06e35d9..947f4ef 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,79 +1,80 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). -include("erlcron.hrl"). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> %application:start(crypto), application:start(eunit), %application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> {ok, H} = inet:gethostname(), Def = application:get_env(erlcron, defaults, #{}), is_map(Def) orelse erlang:error("erlcron/defaults config must be a map!"), ?LOG_INFO("CRON: started on host ~p using defaults: ~1024p", [H, Def]), setup(Def), {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. setup(Def) -> case application:get_env(erlcron, crontab) of {ok, Crontab} -> lists:foreach(fun(CronJob) -> - Res = erlcron:cron(CronJob, Def), - ?LOG_INFO("CRON: adding job ~1024p: ~p", [CronJob, Res]), + Res = erlcron:cron(CronJob, Def), + Res2 = if is_reference(Res) -> io_lib:format(": ~p", [Res]); true -> [] end, + ?LOG_INFO("CRON: adding job ~1024p~s", [CronJob, Res2]), case Res of already_started -> erlang:error({duplicate_job_reference, CronJob}); ignored -> ok; Ref when is_reference(Ref); is_atom(Ref); is_binary(Ref) -> ok; {error, Reason} -> erlang:error({failed_to_add_cron_job, CronJob, Reason}) end end, Crontab); undefined -> ok end.
erlware/erlcron
c5ac2cea4fc8c42f5fa0455682638ca1f37e2234
Add startup logging and erlcron version
diff --git a/include/erlcron.hrl b/include/erlcron.hrl new file mode 100644 index 0000000..8fe3dba --- /dev/null +++ b/include/erlcron.hrl @@ -0,0 +1,12 @@ +%% compatibility +-ifdef(OTP_RELEASE). %% this implies 21 or higher +-define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). +-define(GET_STACK(Stacktrace), Stacktrace). +-include_lib("kernel/include/logger.hrl"). +-else. +-define(EXCEPTION(Class, Reason, _), Class:Reason). +-define(GET_STACK(_), erlang:get_stacktrace()). +-define(LOG_ERROR(Report), error_logger:error_report(Report)). +-define(LOG_WARNING(Report), error_logger:warning_report(Report)). +-define(LOG_INFO(Report), error_logger:info_report(Report)). +-endif. diff --git a/rebar.config b/rebar.config index 2b79657..047d793 100644 --- a/rebar.config +++ b/rebar.config @@ -1,19 +1,23 @@ %% -*- mode: Erlang; fill-column: 80; comment-column: 75; -*- %% Dependencies ================================================================ {deps, []}. %% Rebar Plugins =============================================================== -{plugins, []}. +{plugins, [{rebar3_git_vsn, {git, "https://github.com/saleyn/rebar3_git_vsn.git"}}]}. + +%% rebar3_git_vsn plugin: +{provider_hooks, [{post, [{compile, git_vsn}]}]}. +{git_vsn, [{vsn_type, gitver}]}. %% Compiler Options ============================================================ {erl_opts, [debug_info, warnings_as_errors]}. %% EUnit ======================================================================= {eunit_opts, [%verbose, %{report, {eunit_surefire, [{dir, "."}]}}]}. no_tty]}. {cover_enabled, true}. {cover_print_enabled, true}. diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 8c79480..24288b9 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,570 +1,560 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/3, cancel/1, next_run/1, get_datetime/1, get_datetime/2, set_datetime/3, set_datetime/4, recalculate/1, validate/1, until_next_time/2, normalize/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, opts, job_ref, ref_epoch, epoch_at_ref, fast_forward=false, last_time, next_run, % Time in EPOCH seconds until task's next execution last_run, % Time in EPOCH seconds when the task was last run orig_when }). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 1000). -define(MAX_TIMEOUT_SEC, 1800). -define(MAX_TIMEOUT_MSEC, 1800000). -define(SEC_IN_A_DAY, 86400). -%% compatibility --ifdef(OTP_RELEASE). %% this implies 21 or higher --define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). --define(GET_STACK(Stacktrace), Stacktrace). --include_lib("kernel/include/logger.hrl"). --else. --define(EXCEPTION(Class, Reason, _), Class:Reason). --define(GET_STACK(_), erlang:get_stacktrace()). --define(LOG_ERROR(Report), error_logger:error_report(Report)). --define(LOG_WARNING(Report), error_logger:warning_report(Report)). --endif. +-include("erlcron.hrl"). %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the appropriate job and the appropriate ref -spec start_link(erlcron:job_ref(), erlcron:job(), erlcron:job_opts()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, {When, _Task} = Job, JobOpts) when (is_reference(JobRef) orelse is_binary(JobRef)) , is_map(JobOpts) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link(?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec, JobOpts], []); start_link(JobRef, {When, _Task} = Job, JobOpts) when is_atom(JobRef), is_map(JobOpts) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link({local, JobRef}, ?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec, JobOpts], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> get_datetime(Pid, local). -spec get_datetime(pid(), local|universal) -> calendar:datetime(). get_datetime(Pid, local) -> erlang:universaltime_to_localtime(get_datetime(Pid, universal)); get_datetime(Pid, universal) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) when is_pid(Pid); is_atom(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> set_datetime(Pid, DateTime, Actual, local). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds(), UTC::local|universal) -> ok | {error, term()}. set_datetime(Pid, DateTime, Actual, UTC) -> DT = case UTC of local -> erlang:localtime_to_universaltime(DateTime); universal -> DateTime end, Res = gen_server:call(Pid, {set_datetime, DT, Actual}, infinity), Res. -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Get job's next execution time -spec next_run(pid()) -> erlang:timestamp(). next_run(Pid) -> gen_server:call(Pid, next_run). %% @doc %% Validate that a run_when spec specified is correct. -spec validate(erlcron:run_when()) -> ok | {error, term()}. validate(Spec) -> State = #state{job=undefined, job_ref=undefined}, {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), NewState = set_internal_time(State, DateTime, ActualMsec), try NormalSpec = normalize(Spec, DateTime), {Msec,_} = until_next_time(NewState#state{job={NormalSpec, undefined}}), Msec > 0 orelse throw({specified_time_past_seconds_ago, to_seconds(Msec)}), ok catch _Error:Reason -> {error, Reason} end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, {When, Task}, Sched, DateTime, ActualMsec, JobOpts]) -> try State = set_internal_time(#state{job_ref=JobRef, job={Sched, Task}, opts=JobOpts, last_run=0, next_run=0, orig_when=When}, DateTime, ActualMsec), case until_next_milliseconds(State) of {ok, {NewState, Timeout}} -> ecrn_reg:register(JobRef, self()), {ok, NewState, Timeout}; {error, {_, Reason}} -> throw(Reason) end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, JobRef}, {run_when, When}, {reason, E}, {stack, ?GET_STACK(ST)}]), {stop, normal} end. %% @private handle_call(next_run, _From, #state{next_run=Time} = State) -> reply_and_wait(Time, State); handle_call(get_datetime, _From, State) -> Epoch = ecrn_util:epoch_milliseconds(), Msec = current_epoch(Epoch, State), DT = to_universal_datetime(Msec), reply_and_wait(DT, State#state{last_time=Epoch}); handle_call({set_datetime, DateTime, CurrEpochMsec}, _From, State) -> try NewRefEpoch = to_milliseconds(erlang:universaltime_to_posixtime(DateTime)), case fast_forward(State#state{fast_forward=true}, NewRefEpoch, DateTime, 1) of true -> NewState = set_internal_time(State#state{next_run=0}, DateTime, CurrEpochMsec), reply_and_wait(ok, NewState); false -> {stop, normal, ok, State} end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, State#state.job_ref}, {run_when, element(1, State#state.orig_when)}, {reason, E}, {stack, ?GET_STACK(ST)}]), reply_and_wait({error, E}, State) end; handle_call(Msg, _From, State) -> {stop, State, {not_implemented, Msg}}. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast(Other, State) -> {stop, {not_implemented, Other}, State}. %% @private handle_info(timeout, S) -> process_timeout(S); handle_info({'EXIT', _, Reason}, State) -> {stop, Reason, State}; handle_info(_Msg, State) -> {noreply, State, 1000}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== normalize_when(When) -> {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), Sched = normalize(When, erlang:universaltime_to_localtime(DateTime)), {Sched, DateTime, ActualMsec}. process_timeout(#state{last_time=LastTime, next_run=NextRun, last_run=LastRun}=S) -> Epoch = ecrn_util:epoch_milliseconds(), NowMsec = current_epoch(Epoch, S), {Reply, State} = if LastTime < Epoch, NextRun > LastRun, NowMsec >= NextRun -> {do_job_run(S), S#state{last_run=NextRun, next_run=0}}; NextRun == LastRun -> S#state.fast_forward orelse timer:sleep(1), {noreply, S#state{next_run=0}}; true -> {noreply, S#state{last_time=Epoch}} end, reply_and_wait(Reply, State). do_job_run(#state{job_ref=Ref, next_run=Time, job={When, Job}, opts=Opts} = S) -> Res = do_job_start(Ref, maps:get(on_job_start, Opts, undefined)), Res /= ignore andalso execute(Job, Ref, Time, maps:get(on_job_end, Opts, undefined)), case When of {once, _} -> stop; _ -> S#state.fast_forward orelse timer:sleep(1), noreply end. do_job_start(_, undefined) -> ok; do_job_start(Ref, {M,F}) -> M:F(Ref); do_job_start(Ref, F) when is_function(F, 1) -> F(Ref). execute(Job, Ref, Time, OnEnd) when is_function(Job, 2) -> safe_spawn(Ref, fun() -> Job(Ref, Time) end, OnEnd); execute(Job, Ref, _, OnEnd) when is_function(Job, 0) -> safe_spawn(Ref, Job, OnEnd); execute({M, F}, Ref, Time, OnEnd) when is_atom(M), is_atom(F) -> %% The exported function is checked for arity 0 or 2 when the job is added case erlang:function_exported(M, F, 2) of true -> safe_spawn(Ref, fun() -> M:F(Ref, Time) end, OnEnd); false -> safe_spawn(Ref, fun() -> M:F() end, OnEnd) end; execute({M, F, A}, Ref, _Time, OnEnd) when is_atom(M), is_atom(F), is_list(A) -> safe_spawn(Ref, fun() -> apply(M, F, A) end, OnEnd). safe_spawn(Ref, Fun, _OnEnd = {M,F}) when is_atom(M), is_atom(F) -> safe_spawn(Ref, Fun, fun(JobRef, Res) -> M:F(JobRef, Res) end); safe_spawn(Ref, Fun, OnEnd) when is_function(OnEnd, 2) -> proc_lib:spawn(fun() -> try OnEnd(Ref, {ok, Fun()}) catch _:Reason:Stack -> OnEnd(Ref, {error, {Reason, Stack}}) end end); safe_spawn(_Ref, Fun, undefined) -> proc_lib:spawn(Fun). reply_and_wait(stop, State) -> {stop, normal, State}; reply_and_wait(Reply, #state{next_run=0} = State) -> reply_and_wait2(Reply, until_next_milliseconds(State)); reply_and_wait(Reply, #state{next_run=Next, last_run=Last} = State) when Next-Last =< 0 -> reply_and_wait2(Reply, {ok, {State, 1000}}); reply_and_wait(Reply, #state{last_time=Now, next_run=NextMsec} = State) -> NowTime = current_epoch(Now, State), Timeout = round_timeout(NextMsec-NowTime), reply_and_wait2(Reply, {ok, {State, Timeout}}). reply_and_wait2(noreply, {ok, {State, Timeout}}) -> {noreply, State, Timeout}; reply_and_wait2(Reply, {ok, {State, Timeout}}) -> {reply, Reply, State, Timeout}; reply_and_wait2(noreply, {error, {State, _}}) -> {stop, normal, State}; reply_and_wait2(Reply, {error, {State, _}}) -> {stop, normal, Reply, State}. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% The returned duration is set to the maximum of 1 hour at which %% point the duration is recalculated, so that daylight savings time %% adjustments don't affect the precision of when a task is run. -spec until_next_milliseconds(#state{}) -> {ok, {#state{}, erlcron:milliseconds()}} | {error, {#state{}, term()}}. until_next_milliseconds(#state{} = S) -> try Epoch = ecrn_util:epoch_milliseconds(), {Msec, S1} = until_next_time(S#state{last_time=Epoch}), {ok, update_next_run(S1, max(0, Msec))} catch ?EXCEPTION(_, E, ST) -> {error, {S, {E, ?GET_STACK(ST)}}} end. -spec update_next_run(#state{}, erlcron:seconds()) -> {#state{}, erlcron:milliseconds()}. update_next_run(#state{} = State, ?SEC_IN_A_DAY) -> {State, ?MAX_TIMEOUT_MSEC}; update_next_run(#state{last_time=Now} = State, Milliseconds) -> Timeout = round_timeout(Milliseconds), EpochS = current_epoch(Now, State), {State#state{next_run=EpochS+Milliseconds}, Timeout}. round_timeout(Milliseconds) -> trunc(max(0, min(Milliseconds, ?MAX_TIMEOUT_MSEC))). -type normalized_period() :: [{integer(), integer(), integer()}]. -type normalized_sched() :: {once, {relative|absolute, integer()}} | {daily, normalized_period()} | {weekly, [integer()], normalized_period()} | {monthly,integer(), normalized_period()}. -spec normalize(erlcron:run_when(), calendar:datetime()) -> normalized_sched(). normalize({once, I}, _) when is_integer(I) -> {once, {relative, to_milliseconds(I)}}; normalize({once, {H,M,S}=T}, {_, Time}) when is_integer(H), is_integer(M), is_integer(S) , H >= 0, H < 24, M >= 0, M < 59, S >= 0, S < 59 -> T < Time andalso throw({time_given_in_the_past, T}), {once, {absolute, resolve_time(T)}}; normalize({once, Period}, _) -> {once, {absolute, resolve_time(Period)}}; normalize({daily, Period}, _) -> {daily, lists:sort(resolve_period(Period))}; normalize({weekly, DoW, Period}, _) -> {weekly, resolve_dow(DoW), lists:sort(resolve_period(Period))}; normalize({monthly, Day, Period}, TodayDate) when is_integer(Day) -> normalize({monthly, [Day], Period}, TodayDate); normalize({monthly, Days, Period}=T, {{Y,M,_},_}) when is_list(Days) -> case [Day || Day <- Days, not is_integer(Day) orelse Day < -30 orelse Day > 31] of [] -> ok; _ -> throw({invalid_days_in_schedule, T}) end, {PosDays, NegDays} = lists:partition(fun(I) -> I > 0 end, Days), {ThisNextMonthDays, _State} = update_dom(Y,M, {undefined, {0,0, PosDays, NegDays}}, #state{job={T, undefined}}), {monthly, ThisNextMonthDays, lists:sort(resolve_period(Period))}; normalize(Other, _) -> throw({invalid_schedule, Other}). update_dom(Y,M, {_, {Y,M,_,_}}=When, State) -> {When, State}; update_dom(Y,M, {_, {_,_,PosDays,NegDays}}, State = #state{job = {{monthly, _, _Period}, Task}}) -> {_, _, ThisMonthDays} = month_days(Y, M, PosDays, NegDays, true), {NY,NM, NextMonFirstDay} = next_month_days(Y, M, PosDays, NegDays), ThisNextMonthDays = {ThisMonthDays, NY, NM, NextMonFirstDay}, When = {ThisNextMonthDays, {Y,M,PosDays,NegDays}}, {When, State#state{job={{monthly, When}, Task}}}. next_month_days(Y, 12, PosDays, NegDays) -> month_days(Y+1, 1, PosDays, NegDays, false); next_month_days(Y, M, [], NegDays) -> month_days(Y, M+1, [], NegDays, false); next_month_days(Y, M, PosDays, NegDays) -> % When checking next month, and PosDays contains days 29,30,31 % make sure that combining that with {Y,M} gives a valid date D = lists:min(PosDays), M1 = M+1, case calendar:valid_date({Y,M1,D}) of true -> month_days(Y, M1, PosDays, NegDays, false); false -> next_month_days(Y, M1, PosDays, NegDays) end. month_days(Y, M, PosDays, NegDays, false) -> LastDay = calendar:last_day_of_the_month(Y, M), Days = [I+LastDay || I <- NegDays] ++ PosDays, case [I || I <- Days, I =< LastDay, I > 0] of [] -> next_month_days(Y, M, PosDays, NegDays); L -> {Y, M, lists:min(L)} end; month_days(Y, M, PosDays, [], true) -> LastDay = calendar:last_day_of_the_month(Y, M), {Y, M, [I || I <- lists:sort(PosDays), I =< LastDay]}; month_days(Y, M, PosDays, NegDays, true) -> LastDay = calendar:last_day_of_the_month(Y, M), AllDays = PosDays ++ [I+LastDay || I <- NegDays], UniqDays= lists:sort(sets:to_list(sets:from_list(AllDays))), check_days(Y, M, UniqDays), {Y, M, [I || I <- UniqDays, I =< LastDay, I > 0]}. check_days(Y,M,Days) -> lists:foreach(fun(I) -> Date = {Y,M,I}, calendar:valid_date(Date) orelse throw({invalid_date, Date}) end, lists:takewhile(fun(I) -> I > 28 end, lists:reverse(Days))). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_time(erlcron:milliseconds(), erlcron:run_when()) -> erlcron:milliseconds(). until_next_time(NowEpochTime, Sched) when is_integer(NowEpochTime), is_tuple(Sched) -> DateTime = erlang:posixtime_to_universaltime(to_ceiling_seconds(NowEpochTime)), NormSched = normalize(Sched, DateTime), State = set_internal_time(#state{job={NormSched, undefined}}, DateTime, NowEpochTime), {Res, _State1} = until_next_time(State), Res. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% @private -spec until_next_time(state()) -> {erlcron:milliseconds(), state()}. until_next_time(State = #state{job={Sched, _Task}}) -> until_next_time2(State, Sched). until_next_time2(State, {once, {relative, Msec}}) when is_integer(Msec) -> {Msec, State}; until_next_time2(State, {once, {absolute, Msec}}) when is_integer(Msec) -> {normalize_to_relative(State, Msec), State}; until_next_time2(State, {daily, Period}) -> {until_next_daytime(State, Period, current_time(State)), State}; until_next_time2(State, {weekly, DoW, Period}) -> {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), Days = find_dow(Today, DoW), NextDays = fun() -> I = Today+1, N = if I>7 -> 1; true -> I end, find_dow(N, DoW) end, {until_next_time_from_now(State, Period, Days, NextDays), State}; until_next_time2(State, {monthly, When, Period}) -> {{ThisYear, ThisMonth, Today}=YMD, _} = current_date(State), {{{ThisMonthDays, NextY, NextM, NextMonthFirstDOM}, _}, State1} = update_dom(ThisYear, ThisMonth, When, State), {YMD1, YMD2} = case lists:dropwhile(fun(I) -> I < Today end, ThisMonthDays) of [DOM1, DOM2 | _] -> {{ThisYear,ThisMonth,DOM1}, {ThisYear,ThisMonth,DOM2}}; [DOM|_] -> {{ThisYear,ThisMonth,DOM}, {NextY,NextM,NextMonthFirstDOM}}; [] -> {{NextY, NextM, NextMonthFirstDOM}, {0,0,0}} end, TodayGreg = to_greg_days(YMD), NextGreg = to_greg_days(YMD1), Days = NextGreg - TodayGreg, NextDays = fun() -> to_greg_days(YMD2) - TodayGreg end, {until_next_time_from_now(State1, Period, Days, NextDays), State1}. until_next_time_from_now(State, Period, 0, NextDays) when is_function(NextDays, 0) -> CurrentTime = current_time(State), F = fun() -> until_days_from_now(State, Period, NextDays()) end, case last_time(Period) of T when CurrentTime > T -> F(); _ -> EndTime = last_time(Period), case next_time(Period, CurrentTime) of I when I > EndTime -> F(); I -> I - CurrentTime end end; until_next_time_from_now(State, Period, Days, _NextDays) when Days > 0 -> until_days_from_now(State, Period, Days-1). to_greg_days({Y,M,D}) -> calendar:date_to_gregorian_days(Y,M,D). %% @doc Calculates the time since midnight in milliseconds until the next time this %% period is to occur during the day. -spec until_next_daytime(state(), normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_next_daytime(State, Period, MsecsFromMidnight) -> StartTime = first_time(Period), EndTime = last_time(Period), if MsecsFromMidnight > EndTime -> until_tomorrow(State, StartTime); true -> case next_time(Period, MsecsFromMidnight) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> T - MsecsFromMidnight end end. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow(state(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_tomorrow(State, StartTime) -> StartTime + 24*3600000 - current_time(State). %% @doc Calculates the duration in milliseconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), normalized_period(), integer()) -> erlcron:milliseconds(). until_days_from_now(State, Period, Days) -> MsecsUntilTomorrow = until_tomorrow(State, 0), MsecsUntilTomorrow + Days * 24 * 3600000 + until_next_daytime(State, Period, 0). %% @doc Calculates the first time in a given period. -spec first_time(normalized_period()) -> erlcron:milliseconds(). first_time([]) -> ?SEC_IN_A_DAY; first_time([{FromTime, _ToTime, _RepeatSec}|_]) -> FromTime. %% @doc Calculates the last time in a given period. -spec last_time(normalized_period()) -> erlcron:milliseconds(). last_time([]) -> ?SEC_IN_A_DAY; last_time(Period) when is_list(Period) -> F = fun({FromTime, _ToTime, 0}) -> FromTime; ({FromTime, ToTime, RepeatSec}) -> FromTime + ((ToTime-FromTime) div RepeatSec) * RepeatSec end, lists:max([F(R) || R <- Period]). %% @doc Calculates the first time in the given period after the given time. -spec next_time(normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). next_time([], _Time) -> ?SEC_IN_A_DAY; next_time(Period, Time) when is_list(Period), is_integer(Time) -> F = fun({FromTime, _ToTime, _RepeatSec}) when Time =< FromTime -> FromTime; ({_FromTime, _ToTime, 0}) -> ?SEC_IN_A_DAY; ({FromTime, _ToTime, RepeatSec}) -> A1 = ((Time-FromTime) div RepeatSec) * RepeatSec, A = if A1 < Time -> A1 + RepeatSec; true -> A1 end, FromTime + A end, case [F(R) || R = {_, ToTm, _} <- Period, Time =< ToTm] of [] -> ?SEC_IN_A_DAY; LL -> lists:min(LL) end. %% @doc Returns the current time, in milliseconds past midnight in local time zone. -spec current_time(state()) -> erlcron:milliseconds(). current_time(State = #state{last_time=Now}) -> % Take ceiling of time to the next second Msec = case (Now div 1000) * 1000 of Now -> 0; N -> Now-N end, {_, {H,M,S}} = current_date(State), to_milliseconds(S + M * 60 + H * 3600) + Msec. %% @doc Returns current date in local time current_date(#state{last_time=Now, ref_epoch=E, epoch_at_ref=S}) when is_integer(Now), Now > 0 -> Elapsed = Now - S, to_local_datetime(Elapsed + E). diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index bbd7098..06e35d9 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,73 +1,79 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). +-include("erlcron.hrl"). + %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> %application:start(crypto), application:start(eunit), %application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> - setup(), + {ok, H} = inet:gethostname(), + Def = application:get_env(erlcron, defaults, #{}), + is_map(Def) orelse + erlang:error("erlcron/defaults config must be a map!"), + ?LOG_INFO("CRON: started on host ~p using defaults: ~1024p", [H, Def]), + setup(Def), {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. -setup() -> +setup(Def) -> case application:get_env(erlcron, crontab) of {ok, Crontab} -> - Def = application:get_env(erlcron, defaults, #{}), - is_map(Def) orelse - erlang:error("erlcron/defaults config must be a map!"), lists:foreach(fun(CronJob) -> - case erlcron:cron(CronJob, Def) of + Res = erlcron:cron(CronJob, Def), + ?LOG_INFO("CRON: adding job ~1024p: ~p", [CronJob, Res]), + case Res of already_started -> erlang:error({duplicate_job_reference, CronJob}); ignored -> ok; Ref when is_reference(Ref); is_atom(Ref); is_binary(Ref) -> ok; {error, Reason} -> erlang:error({failed_to_add_cron_job, CronJob, Reason}) end end, Crontab); undefined -> ok end.
erlware/erlcron
058e3da1e520517acc501cdd6e8998e75555161a
Add more tests
diff --git a/test/ecrn_startup_test.erl b/test/ecrn_startup_test.erl index bbc6b53..b9deb1e 100644 --- a/test/ecrn_startup_test.erl +++ b/test/ecrn_startup_test.erl @@ -1,118 +1,132 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% vim:ts=4:ts=4:et %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_startup_test). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). disable_sasl_logger() -> logger:add_handler_filter(default, ?MODULE, {fun(_,_) -> stop end, nostate}). enable_sasl_logger() -> logger:remove_handler_filter(default, ?MODULE). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> Ref = make_ref(), application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), application:set_env(erlcron, crontab, [ {{daily, {1, 0, pm}}, {erlang, system_time, []}, #{id => one}}, {{daily, {2, 0, pm}}, fun() -> erlang:system_time() end, #{id => <<"two">>}}, {{daily, {3, 0, pm}}, fun(_JobRef, _Now) -> erlang:system_time() end, #{id => Ref}}, #{id => four, interval => {daily, {1, 0, pm}}, execute => {erlang, system_time, []}} ]), disable_sasl_logger(), application:start(erlcron), Ref end, fun(_) -> application:stop(erlcron), enable_sasl_logger() end, {with, [fun(Ref) -> check_startup_jobs(Ref) end]} }. check_startup_jobs(Ref) -> ?assertMatch([_, _, _, _], ecrn_cron_sup:all_jobs()), ?assertEqual([four, one, Ref, <<"two">>], ecrn_reg:get_all_refs()), ?assert(is_pid(ecrn_reg:get(one))), ?assert(is_pid(ecrn_reg:get(<<"two">>))), ?assert(is_pid(ecrn_reg:get(Ref))), ?assert(is_pid(ecrn_reg:get(four))). cron_bad_job_spec_test_() -> {setup, fun() -> application:set_env(sasl, sasl_error_logger, false), application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), disable_sasl_logger() end, fun(_) -> enable_sasl_logger() end, [ ?_assertMatch( {error, {bad_return, {{ecrn_app,start,[normal,[]]}, {'EXIT', {{module_not_loaded,one, {'$$$bad_module',system_time,[]}, nofile}, [_|_]}}}}}, begin application:set_env(erlcron, crontab, [ {{daily, {1, 0, pm}}, {'$$$bad_module', system_time, []}, #{id => one}} ]), application:start(erlcron) end), ?_assertMatch( {error, {bad_return, {{ecrn_app,start,[normal,[]]}, {'EXIT', {{wrong_arity_of_job_task, one, "erlang:system_time1000/0"}, [_|_]}}}}}, begin application:set_env(erlcron, crontab, [ {{daily, {1, 0, pm}}, {erlang, system_time1000, []}, #{id => one}} ]), application:start(erlcron) end), ?_assertMatch( {error, {bad_return, {{ecrn_app,start,[normal,[]]}, {'EXIT', {{wrong_arity_of_job_task, one, "erlang:system_time/3"}, [_|_]}}}}}, begin application:set_env(erlcron, crontab, [ {{daily, {1, 0, pm}}, {erlang, system_time, [1,2,3]}, #{id => one}} ]), application:start(erlcron) end), ?_assertMatch( {error, {bad_return, {{ecrn_app,start,[normal,[]]}, {'EXIT', {{wrong_arity_of_job_task, one, "erlang:system_time123/[0,2]"}, [_|_]}}}}}, begin application:set_env(erlcron, crontab, [ {{daily, {1, 0, pm}}, {erlang, system_time123}, #{id => one}} ]), application:start(erlcron) + end), + ?_assertMatch( + ignored, + erlcron:cron({{daily, {1, 0, pm}}, {'$$$bad_module', system_time, []}, + #{id => ignore_host, hostnames => [<<"$$somehost">>]}}) + ), + ?_assertMatch( + ok, + begin + application:set_env(erlcron, crontab, [ + {{daily, {1, 0, pm}}, {'$$$bad_module', system_time, []}, + #{id => ignore_host, hostnames => [<<"$$somehost">>]}} + ]), + application:start(erlcron) end) ] }.
erlware/erlcron
edca1f55c259743177135a2929a125c6e1b5e162
Improve test cases and change to use rebar3
diff --git a/Makefile b/Makefile index 349d3de..d50621c 100644 --- a/Makefile +++ b/Makefile @@ -1,92 +1,92 @@ # Copyright Erlware, LLC. All Rights Reserved. # # This file is provided to you under the BSD License; you may not use # this file except in compliance with the License. You may obtain a # copy of the License. ERLFLAGS= -pa $(CURDIR)/.eunit -pa $(CURDIR)/ebin -pa $(CURDIR)/deps/*/ebin DEPS_PLT=$(CURDIR)/.deps_plt # ============================================================================= # Verify that the programs we need to run are installed on this system # ============================================================================= ERL = $(shell which erl) ifeq ($(ERL),) $(error "Erlang not available on this system") endif -REBAR=$(shell which rebar) +REBAR=$(shell which rebar3) ifeq ($(REBAR),) $(error "Rebar not available on this system") endif .PHONY: all compile doc clean test dialyzer typer shell distclean pdf \ get-deps escript clean-common-test-data rebuild all: compile dialyzer test # ============================================================================= # Rules to build the system # ============================================================================= get-deps: $(REBAR) get-deps $(REBAR) compile compile: - $(REBAR) skip_deps=true compile + $(REBAR) compile doc: $(REBAR) skip_deps=true doc eunit: compile clean-common-test-data - $(REBAR) skip_deps=true eunit + $(REBAR) eunit ct: compile clean-common-test-data - $(REBAR) skip_deps=true ct + $(REBAR) ct -test: compile eunit ct +test: compile eunit $(DEPS_PLT): @echo Building local plt at $(DEPS_PLT) @echo dialyzer --output_plt $(DEPS_PLT) --build_plt \ --apps erts kernel stdlib dialyzer: $(DEPS_PLT) - dialyzer --plt $(DEPS_PLT) --fullpath \ - -pa $(CURDIR)/ebin --src src + $(REBAR) $@ typer: typer --plt $(DEPS_PLT) -r ./src shell: get-deps compile # You often want *rebuilt* rebar tests to be available to the # shell you have to call eunit (to get the tests # rebuilt). However, eunit runs the tests, which probably # fails (that's probably why You want them in the shell). This # runs eunit but tells make to ignore the result. - - @$(REBAR) skip_deps=true eunit + - @$(REBAR) eunit @$(ERL) $(ERLFLAGS) pdf: pandoc README.md -o README.pdf clean-common-test-data: # We have to do this because of the unique way we generate test # data. Without this rebar eunit gets very confused - - rm -rf $(CURDIR)/test/*_SUITE_data + @rm -rf $(CURDIR)/test/*_SUITE_data clean: clean-common-test-data - rm -rf $(CURDIR)/test/*.beam - - rm -rf $(CURDIR)/logs - $(REBAR) skip_deps=true clean + - rm -rf $(CURDIR)/{.eunit,_build,logs} + - rm -fr TEST-* + $(REBAR) clean distclean: clean - rm -rf $(DEPS_PLT) - rm -rvf $(CURDIR)/deps/* rebuild: distclean get-deps compile dialyzer test diff --git a/rebar.config b/rebar.config index 85f36dd..2b79657 100644 --- a/rebar.config +++ b/rebar.config @@ -1,18 +1,19 @@ %% -*- mode: Erlang; fill-column: 80; comment-column: 75; -*- %% Dependencies ================================================================ {deps, []}. %% Rebar Plugins =============================================================== {plugins, []}. %% Compiler Options ============================================================ {erl_opts, [debug_info, warnings_as_errors]}. %% EUnit ======================================================================= -{eunit_opts, [verbose, - {report, {eunit_surefire, [{dir, "."}]}}]}. +{eunit_opts, [%verbose, + %{report, {eunit_surefire, [{dir, "."}]}}]}. + no_tty]}. {cover_enabled, true}. {cover_print_enabled, true}. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index 5dbf3a2..645dba4 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,180 +1,200 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2, add_job/3, all_jobs/0, terminate/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). add_job(JobRef, Job) -> add_job(JobRef, Job, #{}). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job(), erlcron:cron_opts()) -> erlcron:job_ref() | ignored | already_started | {error, term()}. add_job(JobRef, Job = #{}, CronOpts) when is_map(CronOpts) -> {JobSpec, JobOpts} = parse_job(Job), add_job2(JobRef, JobSpec, check_opts(JobRef, maps:merge(CronOpts, JobOpts))); add_job(JobRef, Job = {_, _Task}, CronOpts) when is_map(CronOpts) -> add_job2(JobRef, Job, check_opts(JobRef, CronOpts)); add_job(JobRef, {When, Task, JobOpts}, CronOpts) when is_map(JobOpts) -> add_job2(JobRef, {When, Task}, check_opts(JobRef, maps:merge(CronOpts, JobOpts))). add_job2(JobRef, Job = {_, Task}, Opts) -> case check_host(Opts) of true -> check_task(JobRef, Task), case supervisor:start_child(?SERVER, [JobRef, Job, Opts]) of {ok, _} -> JobRef; {error, {already_started, _}} -> already_started; Other -> Other end; false -> ignored end. get_opt(Opt, Map) -> case maps:take(Opt, Map) of {V, Map1} -> {V, Map1}; error -> erlang:error({missing_job_option, Opt, Map}) end. parse_job(Job) -> {When, Opts1} = get_opt(interval, Job), {Fun, Opts2} = get_opt(execute, Opts1), {{When, Fun}, Opts2}. %% @doc %% Get a list of all active jobs -spec all_jobs() -> [pid()]. all_jobs() -> [P || {_,P,_,_} <- supervisor:which_children(?SERVER)]. %% @doc %% Terminate a job terminate(Pid) when is_pid(Pid) -> supervisor:terminate_child(?SERVER, Pid). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> SupFlags = #{ strategy => simple_one_for_one, intensity => application:get_env(erlcron, sup_job_intensity, 3), period => application:get_env(erlcron, sup_job_period, 10) }, AChild = #{id => ecrn_agent, start => {ecrn_agent, start_link, []}, restart => transient, shutdown => brutal_kill, type => worker, modules => [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== check_opts(JobRef, Map) -> maps:foreach(fun (hostnames, L) when is_list(L) -> ok; (on_job_start, MF) when tuple_size(MF)==2; is_function(MF, 1) -> ok; (on_job_end, MF) when tuple_size(MF)==2; is_function(MF, 2) -> ok; (id, ID) when is_atom(ID); is_binary(ID); is_reference(ID) -> ok; (K, V) -> - erlang:error({invalid_option_value, JobRef, {K, V}}) + Info = + if is_function(V) -> + [Name, Arity, Mod, Env0] = + [element(2, erlang:fun_info(V, I)) || I <- [name, arity, module, env]], + Fun = lists:flatten(io_lib:format("~w/~w", [Name, Arity])), + case Env0 of + [T|_] when is_tuple(T) -> + {Mod, element(1,T), Fun}; %% {Module, {Line, Pos}, Fun} + _ -> + {Mod, Fun} + end; + true -> + V + end, + erlang:error({invalid_option_value, JobRef, {K, Info}}) end, Map), Map. check_host(Opts) -> case maps:find(hostnames, Opts) of {ok, Hosts} when is_list(Hosts) -> {ok, Host} = inet:gethostname(), lists:member(Host, [to_list(H) || H <- Hosts]); error -> true end. check_task(JobRef, Task) when is_tuple(Task), (tuple_size(Task)==2 orelse tuple_size(Task)==3) -> M = element(1, Task), case code:ensure_loaded(M) of {module, M} -> ok; {error, Err1} -> erlang:error({module_not_loaded, JobRef, Task, Err1}) end, check_exists(JobRef, Task); check_task(_, Task) when is_function(Task, 0) -> ok; check_task(_, Task) when is_function(Task, 2) -> ok; check_task(JobRef, Task) -> erlang:error({invalid_job_task, JobRef, Task}). check_exists(JobRef, {M,F}) -> check_exists2(JobRef, {M,F,undefined}); check_exists(JobRef, {_,_,A} = MFA) when is_list(A) -> check_exists2(JobRef, MFA). check_exists2(JobRef, {M,F,A} = Task) -> case erlang:module_loaded(M) of false -> case code:ensure_loaded(M) of {module, M} -> ok; {error, Err1} -> erlang:error({module_not_loaded, JobRef, Task, Err1}) end; true -> ok end, case A of undefined -> check_arity(JobRef, M, F, [0,2]); _ when is_list(A) -> check_arity(JobRef, M, F, [length(A)]) end. check_arity(JobRef, M, F, Lengths) -> {module, M} == code:ensure_loaded(M) orelse erlang:error({job_task_module_not_loaded, JobRef, M}), lists:any(fun(Arity) -> erlang:function_exported(M,F,Arity) end, Lengths) - orelse erlang:error({wrong_arity_of_job_task, JobRef, {M,F,Lengths}}). + orelse erlang:error({wrong_arity_of_job_task, JobRef, report_arity(M,F,Lengths)}). + +report_arity(M, F, [A]) -> + lists:flatten(io_lib:format("~w:~w/~w", [M, F, A])); +report_arity(M, F, A) when is_list(A) -> + Arities = string:join([integer_to_list(I) || I <- A], ","), + lists:flatten(io_lib:format("~w:~w/[~s]", [M, F, Arities])). to_list(H) when is_binary(H) -> binary_to_list(H); to_list(H) when is_list(H) -> H. diff --git a/test/ecrn_startup_test.erl b/test/ecrn_startup_test.erl index ff8d742..bbc6b53 100644 --- a/test/ecrn_startup_test.erl +++ b/test/ecrn_startup_test.erl @@ -1,44 +1,118 @@ %%% @copyright Erlware, LLC. All Rights Reserved. +%%% vim:ts=4:ts=4:et %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_startup_test). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). +disable_sasl_logger() -> + logger:add_handler_filter(default, ?MODULE, {fun(_,_) -> stop end, nostate}). + +enable_sasl_logger() -> + logger:remove_handler_filter(default, ?MODULE). + %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> Ref = make_ref(), application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), application:set_env(erlcron, crontab, [ {{daily, {1, 0, pm}}, {erlang, system_time, []}, #{id => one}}, {{daily, {2, 0, pm}}, fun() -> erlang:system_time() end, #{id => <<"two">>}}, {{daily, {3, 0, pm}}, fun(_JobRef, _Now) -> erlang:system_time() end, #{id => Ref}}, #{id => four, interval => {daily, {1, 0, pm}}, execute => {erlang, system_time, []}} ]), + disable_sasl_logger(), application:start(erlcron), Ref end, fun(_) -> - application:stop(erlcron) + application:stop(erlcron), + enable_sasl_logger() end, {with, [fun(Ref) -> check_startup_jobs(Ref) end]} }. check_startup_jobs(Ref) -> ?assertMatch([_, _, _, _], ecrn_cron_sup:all_jobs()), ?assertEqual([four, one, Ref, <<"two">>], ecrn_reg:get_all_refs()), ?assert(is_pid(ecrn_reg:get(one))), ?assert(is_pid(ecrn_reg:get(<<"two">>))), ?assert(is_pid(ecrn_reg:get(Ref))), ?assert(is_pid(ecrn_reg:get(four))). + +cron_bad_job_spec_test_() -> + {setup, + fun() -> + application:set_env(sasl, sasl_error_logger, false), + application:load(erlcron), + application:set_env(erlcron, sup_intensity, 0), + application:set_env(erlcron, sup_period, 1), + disable_sasl_logger() + end, + fun(_) -> + enable_sasl_logger() + end, + [ + ?_assertMatch( + {error, + {bad_return, {{ecrn_app,start,[normal,[]]}, + {'EXIT', {{module_not_loaded,one, {'$$$bad_module',system_time,[]}, nofile}, [_|_]}}}}}, + begin + application:set_env(erlcron, crontab, [ + {{daily, {1, 0, pm}}, {'$$$bad_module', system_time, []}, #{id => one}} + ]), + application:start(erlcron) + end), + ?_assertMatch( + {error, + {bad_return, + {{ecrn_app,start,[normal,[]]}, + {'EXIT', + {{wrong_arity_of_job_task, one, "erlang:system_time1000/0"}, + [_|_]}}}}}, + begin + application:set_env(erlcron, crontab, [ + {{daily, {1, 0, pm}}, {erlang, system_time1000, []}, #{id => one}} + ]), + application:start(erlcron) + end), + ?_assertMatch( + {error, + {bad_return, + {{ecrn_app,start,[normal,[]]}, + {'EXIT', + {{wrong_arity_of_job_task, one, "erlang:system_time/3"}, + [_|_]}}}}}, + begin + application:set_env(erlcron, crontab, [ + {{daily, {1, 0, pm}}, {erlang, system_time, [1,2,3]}, #{id => one}} + ]), + application:start(erlcron) + end), + ?_assertMatch( + {error, + {bad_return, + {{ecrn_app,start,[normal,[]]}, + {'EXIT', + {{wrong_arity_of_job_task, one, "erlang:system_time123/[0,2]"}, + [_|_]}}}}}, + begin + application:set_env(erlcron, crontab, [ + {{daily, {1, 0, pm}}, {erlang, system_time123}, #{id => one}} + ]), + application:start(erlcron) + end) + ] + }. diff --git a/test/ecrn_test.erl b/test/ecrn_test.erl index dfa6e77..85cf00a 100644 --- a/test/ecrn_test.erl +++ b/test/ecrn_test.erl @@ -1,273 +1,293 @@ %%% @copyright Erlware, LLC. All Rights Reserved. +%%% vim:ts=4:ts=4:et %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_test). -compile(export_all). -compile(nowarn_export_all). +-import(ecrn_startup_test, [disable_sasl_logger/0, enable_sasl_logger/0]). + -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> - application:load(erlcron), - application:set_env(erlcron, sup_intensity, 0), - application:set_env(erlcron, sup_period, 1), - application:start(erlcron) + application:load(erlcron), + application:set_env(erlcron, sup_intensity, 0), + application:set_env(erlcron, sup_period, 1), + application:unset_env(erlcron, crontab), + disable_sasl_logger(), + application:start(erlcron) end, fun(_) -> - application:stop(erlcron) + application:stop(erlcron), + enable_sasl_logger() end, [{timeout, 30, [ ?FuncTest(set_alarm), - ?FuncTest(start_stop_funs), + ?FuncTest(start_stop_fun1), + ?FuncTest(start_stop_fun2), + ?FuncTest(start_stop_fun3), ?FuncTest(travel_back_in_time), ?FuncTest(cancel_alarm), ?FuncTest(big_time_jump), ?FuncTest(cron), ?FuncTest(cron_run_job_on_host), ?FuncTest(cron_skip_job_on_host), ?FuncTest(validation) ]}, {timeout, 30, [ ?FuncTest(weekly) ]}, {timeout, 30, [ ?FuncTest(weekly_every) ]} ]}. set_alarm() -> erlcron:set_datetime({{2000,1,1},{8,0,0}}), Self = self(), erlcron:at(test1, {9,0,0}, fun() -> Self ! ack1 end), erlcron:at(test2, {9,0,1}, fun() -> Self ! ack2 end), erlcron:daily(test3, {every, {1,s}, {between, {9,0,2}, {9,0,4}}}, fun() -> Self ! ack3 end), erlcron:set_datetime({{2000,1,1},{8,59,59}}), %% The alarm should trigger this nearly immediately. ?assertMatch(1, collect(ack1, 1500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(1, collect(ack2, 2500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(3, collect(ack3, 3000, 3)), erlcron:cancel(test3). cancel_alarm() -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(0, collect(ack, 125, 1)). -start_stop_funs() -> +start_stop_fun1() -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {8,0,1}, Self = self(), Opts = #{on_job_start => fun(Ref) -> Self ! {start, Ref} end, on_job_end => fun(Ref, Res) -> Self ! {finish, Ref, Res} end}, Ref1 = erlcron:at(test1, AlarmTimeOfDay, fun(_, _) -> Self ! ack, 1234 end, Opts), ?assertEqual(test1, Ref1), ?assertMatch(1, collect({start, test1}, 1500, 1)), ?assertMatch(1, collect(ack, 125, 1)), - ?assertMatch(1, collect({finish, test1, {ok, 1234}}, 1500, 1)), + ?assertMatch(1, collect({finish, test1, {ok, 1234}}, 1500, 1)). +start_stop_fun2() -> + Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), + AlarmTimeOfDay = {8,0,1}, + + Self = self(), Opts2 = #{on_job_start => fun(Ref) -> Self ! {ignored, Ref}, ignore end, on_job_end => fun(Ref, Res) -> Self ! {finish, Ref, Res} end}, Ref2 = erlcron:at(test2, AlarmTimeOfDay, fun(_, _) -> timer:sleep(60000), Self ! ack, 1000 end, Opts2), ?assertEqual(test2, Ref2), ?assertMatch(1, collect({ignored, test2}, 1500, 1)), ?assertMatch(0, collect({finish, test2, {ok, 1000}}, 125, 1)), - ?assertEqual(undefined, ecrn_reg:get(test2)), + ?assertEqual(undefined, ecrn_reg:get(test2)). +start_stop_fun3() -> + Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), + AlarmTimeOfDay = {8,0,1}, + + Self = self(), + Opts = #{on_job_start => fun(Ref) -> Self ! {start, Ref} end, + on_job_end => fun(Ref, Res) -> Self ! {finish, Ref, Res} end}, Len3 = length(lists:seq(1, rand:uniform(10)+2)), Ref3 = erlcron:at(test3, AlarmTimeOfDay, fun(_, _) -> 1 = Len3 end, Opts), ?assertEqual(test3, Ref3), ?assertMatch(1, collect({start, test3}, 1500, 1)), ?assertMatch(0, collect(1, 125, 1)), ?assertMatch({finish, test3, {error,{{badmatch, _}, [_|_]}}}, receive _M -> _M after 1500 -> timeout end). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump() -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:daily(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:daily(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)). travel_back_in_time() -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past, universal), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assertMatch(true, ExpectedSeconds =< calendar:datetime_to_gregorian_seconds(Past)), ?assertMatch(true, ExpectedSeconds < Seconds). cron() -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,59}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Ref1 = make_ref(), Job1 = {{daily, {3, 30, pm}}, fun(Ref, _) -> Self ! {ack, Ref} end}, Ref1 = erlcron:cron(Ref1, Job1), Job2 = {{daily, {3, 30, pm}}, fun(Ref, _) -> Self ! {ack, Ref} end}, test2 = erlcron:cron(test2, Job2), Job3 = {{daily, {3, 30, pm}}, fun() -> Self ! {ack, test3} end}, test3 = erlcron:cron(test3, Job3), Job4 = {{daily, {3, 30, pm}}, {?MODULE, sample_arity0}, #{on_job_end => fun(Ref, {ok, undefined}) -> Self ! {ack, Ref} end}}, test4 = erlcron:cron(test4, Job4), Job5 = {{daily, {3, 30, pm}}, {?MODULE, sample_arity2}, #{on_job_end => fun(_Ref, {ok, Res}) -> Self ! Res end}}, test5 = erlcron:cron(test5, Job5), Job6 = {{daily, {3, 30, pm}}, {?MODULE, sample_arityN, [test6, Self]}}, test6 = erlcron:cron(test6, Job6), ?assertMatch(1, collect({ack, Ref1}, 1000, 1)), ?assertMatch(1, collect({ack, test2}, 1000, 1)), ?assertMatch(1, collect({ack, test3}, 1000, 1)), ?assertMatch(1, collect({ack, test4}, 1000, 1)), ?assertMatch(1, collect({ack, test5}, 1000, 1)), ?assertMatch(1, collect({ack, test6}, 1000, 1)). sample_arity0() -> undefined. sample_arity2(Ref, _) -> {ack, Ref}. sample_arityN(Ref, Pid) -> Pid ! {ack, Ref}. %% Run job on this host cron_run_job_on_host() -> {ok, Host} = inet:gethostname(), erlcron:set_datetime({{2000, 1, 1}, {12, 59, 59}}), Self = self(), Ref = make_ref(), Job = {{once, {1, 00, pm}}, fun(_,_) -> Self ! Ref end, #{hostnames => [Host]}}, ?assert(is_reference(erlcron:cron(Job))), ?assertMatch(1, collect(Ref, 2500, 1)). %% Don't add job when executed on a disallowed host cron_skip_job_on_host() -> {ok, Host} = inet:gethostname(), Self = self(), Ref = make_ref(), Job = {{once, {1, 00, pm}}, fun(_,_) -> Self ! Ref end, #{hostnames => [Host ++ "123"]}}, ?assertEqual(ignored, erlcron:cron(Job)). validation() -> erlcron:set_datetime({{2000,1,1}, {15,0,0}}), ?assertMatch(ok, ecrn_agent:validate({once, {3, 30, pm}})), erlcron:set_datetime({{2000,1,1}, {15,31,0}}), ?assertMatch({error,{specified_time_past_seconds_ago, -60}}, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({once, 3600})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {0,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,sec}, {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, fri, {every, {5,sec}}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 4, {2, am}})), ?assertMatch({error,{invalid_time,{55,22,am}}}, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch({error,{invalid_days_in_schedule,{monthly,"A",{55,am}}}}, ecrn_agent:validate({monthly, 65, {55, am}})). weekly() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, sun], {9,0,0}}, fun() -> Self ! weekly end}), Pattern = [1, 1, 0, 0, 0, 0, 0, 1], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). weekly_every() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, mon], {every, {29, sec}, {between, {9, 0, 0}, {9, 1, 0}}}}, fun() -> Self ! weekly end}), Pattern = [3, 0, 3, 0, 0, 0, 0, 3], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). %%%=================================================================== %%% Internal Functions %%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). collect(Msg, Timeout, Count) -> collect(Msg, Timeout, 0, Count). collect(_Msg, _Timeout, Count, Count) -> Count; collect(Msg, Timeout, I, Count) -> receive Msg -> collect(Msg, Timeout, I+1, Count) after Timeout -> I end. % check that for each day generated by DateF(I) for increasing I, Pattern[I] % weekly messages are received collect_weekly(DateF, TimeBefore, TimeAfter, Pattern) -> collect_weekly(DateF, TimeBefore, TimeAfter, Pattern, 0). collect_weekly(DateF, TimeBefore, TimeAfter, [N | PatternTail], I) -> erlcron:set_datetime({DateF(I), TimeBefore}), ?assertMatch(0, collect(weekly, 1000, 1)), erlcron:set_datetime({DateF(I), TimeAfter}), ?assertMatch(N, collect(weekly, 1000, N)), collect_weekly(DateF, TimeBefore, TimeAfter, PatternTail, I+1); collect_weekly(_DateF, _TimeBefore, _TimeAfter, [], _I) -> ok.
erlware/erlcron
dfec5607218e33e0dad3832fdca9f19ff375c00e
Fix startup issue
diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index 649193e..5dbf3a2 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,178 +1,180 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2, add_job/3, all_jobs/0, terminate/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). add_job(JobRef, Job) -> add_job(JobRef, Job, #{}). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job(), erlcron:cron_opts()) -> erlcron:job_ref() | ignored | already_started | {error, term()}. add_job(JobRef, Job = #{}, CronOpts) when is_map(CronOpts) -> {JobSpec, JobOpts} = parse_job(Job), add_job2(JobRef, JobSpec, check_opts(JobRef, maps:merge(CronOpts, JobOpts))); add_job(JobRef, Job = {_, _Task}, CronOpts) when is_map(CronOpts) -> add_job2(JobRef, Job, check_opts(JobRef, CronOpts)); add_job(JobRef, {When, Task, JobOpts}, CronOpts) when is_map(JobOpts) -> add_job2(JobRef, {When, Task}, check_opts(JobRef, maps:merge(CronOpts, JobOpts))). add_job2(JobRef, Job = {_, Task}, Opts) -> case check_host(Opts) of true -> check_task(JobRef, Task), case supervisor:start_child(?SERVER, [JobRef, Job, Opts]) of {ok, _} -> JobRef; {error, {already_started, _}} -> already_started; Other -> Other end; false -> ignored end. get_opt(Opt, Map) -> case maps:take(Opt, Map) of {V, Map1} -> {V, Map1}; error -> erlang:error({missing_job_option, Opt, Map}) end. parse_job(Job) -> {When, Opts1} = get_opt(interval, Job), {Fun, Opts2} = get_opt(execute, Opts1), {{When, Fun}, Opts2}. %% @doc %% Get a list of all active jobs -spec all_jobs() -> [pid()]. all_jobs() -> [P || {_,P,_,_} <- supervisor:which_children(?SERVER)]. %% @doc %% Terminate a job terminate(Pid) when is_pid(Pid) -> supervisor:terminate_child(?SERVER, Pid). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> SupFlags = #{ strategy => simple_one_for_one, intensity => application:get_env(erlcron, sup_job_intensity, 3), period => application:get_env(erlcron, sup_job_period, 10) }, AChild = #{id => ecrn_agent, start => {ecrn_agent, start_link, []}, restart => transient, shutdown => brutal_kill, type => worker, modules => [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== check_opts(JobRef, Map) -> maps:foreach(fun (hostnames, L) when is_list(L) -> ok; (on_job_start, MF) when tuple_size(MF)==2; is_function(MF, 1) -> ok; (on_job_end, MF) when tuple_size(MF)==2; is_function(MF, 2) -> ok; (id, ID) when is_atom(ID); is_binary(ID); is_reference(ID) -> ok; (K, V) -> erlang:error({invalid_option_value, JobRef, {K, V}}) end, Map), Map. check_host(Opts) -> case maps:find(hostnames, Opts) of {ok, Hosts} when is_list(Hosts) -> {ok, Host} = inet:gethostname(), lists:member(Host, [to_list(H) || H <- Hosts]); error -> true end. check_task(JobRef, Task) when is_tuple(Task), (tuple_size(Task)==2 orelse tuple_size(Task)==3) -> M = element(1, Task), case code:ensure_loaded(M) of {module, M} -> ok; {error, Err1} -> erlang:error({module_not_loaded, JobRef, Task, Err1}) end, check_exists(JobRef, Task); check_task(_, Task) when is_function(Task, 0) -> ok; check_task(_, Task) when is_function(Task, 2) -> ok; check_task(JobRef, Task) -> erlang:error({invalid_job_task, JobRef, Task}). check_exists(JobRef, {M,F}) -> check_exists2(JobRef, {M,F,undefined}); check_exists(JobRef, {_,_,A} = MFA) when is_list(A) -> check_exists2(JobRef, MFA). check_exists2(JobRef, {M,F,A} = Task) -> case erlang:module_loaded(M) of false -> case code:ensure_loaded(M) of {module, M} -> ok; {error, Err1} -> erlang:error({module_not_loaded, JobRef, Task, Err1}) end; true -> ok end, case A of undefined -> check_arity(JobRef, M, F, [0,2]); _ when is_list(A) -> check_arity(JobRef, M, F, [length(A)]) end. check_arity(JobRef, M, F, Lengths) -> + {module, M} == code:ensure_loaded(M) + orelse erlang:error({job_task_module_not_loaded, JobRef, M}), lists:any(fun(Arity) -> erlang:function_exported(M,F,Arity) end, Lengths) orelse erlang:error({wrong_arity_of_job_task, JobRef, {M,F,Lengths}}). to_list(H) when is_binary(H) -> binary_to_list(H); to_list(H) when is_list(H) -> H.
erlware/erlcron
37abad5a03618e81cd0a7f1be9ff1810249f6558
Add job specification as a map
diff --git a/README.md b/README.md index ef02a8e..7aaff58 100644 --- a/README.md +++ b/README.md @@ -1,197 +1,208 @@ Erlcron ======= Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The syntax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. Unlike cron's one-minute resolution, erlcron has a millisecond resolution. It does handle Daylight Savings Time changes (but not the cases when the system clock is altered by small increments, in which case the next execution of a scheduled task may be imprecise). Cron Job Description Examples: ```erlang {{once, {3, 30, pm}, fun() -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}, fun(JobRef, CurrDateTime) -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, fun(_JobRef, _DateTime) -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, {fun(_JobRef, _DateTime) -> io:fwrite("It's 2 Wednesday morning~n") end} {{weekly, [tue,wed], {2, am}}, {fun(_, Now) -> io:format("Now is ~p~n", [Now]) end} {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} {{monthly, [1, 7, 14], {2, am}}, {io, fwrite, ["Every 1st, 7th, 14th of the month!~n"]}} {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} {{monthly, [0, -1], {2, am}}, {io, fwrite, ["Last two days of the month!~n"]}} {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} %% Days of month less or equal to zero are subtracted from the end of the month {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} ``` Adding a cron to the system: ```erlang Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job). ``` Cron jobs can be given named atom references: ```erlang erlcron:cron(test_job1, {{once, {3,pm}}, {io, fwrite, "It's 3pm"}}). ``` A simple way to add a daily cron: erlcron:daily({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. ```erlang erlcron:at(300, Fun). ``` Cancel a running job. ```erlang erlcron:cancel(JobRef). ``` Get the current reference (universal) date time of the system. ```erlang erlcron:datetime(). ``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:set_datetime(DateTime). ``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(DateTime). ``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(Nodes, DateTime). ``` The application cron can be pre-configured through environment variables in the config file that all applications can load in the Erlang VM start. The app.config file can be as follow: ```erlang [ {erlcron, [ {crontab, [ {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, %% A job may be specified to be run only if the current host %% is in the list of given hostnames. If default crontab %% options are provided in the `defaults` setting, %% the job-specific options will override corresponding %% default options. See erlcron:job_opts() for available %% options. {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}, #{hostnames => ["somehost"]}, {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, - {io, fwrite, ["Hello, world!~n"]}} + {io, fwrite, ["Hello, world!~n"]}}, + + %% A job spec can be defined as a map, where the `interval' and + %% `execute' keys are mandatory: + #{id => test_job, interval => {daily, {1, 0, pm}}, + execute => {io, fwrite, ["Hello, world!~n"]}}, + + %% If defined as a map, the map can contain any `erlcron:job_opts()' + %% options: + #{id => another_job, interval => {daily, {1, 0, pm}}, + execute => {io, fwrite, ["Hello, world!~n"]}, + hostnames => ["myhost"]} ]}, %% Instead of specifying individual options for each job, you can %% define default options here. {defaults, #{ %% Limit jobs to run only on the given list of hosts hostnames => ["myhost"], %% Function `fun((Ref) -> ignore | any())` to call before a job is started. %% If the function returns `ignore`, the job will not be executed, and the %% `on_job_end` callback will not be executed. on_job_start => {some_module, function}, %% Function `fun((Ref, Status :: {ok, Result}|{error, {Reason, StackTrace}}) -> ok)` %% to call after a job has ended on_job_end => {some_module, function} }} ]} ]. ``` So, when the app will be started, all configurations will be loaded. Note that the limitation is that in the config file is impossible load an anonymous function (or lambda function) so, you only can use {M,F,A} format. If an `on_job_start` or `on_job_end` functions are provided for any job or as default settings, it's the responsibility of a developer to make sure that those functions handle exceptions, since the failure in those functions will cause the supervisor to restart the job up until the supervisor reaches its maximum restart intensity. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index c6c466f..649193e 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,164 +1,178 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2, add_job/3, all_jobs/0, terminate/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). add_job(JobRef, Job) -> add_job(JobRef, Job, #{}). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job(), erlcron:cron_opts()) -> erlcron:job_ref() | ignored | already_started | {error, term()}. +add_job(JobRef, Job = #{}, CronOpts) when is_map(CronOpts) -> + {JobSpec, JobOpts} = parse_job(Job), + add_job2(JobRef, JobSpec, check_opts(JobRef, maps:merge(CronOpts, JobOpts))); add_job(JobRef, Job = {_, _Task}, CronOpts) when is_map(CronOpts) -> add_job2(JobRef, Job, check_opts(JobRef, CronOpts)); add_job(JobRef, {When, Task, JobOpts}, CronOpts) when is_map(JobOpts) -> add_job2(JobRef, {When, Task}, check_opts(JobRef, maps:merge(CronOpts, JobOpts))). add_job2(JobRef, Job = {_, Task}, Opts) -> case check_host(Opts) of true -> check_task(JobRef, Task), case supervisor:start_child(?SERVER, [JobRef, Job, Opts]) of {ok, _} -> JobRef; {error, {already_started, _}} -> already_started; Other -> Other end; false -> ignored end. +get_opt(Opt, Map) -> + case maps:take(Opt, Map) of + {V, Map1} -> {V, Map1}; + error -> erlang:error({missing_job_option, Opt, Map}) + end. + +parse_job(Job) -> + {When, Opts1} = get_opt(interval, Job), + {Fun, Opts2} = get_opt(execute, Opts1), + {{When, Fun}, Opts2}. + %% @doc %% Get a list of all active jobs -spec all_jobs() -> [pid()]. all_jobs() -> [P || {_,P,_,_} <- supervisor:which_children(?SERVER)]. %% @doc %% Terminate a job terminate(Pid) when is_pid(Pid) -> supervisor:terminate_child(?SERVER, Pid). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> SupFlags = #{ strategy => simple_one_for_one, intensity => application:get_env(erlcron, sup_job_intensity, 3), period => application:get_env(erlcron, sup_job_period, 10) }, AChild = #{id => ecrn_agent, start => {ecrn_agent, start_link, []}, restart => transient, shutdown => brutal_kill, type => worker, modules => [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== check_opts(JobRef, Map) -> maps:foreach(fun (hostnames, L) when is_list(L) -> ok; (on_job_start, MF) when tuple_size(MF)==2; is_function(MF, 1) -> ok; (on_job_end, MF) when tuple_size(MF)==2; is_function(MF, 2) -> ok; (id, ID) when is_atom(ID); is_binary(ID); is_reference(ID) -> ok; (K, V) -> erlang:error({invalid_option_value, JobRef, {K, V}}) end, Map), Map. check_host(Opts) -> case maps:find(hostnames, Opts) of {ok, Hosts} when is_list(Hosts) -> {ok, Host} = inet:gethostname(), lists:member(Host, [to_list(H) || H <- Hosts]); error -> true end. check_task(JobRef, Task) when is_tuple(Task), (tuple_size(Task)==2 orelse tuple_size(Task)==3) -> M = element(1, Task), case code:ensure_loaded(M) of {module, M} -> ok; {error, Err1} -> erlang:error({module_not_loaded, JobRef, Task, Err1}) end, check_exists(JobRef, Task); check_task(_, Task) when is_function(Task, 0) -> ok; check_task(_, Task) when is_function(Task, 2) -> ok; check_task(JobRef, Task) -> erlang:error({invalid_job_task, JobRef, Task}). check_exists(JobRef, {M,F}) -> check_exists2(JobRef, {M,F,undefined}); check_exists(JobRef, {_,_,A} = MFA) when is_list(A) -> check_exists2(JobRef, MFA). check_exists2(JobRef, {M,F,A} = Task) -> case erlang:module_loaded(M) of false -> case code:ensure_loaded(M) of {module, M} -> ok; {error, Err1} -> erlang:error({module_not_loaded, JobRef, Task, Err1}) end; true -> ok end, case A of undefined -> check_arity(JobRef, M, F, [0,2]); _ when is_list(A) -> check_arity(JobRef, M, F, [length(A)]) end. check_arity(JobRef, M, F, Lengths) -> lists:any(fun(Arity) -> erlang:function_exported(M,F,Arity) end, Lengths) orelse erlang:error({wrong_arity_of_job_task, JobRef, {M,F,Lengths}}). to_list(H) when is_binary(H) -> binary_to_list(H); to_list(H) when is_list(H) -> H. diff --git a/src/erlcron.erl b/src/erlcron.erl index ab53a55..1ebcff9 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,300 +1,302 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, cron/2, cron/3, at/2, at/3, at/4, daily/2, daily/3, daily/4, weekly/3, weekly/4, weekly/5, monthly/3,monthly/4, monthly/5, cancel/1, epoch/0, epoch_seconds/0, datetime/0, ref_datetime/0, set_datetime/1, set_datetime/2, reset_datetime/0, get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, job_opts/0, cron_opts/0, job_start/0, job_end/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0, milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | h | min | m | sec | s}. -type period() :: cron_time() | {every, duration()} | {every, duration(), constraint()}. -type dom() :: integer(). -type dow_day() :: mon | tue | wed | thu | fri | sat | sun. -type dow() :: dow_day() | [dow_day()]. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | fun(() -> term()) | fun((JobRef::job_ref(), calendar:datetime()) -> term()). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom()|[dom()], period()}. -type job() :: {run_when(), callable()} - | {run_when(), callable(), job_opts()}. + | {run_when(), callable(), job_opts()} + | #{id => job_ref(), interval => run_when(), execute => callable(), _ => any()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference() | atom() | binary(). %% A job reference. -type job_start() :: fun((JobRef::job_ref()) -> ignore | any()). %% A function to be called before a job is started. If it returns the `ignore' %% atom, the job function will not be executed. -type job_end() :: fun((JobRef::job_ref(), Res :: {ok, term()} | {error, {Reason::term(), Stack::list()}}) -> term()). %% A function to be called after a job ended. The function is passed the %% job's result. -type job_opts() :: #{hostnames => [binary()|string()], id => term(), on_job_start => {Mod::atom(), Fun::atom()} | job_start(), on_job_end => {Mod::atom(), Fun::atom()} | job_end() }. %% Job options: %% <dl> %% <dt>hostnames => [Hostname]</dt> %% <dd>List of hostnames where the job is allowed to run</dd> %% <dt>id => ID</dt> %% <dd>An identifier of the job passed to `on_job_start' and `on_job_end' %% callbacks. It can be any term.</dd> %% <dt>on_job_start => {Mod, Fun} | fun(JobRef, ID) -> any()</dt> %% <dd>`Mod:Fun(Ref::job_ref(), ID::any())' function to call on job start. %% The result is ignored.</dd> %% <dt>{on_job_start, {Mod, Fun}} | fun(JobRef, ID, Result) -> term()</dt> %% <dd>`Mod:Fun(Ref::job_ref(), ID::any(), Result)' function to call after %% a job has ended. `Result' is `{ok, JobResult::term()}' or %% `{error, `{Reason, StackTrace}}' if there is an exception.</dd> %% </dl> -type cron_opts() :: job_opts(). %% Cron default options applicable to all jobs. See job_opts(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref() | ignored | already_started | {error, term()}. cron(Job) -> cron(make_ref(Job), Job, #{}). -spec cron(job()|job_ref(), job()|cron_opts()) -> job_ref() | ignored | already_started | {error, term()}. cron(Job, DefOpts) when is_map(DefOpts) -> cron(make_ref(Job), Job, DefOpts); -cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) - , is_tuple(Job) -> +cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) -> cron(JobRef, Job, #{}). %% @doc Schedule a job identified by a `JobRef'. %% A job reference can be a reference, atom, or binary. If it is %% an atom, a job will be locally registered by that name. %% Returns false if the job is not permitted to run on the current host -spec cron(job_ref(), job(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. cron(JobRef, Job, Opts) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) - , is_tuple(Job), is_map(Opts) -> + , is_map(Opts) -> ecrn_cron_sup:add_job(JobRef, Job, Opts). %% @doc %% Convenience method to specify a job to run once at the given time %% or after the amount of time specified. -spec at(cron_time() | seconds(), callable()) -> job_ref() | ignored | already_started | {error, term()}. at(When, Fun) -> at(make_ref(), When, Fun). -spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. at(JobRef, When, Fun) -> cron(JobRef, {{once, When}, Fun}). -spec at(job_ref(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. at(JobRef, When, Fun, #{} = Opts) -> cron(JobRef, {{once, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a daily basis %% at a specific time. -spec daily(cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. daily(When, Fun) -> daily(make_ref(), When, Fun). -spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. daily(JobRef, When, Fun) -> cron(JobRef, {{daily, When}, Fun}). -spec daily(job_ref(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. daily(JobRef, When, Fun, #{} = Opts) -> cron(JobRef, {{daily, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. weekly(DOW, When, Fun) -> weekly(make_ref(), DOW, When, Fun). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. weekly(JobRef, DOW, When, Fun) -> cron(JobRef, {{weekly, DOW, When}, Fun}). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. weekly(JobRef, DOW, When, Fun, #{} = Opts) -> cron(JobRef, {{weekly, DOW, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. monthly(DOM, When, Fun) -> monthly(make_ref(), DOM, When, Fun). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. monthly(JobRef, DOM, When, Fun) -> cron(JobRef, {{monthly, DOM, When}, Fun}). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. monthly(JobRef, DOM, When, Fun, #{} = Opts) -> cron(JobRef, {{monthly, DOM, When}, Fun}, Opts). %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time in seconds millisince epoch. -spec epoch() -> milliseconds(). epoch() -> ecrn_util:epoch_milliseconds(). %% @doc %% Get the current date time in seconds since epoch. -spec epoch_seconds() -> seconds(). epoch_seconds() -> ecrn_util:epoch_seconds(). %% @doc %% Get the current date time of the erlcron system adjusted to reference. %% -spec datetime() -> {calendar:datetime(), milliseconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Get the reference date time of the erlcron system. %% -spec ref_datetime() -> {calendar:datetime(), milliseconds()}. ref_datetime() -> ecrn_control:ref_datetime(). %% @doc %% Set the current date time of the running erlcron system using local time. -spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime) -> set_datetime(DateTime, local). %% @doc %% Set the current date time of the running erlcron system using either local %% or universal time. The `TZ` parameter must contain an atom `local|universal`. -spec set_datetime(calendar:datetime(), local|universal) -> ok. set_datetime({D,T} = DateTime, TZ) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:set_datetime(DateTime, TZ). %% @doc %% Reset the reference datetime of erlcron system to current epoch time. -spec reset_datetime() -> ok. reset_datetime() -> ecrn_control:reset_datetime(). %% Get references of all running jobs -spec get_all_jobs() -> [job_ref()]. get_all_jobs() -> ecrn_reg:get_all_refs(). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime). +make_ref(#{id := ID}) when is_atom(ID); is_binary(ID); is_reference(ID) -> + ID; make_ref({_When, _Callable, #{id := ID}}) when is_atom(ID); is_binary(ID); is_reference(ID) -> ID; make_ref({_When, _Callable, #{}}) -> make_ref(); make_ref({_When, _Callable}) -> make_ref(). diff --git a/test/ecrn_startup_test.erl b/test/ecrn_startup_test.erl index 7e062a6..ff8d742 100644 --- a/test/ecrn_startup_test.erl +++ b/test/ecrn_startup_test.erl @@ -1,42 +1,44 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_startup_test). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> Ref = make_ref(), application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), application:set_env(erlcron, crontab, [ {{daily, {1, 0, pm}}, {erlang, system_time, []}, #{id => one}}, {{daily, {2, 0, pm}}, fun() -> erlang:system_time() end, #{id => <<"two">>}}, - {{daily, {3, 0, pm}}, fun(_JobRef, _Now) -> erlang:system_time() end, #{id => Ref}} + {{daily, {3, 0, pm}}, fun(_JobRef, _Now) -> erlang:system_time() end, #{id => Ref}}, + #{id => four, interval => {daily, {1, 0, pm}}, execute => {erlang, system_time, []}} ]), application:start(erlcron), Ref end, fun(_) -> application:stop(erlcron) end, {with, [fun(Ref) -> check_startup_jobs(Ref) end]} }. check_startup_jobs(Ref) -> - ?assertMatch([_, _, _], ecrn_cron_sup:all_jobs()), - ?assertEqual([one, Ref, <<"two">>], ecrn_reg:get_all_refs()), + ?assertMatch([_, _, _, _], ecrn_cron_sup:all_jobs()), + ?assertEqual([four, one, Ref, <<"two">>], ecrn_reg:get_all_refs()), ?assert(is_pid(ecrn_reg:get(one))), ?assert(is_pid(ecrn_reg:get(<<"two">>))), - ?assert(is_pid(ecrn_reg:get(Ref))). + ?assert(is_pid(ecrn_reg:get(Ref))), + ?assert(is_pid(ecrn_reg:get(four))).
erlware/erlcron
f07346d8397587703c61d16b570e61af0294fc1e
Fix cronjob startup config
diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index aa12fa4..bbd7098 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,73 +1,73 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> %application:start(crypto), application:start(eunit), %application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> setup(), {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. setup() -> case application:get_env(erlcron, crontab) of {ok, Crontab} -> Def = application:get_env(erlcron, defaults, #{}), is_map(Def) orelse erlang:error("erlcron/defaults config must be a map!"), lists:foreach(fun(CronJob) -> case erlcron:cron(CronJob, Def) of - ok -> - ok; already_started -> - ok; + erlang:error({duplicate_job_reference, CronJob}); ignored -> ok; + Ref when is_reference(Ref); is_atom(Ref); is_binary(Ref) -> + ok; {error, Reason} -> erlang:error({failed_to_add_cron_job, CronJob, Reason}) end end, Crontab); undefined -> ok end. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index 10e6c61..c6c466f 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,162 +1,164 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2, add_job/3, all_jobs/0, terminate/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). add_job(JobRef, Job) -> add_job(JobRef, Job, #{}). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job(), erlcron:cron_opts()) -> erlcron:job_ref() | ignored | already_started | {error, term()}. add_job(JobRef, Job = {_, _Task}, CronOpts) when is_map(CronOpts) -> add_job2(JobRef, Job, check_opts(JobRef, CronOpts)); add_job(JobRef, {When, Task, JobOpts}, CronOpts) when is_map(JobOpts) -> add_job2(JobRef, {When, Task}, check_opts(JobRef, maps:merge(CronOpts, JobOpts))). add_job2(JobRef, Job = {_, Task}, Opts) -> case check_host(Opts) of true -> check_task(JobRef, Task), case supervisor:start_child(?SERVER, [JobRef, Job, Opts]) of {ok, _} -> JobRef; {error, {already_started, _}} -> already_started; Other -> Other end; false -> ignored end. %% @doc %% Get a list of all active jobs -spec all_jobs() -> [pid()]. all_jobs() -> [P || {_,P,_,_} <- supervisor:which_children(?SERVER)]. %% @doc %% Terminate a job terminate(Pid) when is_pid(Pid) -> supervisor:terminate_child(?SERVER, Pid). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> SupFlags = #{ strategy => simple_one_for_one, intensity => application:get_env(erlcron, sup_job_intensity, 3), period => application:get_env(erlcron, sup_job_period, 10) }, AChild = #{id => ecrn_agent, start => {ecrn_agent, start_link, []}, restart => transient, shutdown => brutal_kill, type => worker, modules => [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== check_opts(JobRef, Map) -> maps:foreach(fun (hostnames, L) when is_list(L) -> ok; (on_job_start, MF) when tuple_size(MF)==2; is_function(MF, 1) -> ok; (on_job_end, MF) when tuple_size(MF)==2; is_function(MF, 2) -> ok; + (id, ID) when is_atom(ID); is_binary(ID); is_reference(ID) -> + ok; (K, V) -> erlang:error({invalid_option_value, JobRef, {K, V}}) end, Map), Map. check_host(Opts) -> case maps:find(hostnames, Opts) of {ok, Hosts} when is_list(Hosts) -> {ok, Host} = inet:gethostname(), lists:member(Host, [to_list(H) || H <- Hosts]); error -> true end. check_task(JobRef, Task) when is_tuple(Task), (tuple_size(Task)==2 orelse tuple_size(Task)==3) -> M = element(1, Task), case code:ensure_loaded(M) of {module, M} -> ok; {error, Err1} -> erlang:error({module_not_loaded, JobRef, Task, Err1}) end, check_exists(JobRef, Task); check_task(_, Task) when is_function(Task, 0) -> ok; check_task(_, Task) when is_function(Task, 2) -> ok; check_task(JobRef, Task) -> erlang:error({invalid_job_task, JobRef, Task}). check_exists(JobRef, {M,F}) -> check_exists2(JobRef, {M,F,undefined}); check_exists(JobRef, {_,_,A} = MFA) when is_list(A) -> check_exists2(JobRef, MFA). check_exists2(JobRef, {M,F,A} = Task) -> case erlang:module_loaded(M) of false -> case code:ensure_loaded(M) of {module, M} -> ok; {error, Err1} -> erlang:error({module_not_loaded, JobRef, Task, Err1}) end; true -> ok end, case A of undefined -> check_arity(JobRef, M, F, [0,2]); _ when is_list(A) -> check_arity(JobRef, M, F, [length(A)]) end. check_arity(JobRef, M, F, Lengths) -> lists:any(fun(Arity) -> erlang:function_exported(M,F,Arity) end, Lengths) orelse erlang:error({wrong_arity_of_job_task, JobRef, {M,F,Lengths}}). to_list(H) when is_binary(H) -> binary_to_list(H); to_list(H) when is_list(H) -> H. diff --git a/src/ecrn_reg.erl b/src/ecrn_reg.erl index 3d1739e..3e48fb1 100644 --- a/src/ecrn_reg.erl +++ b/src/ecrn_reg.erl @@ -1,248 +1,252 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% This provides simple pid registration for the server. -module(ecrn_reg). -behaviour(gen_server). %% API -export([start_link/0, register/2, unregister/1, get/1, get_refs/1, cancel/1, stop/0, get_all/0, get_all_pids/0, get_all_refs/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -record(state, {pid2ref, ref2pid}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link() -> {ok, Pid::pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %% @doc %% Register an arbitrary value with the system, under a set of keys -spec register(erlcron:job_ref(), term()) -> boolean(). -register(Key, Pid) when (is_atom(Key) orelse is_reference(Key)), is_pid(Pid) -> +register(Key, Pid) when (is_atom(Key) orelse is_reference(Key) orelse is_binary(Key)), is_pid(Pid) -> gen_server:call(?SERVER, {register, Key, Pid}). %% @doc %% Remove the value registered under a que or set of keys -spec unregister(erlcron:job_ref()) -> ok. -unregister(Key) when is_atom(Key); is_reference(Key) -> +unregister(Key) when is_atom(Key); is_reference(Key); is_binary(Key) -> gen_server:cast(?SERVER, {unregister, Key}). %% @doc %% Get a pid by reference key. -spec get(erlcron:job_ref()) -> pid() | undefined. -get(Key) when is_atom(Key); is_reference(Key) -> +get(Key) when is_atom(Key); is_reference(Key); is_binary(Key) -> gen_server:call(?SERVER, {get, Key}). %% @doc %% Get job refs associated with the pid -spec get_refs(pid()) -> [erlcron:job_ref()]. get_refs(Pid) when is_pid(Pid) -> lists:sort(gen_server:call(?SERVER, {get_refs, Pid})). %% @doc %% Cancel all jobs assigned to the given key -spec cancel(term()) -> boolean(). -cancel(Key) when is_atom(Key); is_reference(Key) -> +cancel(Key) when is_atom(Key); is_reference(Key); is_binary(Key) -> gen_server:call(?SERVER, {cancel, Key}). %% @doc %% Get all the values. -spec get_all() -> [{term(), term()}]. get_all() -> gen_server:call(?SERVER, get_all). %% @doc %% Get all registered Pids. -spec get_all_pids() -> [pid()]. get_all_pids() -> gen_server:call(?SERVER, get_all_pids). %% @doc %% Get all registered job references. -spec get_all_refs() -> [erlcron:job_ref()]. get_all_refs() -> gen_server:call(?SERVER, get_all_refs). %% @doc %% stop this server -spec stop() -> ok. stop() -> gen_server:call(?SERVER, stop). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> {ok, #state{pid2ref=#{}, ref2pid=#{}}}. %% @private handle_call({register, Ref, Pid}, _From, #state{pid2ref=M1, ref2pid=M2}=State) -> Ref1 = monitor(process, Pid), case maps:find(Pid, M1) of {ok, Refs} when is_list(Refs) -> demonitor(Ref1, [flush]), case lists:member(Ref, Refs) of true -> {reply, false, State}; false -> {reply, true, State#state{ref2pid=M2#{Ref=>Pid}, pid2ref=M1#{Pid=>[Ref|Refs]}}} end; error -> {reply, true, State#state{ref2pid=M2#{Ref=>Pid}, pid2ref=M1#{Pid=>[Ref]}}} end; handle_call({get, Key}, _From, State) -> case get_for_key(Key, State) of {ok, V} -> {reply, V, State}; undefined -> {reply, undefined, State} end; handle_call({get_refs, Pid}, _From, State) -> case get_for_key(Pid, State) of {ok, V} -> {reply, V, State}; undefined -> {reply, [], State} end; handle_call({cancel, Pid}, _From, State) -> {Found, State1} = find_and_remove(Pid, State, fun(P) -> ecrn_agent:cancel(P) end), {reply, Found, State1}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; handle_call(get_all, _From, State = #state{ref2pid=Map}) -> {reply, maps:to_list(Map), State}; handle_call(get_all_refs, _From, State = #state{ref2pid=Map}) -> {reply, maps:keys(Map), State}; handle_call(get_all_pids, _From, State = #state{pid2ref=Map}) -> {reply, maps:keys(Map), State}. %% @private handle_cast({unregister, Key}, State) -> {_, NewState} = find_and_remove(Key, State, undefined), {noreply, NewState}; handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info({'DOWN', _Ref, process, Pid, _Info}, State) -> handle_cast({unregister, Pid}, State); handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== -get_for_key(Ref, #state{ref2pid=Map}) when is_reference(Ref); is_atom(Ref) -> +get_for_key(Ref, #state{ref2pid=Map}) when is_reference(Ref); is_atom(Ref); is_binary(Ref) -> case maps:find(Ref, Map) of error -> undefined; OkValue -> OkValue end; get_for_key(Pid, #state{pid2ref=Map}) when is_pid(Pid) -> case maps:find(Pid, Map) of error -> undefined; OkValue -> OkValue end. --spec find_and_remove(reference()|atom()|pid(), #state{}, undefined|fun((pid())->ok)) -> +-spec find_and_remove(erlcron:job_ref()|pid(), #state{}, undefined|fun((pid())->ok)) -> {boolean(), #state{}}. -find_and_remove(Ref, S = #state{ref2pid=M1}, Fun) when is_reference(Ref); is_atom(Ref) -> - case maps:find(Ref, M1) of - {ok, Pid} -> - is_function(Fun, 1) andalso Fun(Pid), - {true, find_and_remove2(Pid, Ref, S)}; - error -> - {false, S} - end; find_and_remove(Pid, State = #state{ref2pid=M1, pid2ref=M2}, Fun) when is_pid(Pid) -> case maps:find(Pid, M2) of {ok, Refs} -> is_function(Fun, 1) andalso Fun(Pid), NewM1 = lists:foldl(fun(R, M) -> maps:remove(R, M) end, M1, Refs), {true, State#state{ref2pid=NewM1, pid2ref=maps:remove(Pid,M2)}}; error -> {false, State} + end; +find_and_remove(Ref, S = #state{ref2pid=M1}, Fun) -> + case maps:find(Ref, M1) of + {ok, Pid} -> + is_function(Fun, 1) andalso Fun(Pid), + {true, find_and_remove2(Pid, Ref, S)}; + error -> + {false, S} end. find_and_remove2(Pid, Ref, S = #state{ref2pid=M1, pid2ref=M2}) when is_pid(Pid) -> case maps:find(Pid, M2) of {ok, Refs} -> case lists:delete(Ref, Refs) of [] -> S#state{ref2pid=maps:remove(Ref,M1), pid2ref=maps:remove(Pid,M2)}; L -> S#state{ref2pid=maps:remove(Ref,M1), pid2ref=M2#{Pid => L}} end; error -> S#state{ref2pid=maps:remove(Ref,M1)} end. %%%=================================================================== %%% Tests %%%=================================================================== -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -ifdef(EUNIT). generate_test_() -> {setup, fun () -> ecrn_reg:start_link() end, fun (_) -> ecrn_reg:stop() end, {with, [fun general_tests/1]}}. general_tests(_) -> Self = self(), ?assertMatch(true, ecrn_reg:register(a, Self)), ?assertMatch(Self, ecrn_reg:get(a)), ecrn_reg:unregister(a), Ref = make_ref(), ?assertMatch(undefined, ecrn_reg:get(a)), ?assertMatch(true, ecrn_reg:register(b, Self)), ?assertMatch(true, ecrn_reg:register(c, Self)), ?assertMatch(true, ecrn_reg:register(Ref, Self)), ?assertMatch(Self, ecrn_reg:get(c)), ?assertMatch(Self, ecrn_reg:get(b)), ?assertMatch(Self, ecrn_reg:get(Ref)), ?assertMatch([b,c,Ref], ecrn_reg:get_refs(Self)), ?assertMatch(false, ecrn_reg:register(b, Self)), ?assertMatch(false, ecrn_reg:register(c, Self)), ?assertMatch(false, ecrn_reg:register(Ref, Self)), ?assertMatch([b,c,Ref], ecrn_reg:get_all_refs()), ?assertMatch([Self], ecrn_reg:get_all_pids()), ecrn_reg:unregister(b), ?assertMatch([c,Ref], ecrn_reg:get_all_refs()), ?assertMatch([Self], ecrn_reg:get_all_pids()), + ?assertMatch(true, ecrn_reg:register(<<"d">>, Self)), + ?assertMatch(Self, ecrn_reg:get(<<"d">>)), + ecrn_reg:unregister(<<"d">>), + ?assertMatch(undefined, ecrn_reg:get(<<"d">>)), ok. -endif. diff --git a/src/erlcron.erl b/src/erlcron.erl index 2dc60be..ab53a55 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,293 +1,300 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, cron/2, cron/3, at/2, at/3, at/4, daily/2, daily/3, daily/4, weekly/3, weekly/4, weekly/5, monthly/3,monthly/4, monthly/5, cancel/1, epoch/0, epoch_seconds/0, datetime/0, ref_datetime/0, set_datetime/1, set_datetime/2, reset_datetime/0, get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, job_opts/0, cron_opts/0, job_start/0, job_end/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0, milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | h | min | m | sec | s}. -type period() :: cron_time() | {every, duration()} | {every, duration(), constraint()}. -type dom() :: integer(). -type dow_day() :: mon | tue | wed | thu | fri | sat | sun. -type dow() :: dow_day() | [dow_day()]. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | fun(() -> term()) | - fun((JobRef::atom()|reference(), calendar:datetime()) -> term()). + fun((JobRef::job_ref(), calendar:datetime()) -> term()). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom()|[dom()], period()}. -type job() :: {run_when(), callable()} | {run_when(), callable(), job_opts()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference() | atom() | binary(). %% A job reference. -type job_start() :: fun((JobRef::job_ref()) -> ignore | any()). %% A function to be called before a job is started. If it returns the `ignore' %% atom, the job function will not be executed. -type job_end() :: fun((JobRef::job_ref(), Res :: {ok, term()} | {error, {Reason::term(), Stack::list()}}) -> term()). %% A function to be called after a job ended. The function is passed the %% job's result. -type job_opts() :: #{hostnames => [binary()|string()], id => term(), on_job_start => {Mod::atom(), Fun::atom()} | job_start(), on_job_end => {Mod::atom(), Fun::atom()} | job_end() }. %% Job options: %% <dl> %% <dt>hostnames => [Hostname]</dt> %% <dd>List of hostnames where the job is allowed to run</dd> %% <dt>id => ID</dt> %% <dd>An identifier of the job passed to `on_job_start' and `on_job_end' %% callbacks. It can be any term.</dd> %% <dt>on_job_start => {Mod, Fun} | fun(JobRef, ID) -> any()</dt> %% <dd>`Mod:Fun(Ref::job_ref(), ID::any())' function to call on job start. %% The result is ignored.</dd> %% <dt>{on_job_start, {Mod, Fun}} | fun(JobRef, ID, Result) -> term()</dt> %% <dd>`Mod:Fun(Ref::job_ref(), ID::any(), Result)' function to call after %% a job has ended. `Result' is `{ok, JobResult::term()}' or %% `{error, `{Reason, StackTrace}}' if there is an exception.</dd> %% </dl> -type cron_opts() :: job_opts(). %% Cron default options applicable to all jobs. See job_opts(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref() | ignored | already_started | {error, term()}. cron(Job) -> - cron(make_ref(), Job, #{}). + cron(make_ref(Job), Job, #{}). -spec cron(job()|job_ref(), job()|cron_opts()) -> job_ref() | ignored | already_started | {error, term()}. cron(Job, DefOpts) when is_map(DefOpts) -> - cron(make_ref(), Job, DefOpts); + cron(make_ref(Job), Job, DefOpts); cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) , is_tuple(Job) -> cron(JobRef, Job, #{}). %% @doc Schedule a job identified by a `JobRef'. %% A job reference can be a reference, atom, or binary. If it is %% an atom, a job will be locally registered by that name. %% Returns false if the job is not permitted to run on the current host -spec cron(job_ref(), job(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. cron(JobRef, Job, Opts) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) , is_tuple(Job), is_map(Opts) -> ecrn_cron_sup:add_job(JobRef, Job, Opts). %% @doc %% Convenience method to specify a job to run once at the given time %% or after the amount of time specified. -spec at(cron_time() | seconds(), callable()) -> job_ref() | ignored | already_started | {error, term()}. at(When, Fun) -> at(make_ref(), When, Fun). -spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. at(JobRef, When, Fun) -> cron(JobRef, {{once, When}, Fun}). -spec at(job_ref(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. at(JobRef, When, Fun, #{} = Opts) -> cron(JobRef, {{once, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a daily basis %% at a specific time. -spec daily(cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. daily(When, Fun) -> daily(make_ref(), When, Fun). -spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. daily(JobRef, When, Fun) -> cron(JobRef, {{daily, When}, Fun}). -spec daily(job_ref(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. daily(JobRef, When, Fun, #{} = Opts) -> cron(JobRef, {{daily, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. weekly(DOW, When, Fun) -> weekly(make_ref(), DOW, When, Fun). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. weekly(JobRef, DOW, When, Fun) -> cron(JobRef, {{weekly, DOW, When}, Fun}). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. weekly(JobRef, DOW, When, Fun, #{} = Opts) -> cron(JobRef, {{weekly, DOW, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. monthly(DOM, When, Fun) -> monthly(make_ref(), DOM, When, Fun). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. monthly(JobRef, DOM, When, Fun) -> cron(JobRef, {{monthly, DOM, When}, Fun}). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. monthly(JobRef, DOM, When, Fun, #{} = Opts) -> cron(JobRef, {{monthly, DOM, When}, Fun}, Opts). %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time in seconds millisince epoch. -spec epoch() -> milliseconds(). epoch() -> ecrn_util:epoch_milliseconds(). %% @doc %% Get the current date time in seconds since epoch. -spec epoch_seconds() -> seconds(). epoch_seconds() -> ecrn_util:epoch_seconds(). %% @doc %% Get the current date time of the erlcron system adjusted to reference. %% -spec datetime() -> {calendar:datetime(), milliseconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Get the reference date time of the erlcron system. %% -spec ref_datetime() -> {calendar:datetime(), milliseconds()}. ref_datetime() -> ecrn_control:ref_datetime(). %% @doc %% Set the current date time of the running erlcron system using local time. -spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime) -> set_datetime(DateTime, local). %% @doc %% Set the current date time of the running erlcron system using either local %% or universal time. The `TZ` parameter must contain an atom `local|universal`. -spec set_datetime(calendar:datetime(), local|universal) -> ok. set_datetime({D,T} = DateTime, TZ) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:set_datetime(DateTime, TZ). %% @doc %% Reset the reference datetime of erlcron system to current epoch time. -spec reset_datetime() -> ok. reset_datetime() -> ecrn_control:reset_datetime(). %% Get references of all running jobs -spec get_all_jobs() -> [job_ref()]. get_all_jobs() -> ecrn_reg:get_all_refs(). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime). + +make_ref({_When, _Callable, #{id := ID}}) when is_atom(ID); is_binary(ID); is_reference(ID) -> + ID; +make_ref({_When, _Callable, #{}}) -> + make_ref(); +make_ref({_When, _Callable}) -> + make_ref(). diff --git a/test/ecrn_startup_test.erl b/test/ecrn_startup_test.erl new file mode 100644 index 0000000..7e062a6 --- /dev/null +++ b/test/ecrn_startup_test.erl @@ -0,0 +1,42 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. +-module(ecrn_startup_test). +-compile(export_all). +-compile(nowarn_export_all). + +-include_lib("eunit/include/eunit.hrl"). + +-define(FuncTest(A), {atom_to_list(A), fun A/0}). + +%%%=================================================================== +%%% Types +%%%=================================================================== +cron_test_() -> + {setup, + fun() -> + Ref = make_ref(), + application:load(erlcron), + application:set_env(erlcron, sup_intensity, 0), + application:set_env(erlcron, sup_period, 1), + application:set_env(erlcron, crontab, [ + {{daily, {1, 0, pm}}, {erlang, system_time, []}, #{id => one}}, + {{daily, {2, 0, pm}}, fun() -> erlang:system_time() end, #{id => <<"two">>}}, + {{daily, {3, 0, pm}}, fun(_JobRef, _Now) -> erlang:system_time() end, #{id => Ref}} + ]), + application:start(erlcron), + Ref + end, + fun(_) -> + application:stop(erlcron) + end, + {with, [fun(Ref) -> check_startup_jobs(Ref) end]} + }. + +check_startup_jobs(Ref) -> + ?assertMatch([_, _, _], ecrn_cron_sup:all_jobs()), + ?assertEqual([one, Ref, <<"two">>], ecrn_reg:get_all_refs()), + ?assert(is_pid(ecrn_reg:get(one))), + ?assert(is_pid(ecrn_reg:get(<<"two">>))), + ?assert(is_pid(ecrn_reg:get(Ref))).
erlware/erlcron
1d1d7506d980dbfa63fb55174bcec091a3841bd1
Implement the ability to ignore the job based on return of on_job_start
diff --git a/README.md b/README.md index 5737ed5..ef02a8e 100644 --- a/README.md +++ b/README.md @@ -1,195 +1,197 @@ Erlcron ======= Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The syntax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. Unlike cron's one-minute resolution, erlcron has a millisecond resolution. It does handle Daylight Savings Time changes (but not the cases when the system clock is altered by small increments, in which case the next execution of a scheduled task may be imprecise). Cron Job Description Examples: ```erlang {{once, {3, 30, pm}, fun() -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}, fun(JobRef, CurrDateTime) -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, fun(_JobRef, _DateTime) -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, {fun(_JobRef, _DateTime) -> io:fwrite("It's 2 Wednesday morning~n") end} {{weekly, [tue,wed], {2, am}}, {fun(_, Now) -> io:format("Now is ~p~n", [Now]) end} {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} {{monthly, [1, 7, 14], {2, am}}, {io, fwrite, ["Every 1st, 7th, 14th of the month!~n"]}} {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} {{monthly, [0, -1], {2, am}}, {io, fwrite, ["Last two days of the month!~n"]}} {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} %% Days of month less or equal to zero are subtracted from the end of the month {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} ``` Adding a cron to the system: ```erlang Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job). ``` Cron jobs can be given named atom references: ```erlang erlcron:cron(test_job1, {{once, {3,pm}}, {io, fwrite, "It's 3pm"}}). ``` A simple way to add a daily cron: erlcron:daily({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. ```erlang erlcron:at(300, Fun). ``` Cancel a running job. ```erlang erlcron:cancel(JobRef). ``` Get the current reference (universal) date time of the system. ```erlang erlcron:datetime(). ``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:set_datetime(DateTime). ``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(DateTime). ``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(Nodes, DateTime). ``` The application cron can be pre-configured through environment variables in the config file that all applications can load in the Erlang VM start. The app.config file can be as follow: ```erlang [ {erlcron, [ {crontab, [ {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, %% A job may be specified to be run only if the current host %% is in the list of given hostnames. If default crontab %% options are provided in the `defaults` setting, %% the job-specific options will override corresponding %% default options. See erlcron:job_opts() for available %% options. {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}, #{hostnames => ["somehost"]}, {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} ]}, %% Instead of specifying individual options for each job, you can %% define default options here. {defaults, #{ %% Limit jobs to run only on the given list of hosts hostnames => ["myhost"], - %% Function `fun((Ref) -> ok)` to call before a job is started + %% Function `fun((Ref) -> ignore | any())` to call before a job is started. + %% If the function returns `ignore`, the job will not be executed, and the + %% `on_job_end` callback will not be executed. on_job_start => {some_module, function}, %% Function `fun((Ref, Status :: {ok, Result}|{error, {Reason, StackTrace}}) -> ok)` %% to call after a job has ended on_job_end => {some_module, function} }} ]} ]. ``` So, when the app will be started, all configurations will be loaded. Note that the limitation is that in the config file is impossible load an anonymous function (or lambda function) so, you only can use {M,F,A} format. If an `on_job_start` or `on_job_end` functions are provided for any job or as default settings, it's the responsibility of a developer to make sure that those functions handle exceptions, since the failure in those functions will cause the supervisor to restart the job up until the supervisor reaches its maximum restart intensity. diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index dd97786..8c79480 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,766 +1,763 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/3, cancel/1, next_run/1, get_datetime/1, get_datetime/2, set_datetime/3, set_datetime/4, recalculate/1, validate/1, until_next_time/2, normalize/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, opts, job_ref, ref_epoch, epoch_at_ref, fast_forward=false, last_time, next_run, % Time in EPOCH seconds until task's next execution last_run, % Time in EPOCH seconds when the task was last run orig_when }). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 1000). -define(MAX_TIMEOUT_SEC, 1800). -define(MAX_TIMEOUT_MSEC, 1800000). -define(SEC_IN_A_DAY, 86400). %% compatibility -ifdef(OTP_RELEASE). %% this implies 21 or higher -define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). -define(GET_STACK(Stacktrace), Stacktrace). -include_lib("kernel/include/logger.hrl"). -else. -define(EXCEPTION(Class, Reason, _), Class:Reason). -define(GET_STACK(_), erlang:get_stacktrace()). -define(LOG_ERROR(Report), error_logger:error_report(Report)). -define(LOG_WARNING(Report), error_logger:warning_report(Report)). -endif. %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the appropriate job and the appropriate ref -spec start_link(erlcron:job_ref(), erlcron:job(), erlcron:job_opts()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, {When, _Task} = Job, JobOpts) when (is_reference(JobRef) orelse is_binary(JobRef)) , is_map(JobOpts) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link(?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec, JobOpts], []); start_link(JobRef, {When, _Task} = Job, JobOpts) when is_atom(JobRef), is_map(JobOpts) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link({local, JobRef}, ?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec, JobOpts], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> get_datetime(Pid, local). -spec get_datetime(pid(), local|universal) -> calendar:datetime(). get_datetime(Pid, local) -> erlang:universaltime_to_localtime(get_datetime(Pid, universal)); get_datetime(Pid, universal) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) when is_pid(Pid); is_atom(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> set_datetime(Pid, DateTime, Actual, local). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds(), UTC::local|universal) -> ok | {error, term()}. set_datetime(Pid, DateTime, Actual, UTC) -> DT = case UTC of local -> erlang:localtime_to_universaltime(DateTime); universal -> DateTime end, Res = gen_server:call(Pid, {set_datetime, DT, Actual}, infinity), Res. -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Get job's next execution time -spec next_run(pid()) -> erlang:timestamp(). next_run(Pid) -> gen_server:call(Pid, next_run). %% @doc %% Validate that a run_when spec specified is correct. -spec validate(erlcron:run_when()) -> ok | {error, term()}. validate(Spec) -> State = #state{job=undefined, job_ref=undefined}, {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), NewState = set_internal_time(State, DateTime, ActualMsec), try NormalSpec = normalize(Spec, DateTime), {Msec,_} = until_next_time(NewState#state{job={NormalSpec, undefined}}), Msec > 0 orelse throw({specified_time_past_seconds_ago, to_seconds(Msec)}), ok catch _Error:Reason -> {error, Reason} end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, {When, Task}, Sched, DateTime, ActualMsec, JobOpts]) -> try State = set_internal_time(#state{job_ref=JobRef, job={Sched, Task}, opts=JobOpts, last_run=0, next_run=0, orig_when=When}, DateTime, ActualMsec), case until_next_milliseconds(State) of {ok, {NewState, Timeout}} -> ecrn_reg:register(JobRef, self()), {ok, NewState, Timeout}; {error, {_, Reason}} -> throw(Reason) end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, JobRef}, {run_when, When}, {reason, E}, {stack, ?GET_STACK(ST)}]), {stop, normal} end. %% @private handle_call(next_run, _From, #state{next_run=Time} = State) -> reply_and_wait(Time, State); handle_call(get_datetime, _From, State) -> Epoch = ecrn_util:epoch_milliseconds(), Msec = current_epoch(Epoch, State), DT = to_universal_datetime(Msec), reply_and_wait(DT, State#state{last_time=Epoch}); handle_call({set_datetime, DateTime, CurrEpochMsec}, _From, State) -> try NewRefEpoch = to_milliseconds(erlang:universaltime_to_posixtime(DateTime)), case fast_forward(State#state{fast_forward=true}, NewRefEpoch, DateTime, 1) of true -> NewState = set_internal_time(State#state{next_run=0}, DateTime, CurrEpochMsec), reply_and_wait(ok, NewState); false -> {stop, normal, ok, State} end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, State#state.job_ref}, {run_when, element(1, State#state.orig_when)}, {reason, E}, {stack, ?GET_STACK(ST)}]), reply_and_wait({error, E}, State) end; handle_call(Msg, _From, State) -> {stop, State, {not_implemented, Msg}}. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast(Other, State) -> {stop, {not_implemented, Other}, State}. %% @private handle_info(timeout, S) -> process_timeout(S); handle_info({'EXIT', _, Reason}, State) -> {stop, Reason, State}; handle_info(_Msg, State) -> {noreply, State, 1000}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== normalize_when(When) -> {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), Sched = normalize(When, erlang:universaltime_to_localtime(DateTime)), {Sched, DateTime, ActualMsec}. process_timeout(#state{last_time=LastTime, next_run=NextRun, last_run=LastRun}=S) -> Epoch = ecrn_util:epoch_milliseconds(), NowMsec = current_epoch(Epoch, S), {Reply, State} = if LastTime < Epoch, NextRun > LastRun, NowMsec >= NextRun -> {do_job_run(S), S#state{last_run=NextRun, next_run=0}}; NextRun == LastRun -> S#state.fast_forward orelse timer:sleep(1), {noreply, S#state{next_run=0}}; true -> {noreply, S#state{last_time=Epoch}} end, reply_and_wait(Reply, State). do_job_run(#state{job_ref=Ref, next_run=Time, job={When, Job}, opts=Opts} = S) -> - case Opts of - #{on_job_start := {M,F}} -> - M:F(Ref); - #{on_job_start := F} when is_function(F, 1) -> - F(Ref); - _ -> - ok - end, - execute(Job, Ref, Time, maps:get(on_job_end, Opts, undefined)), + Res = do_job_start(Ref, maps:get(on_job_start, Opts, undefined)), + Res /= ignore andalso execute(Job, Ref, Time, maps:get(on_job_end, Opts, undefined)), case When of {once, _} -> stop; _ -> S#state.fast_forward orelse timer:sleep(1), noreply end. +do_job_start(_, undefined) -> ok; +do_job_start(Ref, {M,F}) -> M:F(Ref); +do_job_start(Ref, F) when is_function(F, 1) -> F(Ref). + execute(Job, Ref, Time, OnEnd) when is_function(Job, 2) -> safe_spawn(Ref, fun() -> Job(Ref, Time) end, OnEnd); execute(Job, Ref, _, OnEnd) when is_function(Job, 0) -> safe_spawn(Ref, Job, OnEnd); execute({M, F}, Ref, Time, OnEnd) when is_atom(M), is_atom(F) -> %% The exported function is checked for arity 0 or 2 when the job is added case erlang:function_exported(M, F, 2) of true -> safe_spawn(Ref, fun() -> M:F(Ref, Time) end, OnEnd); false -> safe_spawn(Ref, fun() -> M:F() end, OnEnd) end; execute({M, F, A}, Ref, _Time, OnEnd) when is_atom(M), is_atom(F), is_list(A) -> safe_spawn(Ref, fun() -> apply(M, F, A) end, OnEnd). safe_spawn(Ref, Fun, _OnEnd = {M,F}) when is_atom(M), is_atom(F) -> safe_spawn(Ref, Fun, fun(JobRef, Res) -> M:F(JobRef, Res) end); safe_spawn(Ref, Fun, OnEnd) when is_function(OnEnd, 2) -> proc_lib:spawn(fun() -> try OnEnd(Ref, {ok, Fun()}) catch _:Reason:Stack -> OnEnd(Ref, {error, {Reason, Stack}}) end end); safe_spawn(_Ref, Fun, undefined) -> proc_lib:spawn(Fun). reply_and_wait(stop, State) -> {stop, normal, State}; reply_and_wait(Reply, #state{next_run=0} = State) -> reply_and_wait2(Reply, until_next_milliseconds(State)); reply_and_wait(Reply, #state{next_run=Next, last_run=Last} = State) when Next-Last =< 0 -> reply_and_wait2(Reply, {ok, {State, 1000}}); reply_and_wait(Reply, #state{last_time=Now, next_run=NextMsec} = State) -> NowTime = current_epoch(Now, State), Timeout = round_timeout(NextMsec-NowTime), reply_and_wait2(Reply, {ok, {State, Timeout}}). reply_and_wait2(noreply, {ok, {State, Timeout}}) -> {noreply, State, Timeout}; reply_and_wait2(Reply, {ok, {State, Timeout}}) -> {reply, Reply, State, Timeout}; reply_and_wait2(noreply, {error, {State, _}}) -> {stop, normal, State}; reply_and_wait2(Reply, {error, {State, _}}) -> {stop, normal, Reply, State}. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% The returned duration is set to the maximum of 1 hour at which %% point the duration is recalculated, so that daylight savings time %% adjustments don't affect the precision of when a task is run. -spec until_next_milliseconds(#state{}) -> {ok, {#state{}, erlcron:milliseconds()}} | {error, {#state{}, term()}}. until_next_milliseconds(#state{} = S) -> try Epoch = ecrn_util:epoch_milliseconds(), {Msec, S1} = until_next_time(S#state{last_time=Epoch}), {ok, update_next_run(S1, max(0, Msec))} catch ?EXCEPTION(_, E, ST) -> {error, {S, {E, ?GET_STACK(ST)}}} end. -spec update_next_run(#state{}, erlcron:seconds()) -> {#state{}, erlcron:milliseconds()}. update_next_run(#state{} = State, ?SEC_IN_A_DAY) -> {State, ?MAX_TIMEOUT_MSEC}; update_next_run(#state{last_time=Now} = State, Milliseconds) -> Timeout = round_timeout(Milliseconds), EpochS = current_epoch(Now, State), {State#state{next_run=EpochS+Milliseconds}, Timeout}. round_timeout(Milliseconds) -> trunc(max(0, min(Milliseconds, ?MAX_TIMEOUT_MSEC))). -type normalized_period() :: [{integer(), integer(), integer()}]. -type normalized_sched() :: {once, {relative|absolute, integer()}} | {daily, normalized_period()} | {weekly, [integer()], normalized_period()} | {monthly,integer(), normalized_period()}. -spec normalize(erlcron:run_when(), calendar:datetime()) -> normalized_sched(). normalize({once, I}, _) when is_integer(I) -> {once, {relative, to_milliseconds(I)}}; normalize({once, {H,M,S}=T}, {_, Time}) when is_integer(H), is_integer(M), is_integer(S) , H >= 0, H < 24, M >= 0, M < 59, S >= 0, S < 59 -> T < Time andalso throw({time_given_in_the_past, T}), {once, {absolute, resolve_time(T)}}; normalize({once, Period}, _) -> {once, {absolute, resolve_time(Period)}}; normalize({daily, Period}, _) -> {daily, lists:sort(resolve_period(Period))}; normalize({weekly, DoW, Period}, _) -> {weekly, resolve_dow(DoW), lists:sort(resolve_period(Period))}; normalize({monthly, Day, Period}, TodayDate) when is_integer(Day) -> normalize({monthly, [Day], Period}, TodayDate); normalize({monthly, Days, Period}=T, {{Y,M,_},_}) when is_list(Days) -> case [Day || Day <- Days, not is_integer(Day) orelse Day < -30 orelse Day > 31] of [] -> ok; _ -> throw({invalid_days_in_schedule, T}) end, {PosDays, NegDays} = lists:partition(fun(I) -> I > 0 end, Days), {ThisNextMonthDays, _State} = update_dom(Y,M, {undefined, {0,0, PosDays, NegDays}}, #state{job={T, undefined}}), {monthly, ThisNextMonthDays, lists:sort(resolve_period(Period))}; normalize(Other, _) -> throw({invalid_schedule, Other}). update_dom(Y,M, {_, {Y,M,_,_}}=When, State) -> {When, State}; update_dom(Y,M, {_, {_,_,PosDays,NegDays}}, State = #state{job = {{monthly, _, _Period}, Task}}) -> {_, _, ThisMonthDays} = month_days(Y, M, PosDays, NegDays, true), {NY,NM, NextMonFirstDay} = next_month_days(Y, M, PosDays, NegDays), ThisNextMonthDays = {ThisMonthDays, NY, NM, NextMonFirstDay}, When = {ThisNextMonthDays, {Y,M,PosDays,NegDays}}, {When, State#state{job={{monthly, When}, Task}}}. next_month_days(Y, 12, PosDays, NegDays) -> month_days(Y+1, 1, PosDays, NegDays, false); next_month_days(Y, M, [], NegDays) -> month_days(Y, M+1, [], NegDays, false); next_month_days(Y, M, PosDays, NegDays) -> % When checking next month, and PosDays contains days 29,30,31 % make sure that combining that with {Y,M} gives a valid date D = lists:min(PosDays), M1 = M+1, case calendar:valid_date({Y,M1,D}) of true -> month_days(Y, M1, PosDays, NegDays, false); false -> next_month_days(Y, M1, PosDays, NegDays) end. month_days(Y, M, PosDays, NegDays, false) -> LastDay = calendar:last_day_of_the_month(Y, M), Days = [I+LastDay || I <- NegDays] ++ PosDays, case [I || I <- Days, I =< LastDay, I > 0] of [] -> next_month_days(Y, M, PosDays, NegDays); L -> {Y, M, lists:min(L)} end; month_days(Y, M, PosDays, [], true) -> LastDay = calendar:last_day_of_the_month(Y, M), {Y, M, [I || I <- lists:sort(PosDays), I =< LastDay]}; month_days(Y, M, PosDays, NegDays, true) -> LastDay = calendar:last_day_of_the_month(Y, M), AllDays = PosDays ++ [I+LastDay || I <- NegDays], UniqDays= lists:sort(sets:to_list(sets:from_list(AllDays))), check_days(Y, M, UniqDays), {Y, M, [I || I <- UniqDays, I =< LastDay, I > 0]}. check_days(Y,M,Days) -> lists:foreach(fun(I) -> Date = {Y,M,I}, calendar:valid_date(Date) orelse throw({invalid_date, Date}) end, lists:takewhile(fun(I) -> I > 28 end, lists:reverse(Days))). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_time(erlcron:milliseconds(), erlcron:run_when()) -> erlcron:milliseconds(). until_next_time(NowEpochTime, Sched) when is_integer(NowEpochTime), is_tuple(Sched) -> DateTime = erlang:posixtime_to_universaltime(to_ceiling_seconds(NowEpochTime)), NormSched = normalize(Sched, DateTime), State = set_internal_time(#state{job={NormSched, undefined}}, DateTime, NowEpochTime), {Res, _State1} = until_next_time(State), Res. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% @private -spec until_next_time(state()) -> {erlcron:milliseconds(), state()}. until_next_time(State = #state{job={Sched, _Task}}) -> until_next_time2(State, Sched). until_next_time2(State, {once, {relative, Msec}}) when is_integer(Msec) -> {Msec, State}; until_next_time2(State, {once, {absolute, Msec}}) when is_integer(Msec) -> {normalize_to_relative(State, Msec), State}; until_next_time2(State, {daily, Period}) -> {until_next_daytime(State, Period, current_time(State)), State}; until_next_time2(State, {weekly, DoW, Period}) -> {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), Days = find_dow(Today, DoW), NextDays = fun() -> I = Today+1, N = if I>7 -> 1; true -> I end, find_dow(N, DoW) end, {until_next_time_from_now(State, Period, Days, NextDays), State}; until_next_time2(State, {monthly, When, Period}) -> {{ThisYear, ThisMonth, Today}=YMD, _} = current_date(State), {{{ThisMonthDays, NextY, NextM, NextMonthFirstDOM}, _}, State1} = update_dom(ThisYear, ThisMonth, When, State), {YMD1, YMD2} = case lists:dropwhile(fun(I) -> I < Today end, ThisMonthDays) of [DOM1, DOM2 | _] -> {{ThisYear,ThisMonth,DOM1}, {ThisYear,ThisMonth,DOM2}}; [DOM|_] -> {{ThisYear,ThisMonth,DOM}, {NextY,NextM,NextMonthFirstDOM}}; [] -> {{NextY, NextM, NextMonthFirstDOM}, {0,0,0}} end, TodayGreg = to_greg_days(YMD), NextGreg = to_greg_days(YMD1), Days = NextGreg - TodayGreg, NextDays = fun() -> to_greg_days(YMD2) - TodayGreg end, {until_next_time_from_now(State1, Period, Days, NextDays), State1}. until_next_time_from_now(State, Period, 0, NextDays) when is_function(NextDays, 0) -> CurrentTime = current_time(State), F = fun() -> until_days_from_now(State, Period, NextDays()) end, case last_time(Period) of T when CurrentTime > T -> F(); _ -> EndTime = last_time(Period), case next_time(Period, CurrentTime) of I when I > EndTime -> F(); I -> I - CurrentTime end end; until_next_time_from_now(State, Period, Days, _NextDays) when Days > 0 -> until_days_from_now(State, Period, Days-1). to_greg_days({Y,M,D}) -> calendar:date_to_gregorian_days(Y,M,D). %% @doc Calculates the time since midnight in milliseconds until the next time this %% period is to occur during the day. -spec until_next_daytime(state(), normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_next_daytime(State, Period, MsecsFromMidnight) -> StartTime = first_time(Period), EndTime = last_time(Period), if MsecsFromMidnight > EndTime -> until_tomorrow(State, StartTime); true -> case next_time(Period, MsecsFromMidnight) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> T - MsecsFromMidnight end end. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow(state(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_tomorrow(State, StartTime) -> StartTime + 24*3600000 - current_time(State). %% @doc Calculates the duration in milliseconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), normalized_period(), integer()) -> erlcron:milliseconds(). until_days_from_now(State, Period, Days) -> MsecsUntilTomorrow = until_tomorrow(State, 0), MsecsUntilTomorrow + Days * 24 * 3600000 + until_next_daytime(State, Period, 0). %% @doc Calculates the first time in a given period. -spec first_time(normalized_period()) -> erlcron:milliseconds(). first_time([]) -> ?SEC_IN_A_DAY; first_time([{FromTime, _ToTime, _RepeatSec}|_]) -> FromTime. %% @doc Calculates the last time in a given period. -spec last_time(normalized_period()) -> erlcron:milliseconds(). last_time([]) -> ?SEC_IN_A_DAY; last_time(Period) when is_list(Period) -> F = fun({FromTime, _ToTime, 0}) -> FromTime; ({FromTime, ToTime, RepeatSec}) -> FromTime + ((ToTime-FromTime) div RepeatSec) * RepeatSec end, lists:max([F(R) || R <- Period]). %% @doc Calculates the first time in the given period after the given time. -spec next_time(normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). next_time([], _Time) -> ?SEC_IN_A_DAY; next_time(Period, Time) when is_list(Period), is_integer(Time) -> F = fun({FromTime, _ToTime, _RepeatSec}) when Time =< FromTime -> FromTime; ({_FromTime, _ToTime, 0}) -> ?SEC_IN_A_DAY; ({FromTime, _ToTime, RepeatSec}) -> A1 = ((Time-FromTime) div RepeatSec) * RepeatSec, A = if A1 < Time -> A1 + RepeatSec; true -> A1 end, FromTime + A end, case [F(R) || R = {_, ToTm, _} <- Period, Time =< ToTm] of [] -> ?SEC_IN_A_DAY; LL -> lists:min(LL) end. %% @doc Returns the current time, in milliseconds past midnight in local time zone. -spec current_time(state()) -> erlcron:milliseconds(). current_time(State = #state{last_time=Now}) -> % Take ceiling of time to the next second Msec = case (Now div 1000) * 1000 of Now -> 0; N -> Now-N end, {_, {H,M,S}} = current_date(State), to_milliseconds(S + M * 60 + H * 3600) + Msec. %% @doc Returns current date in local time current_date(#state{last_time=Now, ref_epoch=E, epoch_at_ref=S}) when is_integer(Now), Now > 0 -> Elapsed = Now - S, to_local_datetime(Elapsed + E). current_epoch(EpochMsec, #state{ref_epoch=RefEpoch, epoch_at_ref=Epoch}) -> Elapsed = EpochMsec - Epoch, Elapsed + RefEpoch. normalize_to_relative(State, Milliseconds) -> NowSec = current_time(State), Milliseconds - NowSec. %% @doc Returns a list of times given a periodic specification. -spec resolve_period([erlcron:period()] | erlcron:period()) -> [{erlcron:milliseconds(), erlcron:milliseconds(), erlcron:milliseconds()}]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration}) -> resolve_period({every, Duration, {between, {0,0,0}, {23,59,59}}}); resolve_period({every, Duration, {between, TimeA, TimeB}} = P) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), StartTime =< EndTime orelse throw({invalid_period, P}), [{StartTime, EndTime, Period}]; resolve_period(Time) -> T = resolve_time(Time), [{T, T, 0}]. %% @doc Returns seconds past midnight for a given time. -spec resolve_time(erlcron:cron_time()) -> erlcron:milliseconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> to_milliseconds(S + M * 60 + H * 3600); resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60 + S); resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60); resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> to_milliseconds(H * 3600); resolve_time({12, pm}) -> to_milliseconds(12 * 3600); resolve_time({H, pm}) when H < 12 -> to_milliseconds((H + 12) * 3600); resolve_time(Other) -> throw({invalid_time, Other}). %% @doc Returns seconds for a given duration. -spec resolve_dur(erlcron:duration()) -> erlcron:milliseconds(). resolve_dur({Hour, H}) when H==h; H==hr -> to_milliseconds(Hour * 3600); resolve_dur({Min, M}) when M==m; M==min -> to_milliseconds(Min * 60); resolve_dur({Sec, S}) when S==s; S==sec -> to_milliseconds(Sec); resolve_dur({Mil, M}) when M==ms; M==milli; M==millisecond -> Mil; resolve_dur(Other) -> throw({invalid_duration, Other}). %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow(erlcron:dow()) -> [integer()]. resolve_dow(I) when is_atom(I) -> [resolve_dow2(I)]; resolve_dow([I]) -> [resolve_dow2(I)]; resolve_dow(L) when is_list(L) -> lists:sort([resolve_dow2(I) || I <- L]). resolve_dow2(mon) -> 1; resolve_dow2(tue) -> 2; resolve_dow2(wed) -> 3; resolve_dow2(thu) -> 4; resolve_dow2(fri) -> 5; resolve_dow2(sat) -> 6; resolve_dow2(sun) -> 7. -spec find_dow(integer(), [integer()]) -> integer(). find_dow(_TodayDOW, []) -> throw(invalid_dow_period); find_dow(TodayDOW, [FirstDOW|_]=DOWs) -> find_dow(TodayDOW, DOWs, FirstDOW). find_dow(TodayDOW, [TodayDOW|_], _) -> 0; find_dow(TodayDOW, [DOW|_], _FirstDOW) when TodayDOW < DOW -> DOW-TodayDOW; find_dow(TodayDOW, [DOW|T], FirstDOW) when TodayDOW > DOW -> find_dow(TodayDOW, T, FirstDOW); find_dow(TodayDOW, [], FirstDOW) -> FirstDOW+7 - TodayDOW. set_internal_time(State, RefDate, CurEpochMsec) -> EpochS = to_seconds(CurEpochMsec), FloorE = to_milliseconds(EpochS), Msec = to_milliseconds(erlang:universaltime_to_posixtime(RefDate)), State1 = State#state{ref_epoch=Msec, epoch_at_ref=FloorE}, %Now = Msec + CurEpochMsec - FloorE, State1#state{last_time=CurEpochMsec}. %% @doc NewDate is in universal time. fast_forward(#state{ref_epoch=OldRefEpoch, next_run=NextRun}=S, NewRefEpoch, NewDate, Count) -> {Msec, State1} = until_next_time(S#state{last_time=OldRefEpoch, epoch_at_ref=OldRefEpoch}), Span = NewRefEpoch - OldRefEpoch, if Span =< Msec; Msec =:= 0 -> true; true -> RefMsec = OldRefEpoch + Msec, State2 = State1#state{ref_epoch = RefMsec+1, last_run=NextRun, next_run=RefMsec}, do_job_run(State2), case State2#state.job of {{once, _}, _} when Count =:= 1 -> Msec =< 0 andalso ?LOG_WARNING([{info, "One-time job executed immediately due to negative time shift"}, {time_shift_secs, to_seconds(Msec)}, {job_ref, State2#state.job_ref}, {job_when, State2#state.orig_when}]), false; _ -> fast_forward(State2, NewRefEpoch, NewDate, Count+1) end end. to_local_datetime(Milliseconds) when is_integer(Milliseconds) -> DT = to_universal_datetime(Milliseconds), erlang:universaltime_to_localtime(DT). to_universal_datetime(Milliseconds) -> erlang:posixtime_to_universaltime(to_seconds(Milliseconds)). to_milliseconds(Secs) -> Secs * 1000. to_seconds(MilliSec) -> MilliSec div 1000. to_ceiling_seconds(Msec) -> S = to_seconds(Msec), case to_milliseconds(S) of Msec -> S; _ -> S+1 end. %%%=================================================================== %%% Tests %%%=================================================================== -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -ifdef(EUNIT). dow_test() -> DOWs = resolve_dow([tue,wed,thu]), ?assertEqual([7], resolve_dow(sun)), ?assertEqual([7], resolve_dow([sun])), ?assertEqual([1,2], resolve_dow([mon,tue])), ?assertEqual([2,3,4], DOWs), ?assertEqual(1, find_dow(1, DOWs)), ?assertEqual(0, find_dow(2, DOWs)), ?assertEqual(0, find_dow(3, DOWs)), ?assertEqual(0, find_dow(4, DOWs)), ?assertEqual(4, find_dow(5, DOWs)), DOWs1 = resolve_dow([thu,sat]), ?assertEqual([4,6], DOWs1), ?assertEqual(3, find_dow(1, DOWs1)), ?assertEqual(2, find_dow(2, DOWs1)), ?assertEqual(1, find_dow(3, DOWs1)), ?assertEqual(0, find_dow(4, DOWs1)), ?assertEqual(1, find_dow(5, DOWs1)), ?assertEqual(0, find_dow(6, DOWs1)), ?assertEqual(4, find_dow(7, DOWs1)), ok. normalize_test() -> Date = {date(), {0,0,0}}, ?assertEqual({once,{relative,1000}}, normalize({once, 1}, Date)), ?assertEqual({once,{absolute,43200000}}, normalize({once, {12,pm}}, Date)), ?assertThrow({time_given_in_the_past,{2,3,4}}, normalize({once, {2,3,4}}, {date(), {2,3,5}})), ?assertEqual({once,{absolute,7384000}}, normalize({once, {2,3,4}}, Date)), ?assertEqual({daily,[{50400000,50400000,0}]}, normalize({daily, {2,pm}}, Date)), ?assertEqual({daily,[{0,86399000,20000}]}, normalize({daily, {every, {20,s}}}, Date)), ?assertEqual({daily,[{0,86399000,200}]}, normalize({daily, {every, {200,ms}}}, Date)), ?assertEqual({daily,[{0,86399000,2000}]}, normalize({daily, {every, {2000,millisecond}}}, Date)), ?assertEqual({daily,[{3600000,3600000,0},{7200000,7200000,0}]}, normalize({daily, [{2,am},{1,am}]}, Date)), ?assertEqual({daily,[{0,86399000,5000},{0,86399000,20000}]}, normalize({daily, [{every, {5,s}}, {every, {20,s}}]}, Date)), ?assertEqual({daily,[{3600000,7200000,20000}]}, normalize({daily, {every, {20,s}, {between, {1,am}, {2,am}}}}, Date)), ?assertEqual({weekly,[1], [{3600000,3600000,0}]}, normalize({weekly, mon, {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [mon,wed], {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [wed,mon], {1,am}}, Date)), ?assertEqual({monthly,{{[31],2019,2,28},{2019,1, [],[0]}},[{3600000,3600000,0}]}, normalize({monthly, 0, {1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[],[0]}},[{3600000,3600000,0}]}, normalize({monthly, [0], {1,am}}, {{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[], 2019,3,31},{2019,2,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly,[31], {1,am}}, {{2019,2,1},{0,0,0}})), ?assertEqual({monthly,{{[1, 31],2020,1,1}, {2019,12,[1],[0]}},[{3600000,3600000,0}]},normalize({monthly,[1,0],{1,am}},{{2019,12,1},{0,0,0}})), diff --git a/src/erlcron.erl b/src/erlcron.erl index e87ee1e..2dc60be 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,283 +1,293 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, cron/2, cron/3, at/2, at/3, at/4, daily/2, daily/3, daily/4, weekly/3, weekly/4, weekly/5, monthly/3,monthly/4, monthly/5, cancel/1, epoch/0, epoch_seconds/0, datetime/0, ref_datetime/0, set_datetime/1, set_datetime/2, reset_datetime/0, get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, + job_opts/0, + cron_opts/0, + job_start/0, + job_end/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0, milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | h | min | m | sec | s}. -type period() :: cron_time() | {every, duration()} | {every, duration(), constraint()}. -type dom() :: integer(). -type dow_day() :: mon | tue | wed | thu | fri | sat | sun. -type dow() :: dow_day() | [dow_day()]. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | fun(() -> term()) | fun((JobRef::atom()|reference(), calendar:datetime()) -> term()). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom()|[dom()], period()}. -type job() :: {run_when(), callable()} | {run_when(), callable(), job_opts()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference() | atom() | binary(). %% A job reference. +-type job_start() :: fun((JobRef::job_ref()) -> ignore | any()). +%% A function to be called before a job is started. If it returns the `ignore' +%% atom, the job function will not be executed. + +-type job_end() :: fun((JobRef::job_ref(), + Res :: {ok, term()} | {error, {Reason::term(), Stack::list()}}) + -> term()). +%% A function to be called after a job ended. The function is passed the +%% job's result. + -type job_opts() :: #{hostnames => [binary()|string()], id => term(), - on_job_start => {Mod::atom(), Fun::atom()} - | fun((JobRef::job_ref()) -> any()), - on_job_end => {Mod::atom(), Fun::atom()} - | fun((JobRef::job_ref(), - Res :: {ok, term()} | {error, {Reason::term(), Stack::list()}}) - -> term()) + on_job_start => {Mod::atom(), Fun::atom()} | job_start(), + on_job_end => {Mod::atom(), Fun::atom()} | job_end() }. %% Job options: %% <dl> %% <dt>hostnames => [Hostname]</dt> %% <dd>List of hostnames where the job is allowed to run</dd> %% <dt>id => ID</dt> %% <dd>An identifier of the job passed to `on_job_start' and `on_job_end' %% callbacks. It can be any term.</dd> %% <dt>on_job_start => {Mod, Fun} | fun(JobRef, ID) -> any()</dt> %% <dd>`Mod:Fun(Ref::job_ref(), ID::any())' function to call on job start. %% The result is ignored.</dd> %% <dt>{on_job_start, {Mod, Fun}} | fun(JobRef, ID, Result) -> term()</dt> %% <dd>`Mod:Fun(Ref::job_ref(), ID::any(), Result)' function to call after %% a job has ended. `Result' is `{ok, JobResult::term()}' or %% `{error, `{Reason, StackTrace}}' if there is an exception.</dd> %% </dl> -type cron_opts() :: job_opts(). %% Cron default options applicable to all jobs. See job_opts(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref() | ignored | already_started | {error, term()}. cron(Job) -> cron(make_ref(), Job, #{}). -spec cron(job()|job_ref(), job()|cron_opts()) -> job_ref() | ignored | already_started | {error, term()}. cron(Job, DefOpts) when is_map(DefOpts) -> cron(make_ref(), Job, DefOpts); cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) , is_tuple(Job) -> cron(JobRef, Job, #{}). %% @doc Schedule a job identified by a `JobRef'. %% A job reference can be a reference, atom, or binary. If it is %% an atom, a job will be locally registered by that name. %% Returns false if the job is not permitted to run on the current host -spec cron(job_ref(), job(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. cron(JobRef, Job, Opts) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) , is_tuple(Job), is_map(Opts) -> ecrn_cron_sup:add_job(JobRef, Job, Opts). %% @doc %% Convenience method to specify a job to run once at the given time %% or after the amount of time specified. -spec at(cron_time() | seconds(), callable()) -> job_ref() | ignored | already_started | {error, term()}. at(When, Fun) -> at(make_ref(), When, Fun). -spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. at(JobRef, When, Fun) -> cron(JobRef, {{once, When}, Fun}). -spec at(job_ref(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. at(JobRef, When, Fun, #{} = Opts) -> cron(JobRef, {{once, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a daily basis %% at a specific time. -spec daily(cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. daily(When, Fun) -> daily(make_ref(), When, Fun). -spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. daily(JobRef, When, Fun) -> cron(JobRef, {{daily, When}, Fun}). -spec daily(job_ref(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. daily(JobRef, When, Fun, #{} = Opts) -> cron(JobRef, {{daily, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. weekly(DOW, When, Fun) -> weekly(make_ref(), DOW, When, Fun). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. weekly(JobRef, DOW, When, Fun) -> cron(JobRef, {{weekly, DOW, When}, Fun}). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. weekly(JobRef, DOW, When, Fun, #{} = Opts) -> cron(JobRef, {{weekly, DOW, When}, Fun}, Opts). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. monthly(DOM, When, Fun) -> monthly(make_ref(), DOM, When, Fun). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref() | ignored | already_started | {error, term()}. monthly(JobRef, DOM, When, Fun) -> cron(JobRef, {{monthly, DOM, When}, Fun}). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function(), job_opts()) -> job_ref() | ignored | already_started | {error, term()}. monthly(JobRef, DOM, When, Fun, #{} = Opts) -> cron(JobRef, {{monthly, DOM, When}, Fun}, Opts). %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time in seconds millisince epoch. -spec epoch() -> milliseconds(). epoch() -> ecrn_util:epoch_milliseconds(). %% @doc %% Get the current date time in seconds since epoch. -spec epoch_seconds() -> seconds(). epoch_seconds() -> ecrn_util:epoch_seconds(). %% @doc %% Get the current date time of the erlcron system adjusted to reference. %% -spec datetime() -> {calendar:datetime(), milliseconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Get the reference date time of the erlcron system. %% -spec ref_datetime() -> {calendar:datetime(), milliseconds()}. ref_datetime() -> ecrn_control:ref_datetime(). %% @doc %% Set the current date time of the running erlcron system using local time. -spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime) -> set_datetime(DateTime, local). %% @doc %% Set the current date time of the running erlcron system using either local %% or universal time. The `TZ` parameter must contain an atom `local|universal`. -spec set_datetime(calendar:datetime(), local|universal) -> ok. set_datetime({D,T} = DateTime, TZ) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:set_datetime(DateTime, TZ). %% @doc %% Reset the reference datetime of erlcron system to current epoch time. -spec reset_datetime() -> ok. reset_datetime() -> ecrn_control:reset_datetime(). %% Get references of all running jobs -spec get_all_jobs() -> [job_ref()]. get_all_jobs() -> ecrn_reg:get_all_refs(). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime). diff --git a/test/ecrn_test.erl b/test/ecrn_test.erl index cca13de..dfa6e77 100644 --- a/test/ecrn_test.erl +++ b/test/ecrn_test.erl @@ -1,263 +1,273 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_test). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), application:start(erlcron) end, fun(_) -> application:stop(erlcron) end, [{timeout, 30, [ ?FuncTest(set_alarm), ?FuncTest(start_stop_funs), ?FuncTest(travel_back_in_time), ?FuncTest(cancel_alarm), ?FuncTest(big_time_jump), ?FuncTest(cron), ?FuncTest(cron_run_job_on_host), ?FuncTest(cron_skip_job_on_host), ?FuncTest(validation) ]}, {timeout, 30, [ ?FuncTest(weekly) ]}, {timeout, 30, [ ?FuncTest(weekly_every) ]} ]}. set_alarm() -> erlcron:set_datetime({{2000,1,1},{8,0,0}}), Self = self(), erlcron:at(test1, {9,0,0}, fun() -> Self ! ack1 end), erlcron:at(test2, {9,0,1}, fun() -> Self ! ack2 end), erlcron:daily(test3, {every, {1,s}, {between, {9,0,2}, {9,0,4}}}, fun() -> Self ! ack3 end), erlcron:set_datetime({{2000,1,1},{8,59,59}}), %% The alarm should trigger this nearly immediately. ?assertMatch(1, collect(ack1, 1500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(1, collect(ack2, 2500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(3, collect(ack3, 3000, 3)), erlcron:cancel(test3). cancel_alarm() -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(0, collect(ack, 125, 1)). start_stop_funs() -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {8,0,1}, Self = self(), Opts = #{on_job_start => fun(Ref) -> Self ! {start, Ref} end, on_job_end => fun(Ref, Res) -> Self ! {finish, Ref, Res} end}, Ref1 = erlcron:at(test1, AlarmTimeOfDay, fun(_, _) -> Self ! ack, 1234 end, Opts), ?assertEqual(test1, Ref1), ?assertMatch(1, collect({start, test1}, 1500, 1)), ?assertMatch(1, collect(ack, 125, 1)), ?assertMatch(1, collect({finish, test1, {ok, 1234}}, 1500, 1)), erlcron:set_datetime({Day,{8,0,0}}), - Len = length(lists:seq(1, rand:uniform(10)+2)), - Ref2 = erlcron:at(test2, AlarmTimeOfDay, fun(_, _) -> 1 = Len end, Opts), + Opts2 = #{on_job_start => fun(Ref) -> Self ! {ignored, Ref}, ignore end, + on_job_end => fun(Ref, Res) -> Self ! {finish, Ref, Res} end}, + Ref2 = erlcron:at(test2, AlarmTimeOfDay, fun(_, _) -> timer:sleep(60000), Self ! ack, 1000 end, Opts2), ?assertEqual(test2, Ref2), - ?assertMatch(1, collect({start, test2}, 1500, 1)), + ?assertMatch(1, collect({ignored, test2}, 1500, 1)), + ?assertMatch(0, collect({finish, test2, {ok, 1000}}, 125, 1)), + ?assertEqual(undefined, ecrn_reg:get(test2)), + + erlcron:set_datetime({Day,{8,0,0}}), + Len3 = length(lists:seq(1, rand:uniform(10)+2)), + Ref3 = erlcron:at(test3, AlarmTimeOfDay, fun(_, _) -> 1 = Len3 end, Opts), + + ?assertEqual(test3, Ref3), + ?assertMatch(1, collect({start, test3}, 1500, 1)), ?assertMatch(0, collect(1, 125, 1)), - ?assertMatch({finish, test2, {error,{{badmatch, _}, [_|_]}}}, receive _M -> _M after 1500 -> timeout end). + ?assertMatch({finish, test3, {error,{{badmatch, _}, [_|_]}}}, receive _M -> _M after 1500 -> timeout end). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump() -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:daily(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:daily(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)). travel_back_in_time() -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past, universal), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assertMatch(true, ExpectedSeconds =< calendar:datetime_to_gregorian_seconds(Past)), ?assertMatch(true, ExpectedSeconds < Seconds). cron() -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,59}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Ref1 = make_ref(), Job1 = {{daily, {3, 30, pm}}, fun(Ref, _) -> Self ! {ack, Ref} end}, Ref1 = erlcron:cron(Ref1, Job1), Job2 = {{daily, {3, 30, pm}}, fun(Ref, _) -> Self ! {ack, Ref} end}, test2 = erlcron:cron(test2, Job2), Job3 = {{daily, {3, 30, pm}}, fun() -> Self ! {ack, test3} end}, test3 = erlcron:cron(test3, Job3), Job4 = {{daily, {3, 30, pm}}, {?MODULE, sample_arity0}, #{on_job_end => fun(Ref, {ok, undefined}) -> Self ! {ack, Ref} end}}, test4 = erlcron:cron(test4, Job4), Job5 = {{daily, {3, 30, pm}}, {?MODULE, sample_arity2}, #{on_job_end => fun(_Ref, {ok, Res}) -> Self ! Res end}}, test5 = erlcron:cron(test5, Job5), Job6 = {{daily, {3, 30, pm}}, {?MODULE, sample_arityN, [test6, Self]}}, test6 = erlcron:cron(test6, Job6), ?assertMatch(1, collect({ack, Ref1}, 1000, 1)), ?assertMatch(1, collect({ack, test2}, 1000, 1)), ?assertMatch(1, collect({ack, test3}, 1000, 1)), ?assertMatch(1, collect({ack, test4}, 1000, 1)), ?assertMatch(1, collect({ack, test5}, 1000, 1)), ?assertMatch(1, collect({ack, test6}, 1000, 1)). sample_arity0() -> undefined. sample_arity2(Ref, _) -> {ack, Ref}. sample_arityN(Ref, Pid) -> Pid ! {ack, Ref}. %% Run job on this host cron_run_job_on_host() -> {ok, Host} = inet:gethostname(), erlcron:set_datetime({{2000, 1, 1}, {12, 59, 59}}), Self = self(), Ref = make_ref(), Job = {{once, {1, 00, pm}}, fun(_,_) -> Self ! Ref end, #{hostnames => [Host]}}, ?assert(is_reference(erlcron:cron(Job))), ?assertMatch(1, collect(Ref, 2500, 1)). %% Don't add job when executed on a disallowed host cron_skip_job_on_host() -> {ok, Host} = inet:gethostname(), Self = self(), Ref = make_ref(), Job = {{once, {1, 00, pm}}, fun(_,_) -> Self ! Ref end, #{hostnames => [Host ++ "123"]}}, ?assertEqual(ignored, erlcron:cron(Job)). validation() -> erlcron:set_datetime({{2000,1,1}, {15,0,0}}), ?assertMatch(ok, ecrn_agent:validate({once, {3, 30, pm}})), erlcron:set_datetime({{2000,1,1}, {15,31,0}}), ?assertMatch({error,{specified_time_past_seconds_ago, -60}}, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({once, 3600})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {0,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,sec}, {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, fri, {every, {5,sec}}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 4, {2, am}})), ?assertMatch({error,{invalid_time,{55,22,am}}}, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch({error,{invalid_days_in_schedule,{monthly,"A",{55,am}}}}, ecrn_agent:validate({monthly, 65, {55, am}})). weekly() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, sun], {9,0,0}}, fun() -> Self ! weekly end}), Pattern = [1, 1, 0, 0, 0, 0, 0, 1], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). weekly_every() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, mon], {every, {29, sec}, {between, {9, 0, 0}, {9, 1, 0}}}}, fun() -> Self ! weekly end}), Pattern = [3, 0, 3, 0, 0, 0, 0, 3], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). %%%=================================================================== %%% Internal Functions %%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). collect(Msg, Timeout, Count) -> collect(Msg, Timeout, 0, Count). collect(_Msg, _Timeout, Count, Count) -> Count; collect(Msg, Timeout, I, Count) -> receive Msg -> collect(Msg, Timeout, I+1, Count) after Timeout -> I end. % check that for each day generated by DateF(I) for increasing I, Pattern[I] % weekly messages are received collect_weekly(DateF, TimeBefore, TimeAfter, Pattern) -> collect_weekly(DateF, TimeBefore, TimeAfter, Pattern, 0). collect_weekly(DateF, TimeBefore, TimeAfter, [N | PatternTail], I) -> erlcron:set_datetime({DateF(I), TimeBefore}), ?assertMatch(0, collect(weekly, 1000, 1)), erlcron:set_datetime({DateF(I), TimeAfter}), ?assertMatch(N, collect(weekly, 1000, N)), collect_weekly(DateF, TimeBefore, TimeAfter, PatternTail, I+1); collect_weekly(_DateF, _TimeBefore, _TimeAfter, [], _I) -> ok.
erlware/erlcron
0d2a82d92ae72d72c3a121c4144f88a197dd6efa
Add job on_job_start and on_job_end optional callbacks
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 223bb60..3f4509c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,24 +1,24 @@ name: CI on: push: pull_request: branches: [ $default-branch ] release: types: - created jobs: test: name: "Erlang Test" runs-on: ubuntu-latest strategy: matrix: - otp: [23, 24, 25] + otp: [24, 25] fail-fast: false container: image: erlang:${{ matrix.otp }} steps: - uses: actions/checkout@v3 - name: Test run: make diff --git a/README.md b/README.md index 3f90640..5737ed5 100644 --- a/README.md +++ b/README.md @@ -1,177 +1,195 @@ Erlcron ======= Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The syntax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. Unlike cron's one-minute resolution, erlcron has a millisecond resolution. It does handle Daylight Savings Time changes (but not the cases when the system clock is altered by small increments, in which case the next execution of a scheduled task may be imprecise). Cron Job Description Examples: ```erlang {{once, {3, 30, pm}, fun() -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}, fun(JobRef, CurrDateTime) -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, fun(_JobRef, _DateTime) -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, {fun(_JobRef, _DateTime) -> io:fwrite("It's 2 Wednesday morning~n") end} {{weekly, [tue,wed], {2, am}}, {fun(_, Now) -> io:format("Now is ~p~n", [Now]) end} {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} {{monthly, [1, 7, 14], {2, am}}, {io, fwrite, ["Every 1st, 7th, 14th of the month!~n"]}} {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} {{monthly, [0, -1], {2, am}}, {io, fwrite, ["Last two days of the month!~n"]}} {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} %% Days of month less or equal to zero are subtracted from the end of the month {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} ``` Adding a cron to the system: ```erlang Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job). ``` Cron jobs can be given named atom references: ```erlang erlcron:cron(test_job1, {{once, {3,pm}}, {io, fwrite, "It's 3pm"}}). ``` A simple way to add a daily cron: erlcron:daily({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. ```erlang erlcron:at(300, Fun). ``` Cancel a running job. ```erlang erlcron:cancel(JobRef). ``` Get the current reference (universal) date time of the system. ```erlang erlcron:datetime(). ``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:set_datetime(DateTime). ``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(DateTime). ``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(Nodes, DateTime). ``` The application cron can be pre-configured through environment variables in the config file that all applications can load in the Erlang VM start. The app.config file can be as follow: ```erlang [ {erlcron, [ {crontab, [ {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, %% A job may be specified to be run only if the current host %% is in the list of given hostnames. If default crontab %% options are provided in the `defaults` setting, %% the job-specific options will override corresponding - %% default options. - {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}, #{hostnames => ["somehost"]}, + %% default options. See erlcron:job_opts() for available + %% options. + {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}, + #{hostnames => ["somehost"]}, {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} ]}, %% Instead of specifying individual options for each job, you can %% define default options here. - {defaults, #{hostnames => ["myhost"]}} + {defaults, #{ + %% Limit jobs to run only on the given list of hosts + hostnames => ["myhost"], + + %% Function `fun((Ref) -> ok)` to call before a job is started + on_job_start => {some_module, function}, + + %% Function `fun((Ref, Status :: {ok, Result}|{error, {Reason, StackTrace}}) -> ok)` + %% to call after a job has ended + on_job_end => {some_module, function} + }} ]} ]. ``` So, when the app will be started, all configurations will be loaded. Note that the limitation is that in the config file is impossible load an anonymous function (or lambda function) so, you only can use {M,F,A} format. + +If an `on_job_start` or `on_job_end` functions are provided for any job or as +default settings, it's the responsibility of a developer to make sure that +those functions handle exceptions, since the failure in those functions will +cause the supervisor to restart the job up until the supervisor reaches its +maximum restart intensity. diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 3627daf..dd97786 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,758 +1,789 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API --export([start_link/2, +-export([start_link/3, cancel/1, next_run/1, get_datetime/1, get_datetime/2, set_datetime/3, set_datetime/4, recalculate/1, validate/1, until_next_time/2, normalize/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, - alarm_ref, + opts, + job_ref, ref_epoch, epoch_at_ref, fast_forward=false, last_time, next_run, % Time in EPOCH seconds until task's next execution last_run, % Time in EPOCH seconds when the task was last run orig_when }). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 1000). -define(MAX_TIMEOUT_SEC, 1800). -define(MAX_TIMEOUT_MSEC, 1800000). -define(SEC_IN_A_DAY, 86400). %% compatibility -ifdef(OTP_RELEASE). %% this implies 21 or higher -define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). -define(GET_STACK(Stacktrace), Stacktrace). -include_lib("kernel/include/logger.hrl"). -else. -define(EXCEPTION(Class, Reason, _), Class:Reason). -define(GET_STACK(_), erlang:get_stacktrace()). -define(LOG_ERROR(Report), error_logger:error_report(Report)). -define(LOG_WARNING(Report), error_logger:warning_report(Report)). -endif. %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the appropriate job and the appropriate ref --spec start_link(erlcron:job_ref(), erlcron:job()) -> +-spec start_link(erlcron:job_ref(), erlcron:job(), erlcron:job_opts()) -> ignore | {error, Reason::term()} | {ok, pid()}. -start_link(JobRef, {When, _Task} = Job) when is_reference(JobRef) -> +start_link(JobRef, {When, _Task} = Job, JobOpts) when (is_reference(JobRef) orelse is_binary(JobRef)) + , is_map(JobOpts) -> {Sched, DateTime, ActualMsec} = normalize_when(When), - gen_server:start_link(?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []); -start_link(JobRef, {When, _Task} = Job) when is_atom(JobRef) -> + gen_server:start_link(?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec, JobOpts], []); +start_link(JobRef, {When, _Task} = Job, JobOpts) when is_atom(JobRef), is_map(JobOpts) -> {Sched, DateTime, ActualMsec} = normalize_when(When), - gen_server:start_link({local, JobRef}, ?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []). + gen_server:start_link({local, JobRef}, ?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec, JobOpts], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> get_datetime(Pid, local). -spec get_datetime(pid(), local|universal) -> calendar:datetime(). get_datetime(Pid, local) -> erlang:universaltime_to_localtime(get_datetime(Pid, universal)); get_datetime(Pid, universal) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) when is_pid(Pid); is_atom(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> set_datetime(Pid, DateTime, Actual, local). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds(), UTC::local|universal) -> ok | {error, term()}. set_datetime(Pid, DateTime, Actual, UTC) -> DT = case UTC of local -> erlang:localtime_to_universaltime(DateTime); universal -> DateTime end, Res = gen_server:call(Pid, {set_datetime, DT, Actual}, infinity), Res. -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Get job's next execution time -spec next_run(pid()) -> erlang:timestamp(). next_run(Pid) -> gen_server:call(Pid, next_run). %% @doc %% Validate that a run_when spec specified is correct. -spec validate(erlcron:run_when()) -> ok | {error, term()}. validate(Spec) -> - State = #state{job=undefined, alarm_ref=undefined}, + State = #state{job=undefined, job_ref=undefined}, {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), NewState = set_internal_time(State, DateTime, ActualMsec), try NormalSpec = normalize(Spec, DateTime), {Msec,_} = until_next_time(NewState#state{job={NormalSpec, undefined}}), Msec > 0 orelse throw({specified_time_past_seconds_ago, to_seconds(Msec)}), ok catch _Error:Reason -> {error, Reason} end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private -init([JobRef, {When, Task}, Sched, DateTime, ActualMsec]) -> +init([JobRef, {When, Task}, Sched, DateTime, ActualMsec, JobOpts]) -> try - State = set_internal_time(#state{alarm_ref=JobRef, job={Sched, Task}, + State = set_internal_time(#state{job_ref=JobRef, job={Sched, Task}, opts=JobOpts, last_run=0, next_run=0, orig_when=When}, DateTime, ActualMsec), case until_next_milliseconds(State) of {ok, {NewState, Timeout}} -> ecrn_reg:register(JobRef, self()), {ok, NewState, Timeout}; {error, {_, Reason}} -> throw(Reason) end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, JobRef}, {run_when, When}, {reason, E}, {stack, ?GET_STACK(ST)}]), {stop, normal} end. %% @private handle_call(next_run, _From, #state{next_run=Time} = State) -> reply_and_wait(Time, State); handle_call(get_datetime, _From, State) -> Epoch = ecrn_util:epoch_milliseconds(), Msec = current_epoch(Epoch, State), DT = to_universal_datetime(Msec), reply_and_wait(DT, State#state{last_time=Epoch}); handle_call({set_datetime, DateTime, CurrEpochMsec}, _From, State) -> try NewRefEpoch = to_milliseconds(erlang:universaltime_to_posixtime(DateTime)), case fast_forward(State#state{fast_forward=true}, NewRefEpoch, DateTime, 1) of true -> NewState = set_internal_time(State#state{next_run=0}, DateTime, CurrEpochMsec), reply_and_wait(ok, NewState); false -> {stop, normal, ok, State} end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, - {job_ref, State#state.alarm_ref}, + {job_ref, State#state.job_ref}, {run_when, element(1, State#state.orig_when)}, {reason, E}, {stack, ?GET_STACK(ST)}]), reply_and_wait({error, E}, State) end; handle_call(Msg, _From, State) -> {stop, State, {not_implemented, Msg}}. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast(Other, State) -> {stop, {not_implemented, Other}, State}. %% @private handle_info(timeout, S) -> process_timeout(S); handle_info({'EXIT', _, Reason}, State) -> {stop, Reason, State}; handle_info(_Msg, State) -> {noreply, State, 1000}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== normalize_when(When) -> {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), Sched = normalize(When, erlang:universaltime_to_localtime(DateTime)), {Sched, DateTime, ActualMsec}. process_timeout(#state{last_time=LastTime, next_run=NextRun, last_run=LastRun}=S) -> Epoch = ecrn_util:epoch_milliseconds(), NowMsec = current_epoch(Epoch, S), {Reply, State} = if LastTime < Epoch, NextRun > LastRun, NowMsec >= NextRun -> {do_job_run(S), S#state{last_run=NextRun, next_run=0}}; NextRun == LastRun -> S#state.fast_forward orelse timer:sleep(1), {noreply, S#state{next_run=0}}; true -> {noreply, S#state{last_time=Epoch}} end, reply_and_wait(Reply, State). -do_job_run(#state{alarm_ref=Ref, next_run=Time, job={When, Job}} = S) -> - execute(Job, Ref, Time), +do_job_run(#state{job_ref=Ref, next_run=Time, job={When, Job}, opts=Opts} = S) -> + case Opts of + #{on_job_start := {M,F}} -> + M:F(Ref); + #{on_job_start := F} when is_function(F, 1) -> + F(Ref); + _ -> + ok + end, + execute(Job, Ref, Time, maps:get(on_job_end, Opts, undefined)), case When of {once, _} -> stop; _ -> S#state.fast_forward orelse timer:sleep(1), noreply end. -execute(Job, Ref, Time) when is_function(Job, 2) -> - proc_lib:spawn(fun() -> Job(Ref, Time) end); -execute(Job, _, _) when is_function(Job, 0) -> - proc_lib:spawn(Job); -execute({M, F, A}, _, _) when is_atom(M), is_atom(F), is_list(A) -> - proc_lib:spawn(M, F, A). +execute(Job, Ref, Time, OnEnd) when is_function(Job, 2) -> + safe_spawn(Ref, fun() -> Job(Ref, Time) end, OnEnd); +execute(Job, Ref, _, OnEnd) when is_function(Job, 0) -> + safe_spawn(Ref, Job, OnEnd); +execute({M, F}, Ref, Time, OnEnd) when is_atom(M), is_atom(F) -> + %% The exported function is checked for arity 0 or 2 when the job is added + case erlang:function_exported(M, F, 2) of + true -> safe_spawn(Ref, fun() -> M:F(Ref, Time) end, OnEnd); + false -> safe_spawn(Ref, fun() -> M:F() end, OnEnd) + end; +execute({M, F, A}, Ref, _Time, OnEnd) when is_atom(M), is_atom(F), is_list(A) -> + safe_spawn(Ref, fun() -> apply(M, F, A) end, OnEnd). + +safe_spawn(Ref, Fun, _OnEnd = {M,F}) when is_atom(M), is_atom(F) -> + safe_spawn(Ref, Fun, fun(JobRef, Res) -> M:F(JobRef, Res) end); + +safe_spawn(Ref, Fun, OnEnd) when is_function(OnEnd, 2) -> + proc_lib:spawn(fun() -> + try + OnEnd(Ref, {ok, Fun()}) + catch _:Reason:Stack -> + OnEnd(Ref, {error, {Reason, Stack}}) + end + end); + +safe_spawn(_Ref, Fun, undefined) -> + proc_lib:spawn(Fun). reply_and_wait(stop, State) -> {stop, normal, State}; reply_and_wait(Reply, #state{next_run=0} = State) -> reply_and_wait2(Reply, until_next_milliseconds(State)); reply_and_wait(Reply, #state{next_run=Next, last_run=Last} = State) when Next-Last =< 0 -> reply_and_wait2(Reply, {ok, {State, 1000}}); reply_and_wait(Reply, #state{last_time=Now, next_run=NextMsec} = State) -> NowTime = current_epoch(Now, State), Timeout = round_timeout(NextMsec-NowTime), reply_and_wait2(Reply, {ok, {State, Timeout}}). reply_and_wait2(noreply, {ok, {State, Timeout}}) -> {noreply, State, Timeout}; reply_and_wait2(Reply, {ok, {State, Timeout}}) -> {reply, Reply, State, Timeout}; reply_and_wait2(noreply, {error, {State, _}}) -> {stop, normal, State}; reply_and_wait2(Reply, {error, {State, _}}) -> {stop, normal, Reply, State}. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% The returned duration is set to the maximum of 1 hour at which %% point the duration is recalculated, so that daylight savings time %% adjustments don't affect the precision of when a task is run. -spec until_next_milliseconds(#state{}) -> {ok, {#state{}, erlcron:milliseconds()}} | {error, {#state{}, term()}}. until_next_milliseconds(#state{} = S) -> try Epoch = ecrn_util:epoch_milliseconds(), {Msec, S1} = until_next_time(S#state{last_time=Epoch}), {ok, update_next_run(S1, max(0, Msec))} catch ?EXCEPTION(_, E, ST) -> {error, {S, {E, ?GET_STACK(ST)}}} end. -spec update_next_run(#state{}, erlcron:seconds()) -> {#state{}, erlcron:milliseconds()}. update_next_run(#state{} = State, ?SEC_IN_A_DAY) -> {State, ?MAX_TIMEOUT_MSEC}; update_next_run(#state{last_time=Now} = State, Milliseconds) -> Timeout = round_timeout(Milliseconds), EpochS = current_epoch(Now, State), {State#state{next_run=EpochS+Milliseconds}, Timeout}. round_timeout(Milliseconds) -> trunc(max(0, min(Milliseconds, ?MAX_TIMEOUT_MSEC))). -type normalized_period() :: [{integer(), integer(), integer()}]. -type normalized_sched() :: {once, {relative|absolute, integer()}} | {daily, normalized_period()} | {weekly, [integer()], normalized_period()} | {monthly,integer(), normalized_period()}. -spec normalize(erlcron:run_when(), calendar:datetime()) -> normalized_sched(). normalize({once, I}, _) when is_integer(I) -> {once, {relative, to_milliseconds(I)}}; normalize({once, {H,M,S}=T}, {_, Time}) when is_integer(H), is_integer(M), is_integer(S) , H >= 0, H < 24, M >= 0, M < 59, S >= 0, S < 59 -> T < Time andalso throw({time_given_in_the_past, T}), {once, {absolute, resolve_time(T)}}; normalize({once, Period}, _) -> {once, {absolute, resolve_time(Period)}}; normalize({daily, Period}, _) -> {daily, lists:sort(resolve_period(Period))}; normalize({weekly, DoW, Period}, _) -> {weekly, resolve_dow(DoW), lists:sort(resolve_period(Period))}; normalize({monthly, Day, Period}, TodayDate) when is_integer(Day) -> normalize({monthly, [Day], Period}, TodayDate); normalize({monthly, Days, Period}=T, {{Y,M,_},_}) when is_list(Days) -> case [Day || Day <- Days, not is_integer(Day) orelse Day < -30 orelse Day > 31] of [] -> ok; _ -> throw({invalid_days_in_schedule, T}) end, {PosDays, NegDays} = lists:partition(fun(I) -> I > 0 end, Days), {ThisNextMonthDays, _State} = update_dom(Y,M, {undefined, {0,0, PosDays, NegDays}}, #state{job={T, undefined}}), {monthly, ThisNextMonthDays, lists:sort(resolve_period(Period))}; normalize(Other, _) -> throw({invalid_schedule, Other}). update_dom(Y,M, {_, {Y,M,_,_}}=When, State) -> {When, State}; update_dom(Y,M, {_, {_,_,PosDays,NegDays}}, State = #state{job = {{monthly, _, _Period}, Task}}) -> {_, _, ThisMonthDays} = month_days(Y, M, PosDays, NegDays, true), {NY,NM, NextMonFirstDay} = next_month_days(Y, M, PosDays, NegDays), ThisNextMonthDays = {ThisMonthDays, NY, NM, NextMonFirstDay}, When = {ThisNextMonthDays, {Y,M,PosDays,NegDays}}, {When, State#state{job={{monthly, When}, Task}}}. next_month_days(Y, 12, PosDays, NegDays) -> month_days(Y+1, 1, PosDays, NegDays, false); next_month_days(Y, M, [], NegDays) -> month_days(Y, M+1, [], NegDays, false); next_month_days(Y, M, PosDays, NegDays) -> % When checking next month, and PosDays contains days 29,30,31 % make sure that combining that with {Y,M} gives a valid date D = lists:min(PosDays), M1 = M+1, case calendar:valid_date({Y,M1,D}) of true -> month_days(Y, M1, PosDays, NegDays, false); false -> next_month_days(Y, M1, PosDays, NegDays) end. month_days(Y, M, PosDays, NegDays, false) -> LastDay = calendar:last_day_of_the_month(Y, M), Days = [I+LastDay || I <- NegDays] ++ PosDays, case [I || I <- Days, I =< LastDay, I > 0] of [] -> next_month_days(Y, M, PosDays, NegDays); L -> {Y, M, lists:min(L)} end; month_days(Y, M, PosDays, [], true) -> LastDay = calendar:last_day_of_the_month(Y, M), {Y, M, [I || I <- lists:sort(PosDays), I =< LastDay]}; month_days(Y, M, PosDays, NegDays, true) -> LastDay = calendar:last_day_of_the_month(Y, M), AllDays = PosDays ++ [I+LastDay || I <- NegDays], UniqDays= lists:sort(sets:to_list(sets:from_list(AllDays))), check_days(Y, M, UniqDays), {Y, M, [I || I <- UniqDays, I =< LastDay, I > 0]}. check_days(Y,M,Days) -> lists:foreach(fun(I) -> Date = {Y,M,I}, calendar:valid_date(Date) orelse throw({invalid_date, Date}) end, lists:takewhile(fun(I) -> I > 28 end, lists:reverse(Days))). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_time(erlcron:milliseconds(), erlcron:run_when()) -> erlcron:milliseconds(). until_next_time(NowEpochTime, Sched) when is_integer(NowEpochTime), is_tuple(Sched) -> DateTime = erlang:posixtime_to_universaltime(to_ceiling_seconds(NowEpochTime)), NormSched = normalize(Sched, DateTime), State = set_internal_time(#state{job={NormSched, undefined}}, DateTime, NowEpochTime), {Res, _State1} = until_next_time(State), Res. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% @private -spec until_next_time(state()) -> {erlcron:milliseconds(), state()}. until_next_time(State = #state{job={Sched, _Task}}) -> until_next_time2(State, Sched). until_next_time2(State, {once, {relative, Msec}}) when is_integer(Msec) -> {Msec, State}; until_next_time2(State, {once, {absolute, Msec}}) when is_integer(Msec) -> {normalize_to_relative(State, Msec), State}; until_next_time2(State, {daily, Period}) -> {until_next_daytime(State, Period, current_time(State)), State}; until_next_time2(State, {weekly, DoW, Period}) -> {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), Days = find_dow(Today, DoW), NextDays = fun() -> I = Today+1, N = if I>7 -> 1; true -> I end, find_dow(N, DoW) end, {until_next_time_from_now(State, Period, Days, NextDays), State}; until_next_time2(State, {monthly, When, Period}) -> {{ThisYear, ThisMonth, Today}=YMD, _} = current_date(State), {{{ThisMonthDays, NextY, NextM, NextMonthFirstDOM}, _}, State1} = update_dom(ThisYear, ThisMonth, When, State), {YMD1, YMD2} = case lists:dropwhile(fun(I) -> I < Today end, ThisMonthDays) of [DOM1, DOM2 | _] -> {{ThisYear,ThisMonth,DOM1}, {ThisYear,ThisMonth,DOM2}}; [DOM|_] -> {{ThisYear,ThisMonth,DOM}, {NextY,NextM,NextMonthFirstDOM}}; [] -> {{NextY, NextM, NextMonthFirstDOM}, {0,0,0}} end, TodayGreg = to_greg_days(YMD), NextGreg = to_greg_days(YMD1), Days = NextGreg - TodayGreg, NextDays = fun() -> to_greg_days(YMD2) - TodayGreg end, {until_next_time_from_now(State1, Period, Days, NextDays), State1}. until_next_time_from_now(State, Period, 0, NextDays) when is_function(NextDays, 0) -> CurrentTime = current_time(State), F = fun() -> until_days_from_now(State, Period, NextDays()) end, case last_time(Period) of T when CurrentTime > T -> F(); _ -> EndTime = last_time(Period), case next_time(Period, CurrentTime) of I when I > EndTime -> F(); I -> I - CurrentTime end end; until_next_time_from_now(State, Period, Days, _NextDays) when Days > 0 -> until_days_from_now(State, Period, Days-1). to_greg_days({Y,M,D}) -> calendar:date_to_gregorian_days(Y,M,D). %% @doc Calculates the time since midnight in milliseconds until the next time this %% period is to occur during the day. -spec until_next_daytime(state(), normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_next_daytime(State, Period, MsecsFromMidnight) -> StartTime = first_time(Period), EndTime = last_time(Period), if MsecsFromMidnight > EndTime -> until_tomorrow(State, StartTime); true -> case next_time(Period, MsecsFromMidnight) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> T - MsecsFromMidnight end end. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow(state(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_tomorrow(State, StartTime) -> StartTime + 24*3600000 - current_time(State). %% @doc Calculates the duration in milliseconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), normalized_period(), integer()) -> erlcron:milliseconds(). until_days_from_now(State, Period, Days) -> MsecsUntilTomorrow = until_tomorrow(State, 0), MsecsUntilTomorrow + Days * 24 * 3600000 + until_next_daytime(State, Period, 0). %% @doc Calculates the first time in a given period. -spec first_time(normalized_period()) -> erlcron:milliseconds(). first_time([]) -> ?SEC_IN_A_DAY; first_time([{FromTime, _ToTime, _RepeatSec}|_]) -> FromTime. %% @doc Calculates the last time in a given period. -spec last_time(normalized_period()) -> erlcron:milliseconds(). last_time([]) -> ?SEC_IN_A_DAY; last_time(Period) when is_list(Period) -> F = fun({FromTime, _ToTime, 0}) -> FromTime; ({FromTime, ToTime, RepeatSec}) -> FromTime + ((ToTime-FromTime) div RepeatSec) * RepeatSec end, lists:max([F(R) || R <- Period]). %% @doc Calculates the first time in the given period after the given time. -spec next_time(normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). next_time([], _Time) -> ?SEC_IN_A_DAY; next_time(Period, Time) when is_list(Period), is_integer(Time) -> F = fun({FromTime, _ToTime, _RepeatSec}) when Time =< FromTime -> FromTime; ({_FromTime, _ToTime, 0}) -> ?SEC_IN_A_DAY; ({FromTime, _ToTime, RepeatSec}) -> A1 = ((Time-FromTime) div RepeatSec) * RepeatSec, A = if A1 < Time -> A1 + RepeatSec; true -> A1 end, FromTime + A end, case [F(R) || R = {_, ToTm, _} <- Period, Time =< ToTm] of [] -> ?SEC_IN_A_DAY; LL -> lists:min(LL) end. %% @doc Returns the current time, in milliseconds past midnight in local time zone. -spec current_time(state()) -> erlcron:milliseconds(). current_time(State = #state{last_time=Now}) -> % Take ceiling of time to the next second Msec = case (Now div 1000) * 1000 of Now -> 0; N -> Now-N end, {_, {H,M,S}} = current_date(State), to_milliseconds(S + M * 60 + H * 3600) + Msec. %% @doc Returns current date in local time current_date(#state{last_time=Now, ref_epoch=E, epoch_at_ref=S}) when is_integer(Now), Now > 0 -> Elapsed = Now - S, to_local_datetime(Elapsed + E). current_epoch(EpochMsec, #state{ref_epoch=RefEpoch, epoch_at_ref=Epoch}) -> Elapsed = EpochMsec - Epoch, Elapsed + RefEpoch. normalize_to_relative(State, Milliseconds) -> NowSec = current_time(State), Milliseconds - NowSec. %% @doc Returns a list of times given a periodic specification. -spec resolve_period([erlcron:period()] | erlcron:period()) -> [{erlcron:milliseconds(), erlcron:milliseconds(), erlcron:milliseconds()}]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration}) -> resolve_period({every, Duration, {between, {0,0,0}, {23,59,59}}}); resolve_period({every, Duration, {between, TimeA, TimeB}} = P) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), StartTime =< EndTime orelse throw({invalid_period, P}), [{StartTime, EndTime, Period}]; resolve_period(Time) -> T = resolve_time(Time), [{T, T, 0}]. %% @doc Returns seconds past midnight for a given time. -spec resolve_time(erlcron:cron_time()) -> erlcron:milliseconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> to_milliseconds(S + M * 60 + H * 3600); resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60 + S); resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60); resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> to_milliseconds(H * 3600); resolve_time({12, pm}) -> to_milliseconds(12 * 3600); resolve_time({H, pm}) when H < 12 -> to_milliseconds((H + 12) * 3600); resolve_time(Other) -> throw({invalid_time, Other}). %% @doc Returns seconds for a given duration. -spec resolve_dur(erlcron:duration()) -> erlcron:milliseconds(). resolve_dur({Hour, H}) when H==h; H==hr -> to_milliseconds(Hour * 3600); resolve_dur({Min, M}) when M==m; M==min -> to_milliseconds(Min * 60); resolve_dur({Sec, S}) when S==s; S==sec -> to_milliseconds(Sec); resolve_dur({Mil, M}) when M==ms; M==milli; M==millisecond -> Mil; resolve_dur(Other) -> throw({invalid_duration, Other}). %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow(erlcron:dow()) -> [integer()]. resolve_dow(I) when is_atom(I) -> [resolve_dow2(I)]; resolve_dow([I]) -> [resolve_dow2(I)]; resolve_dow(L) when is_list(L) -> lists:sort([resolve_dow2(I) || I <- L]). resolve_dow2(mon) -> 1; resolve_dow2(tue) -> 2; resolve_dow2(wed) -> 3; resolve_dow2(thu) -> 4; resolve_dow2(fri) -> 5; resolve_dow2(sat) -> 6; resolve_dow2(sun) -> 7. -spec find_dow(integer(), [integer()]) -> integer(). find_dow(_TodayDOW, []) -> throw(invalid_dow_period); find_dow(TodayDOW, [FirstDOW|_]=DOWs) -> find_dow(TodayDOW, DOWs, FirstDOW). find_dow(TodayDOW, [TodayDOW|_], _) -> 0; find_dow(TodayDOW, [DOW|_], _FirstDOW) when TodayDOW < DOW -> DOW-TodayDOW; find_dow(TodayDOW, [DOW|T], FirstDOW) when TodayDOW > DOW -> find_dow(TodayDOW, T, FirstDOW); find_dow(TodayDOW, [], FirstDOW) -> FirstDOW+7 - TodayDOW. set_internal_time(State, RefDate, CurEpochMsec) -> EpochS = to_seconds(CurEpochMsec), FloorE = to_milliseconds(EpochS), Msec = to_milliseconds(erlang:universaltime_to_posixtime(RefDate)), State1 = State#state{ref_epoch=Msec, epoch_at_ref=FloorE}, %Now = Msec + CurEpochMsec - FloorE, State1#state{last_time=CurEpochMsec}. %% @doc NewDate is in universal time. fast_forward(#state{ref_epoch=OldRefEpoch, next_run=NextRun}=S, NewRefEpoch, NewDate, Count) -> {Msec, State1} = until_next_time(S#state{last_time=OldRefEpoch, epoch_at_ref=OldRefEpoch}), Span = NewRefEpoch - OldRefEpoch, if Span =< Msec; Msec =:= 0 -> true; true -> RefMsec = OldRefEpoch + Msec, State2 = State1#state{ref_epoch = RefMsec+1, last_run=NextRun, next_run=RefMsec}, do_job_run(State2), case State2#state.job of {{once, _}, _} when Count =:= 1 -> Msec =< 0 andalso ?LOG_WARNING([{info, "One-time job executed immediately due to negative time shift"}, {time_shift_secs, to_seconds(Msec)}, - {job_ref, State2#state.alarm_ref}, + {job_ref, State2#state.job_ref}, {job_when, State2#state.orig_when}]), false; _ -> fast_forward(State2, NewRefEpoch, NewDate, Count+1) end end. to_local_datetime(Milliseconds) when is_integer(Milliseconds) -> DT = to_universal_datetime(Milliseconds), erlang:universaltime_to_localtime(DT). to_universal_datetime(Milliseconds) -> erlang:posixtime_to_universaltime(to_seconds(Milliseconds)). to_milliseconds(Secs) -> Secs * 1000. to_seconds(MilliSec) -> MilliSec div 1000. to_ceiling_seconds(Msec) -> S = to_seconds(Msec), case to_milliseconds(S) of Msec -> S; _ -> S+1 end. %%%=================================================================== %%% Tests %%%=================================================================== -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -ifdef(EUNIT). dow_test() -> DOWs = resolve_dow([tue,wed,thu]), ?assertEqual([7], resolve_dow(sun)), ?assertEqual([7], resolve_dow([sun])), ?assertEqual([1,2], resolve_dow([mon,tue])), ?assertEqual([2,3,4], DOWs), ?assertEqual(1, find_dow(1, DOWs)), ?assertEqual(0, find_dow(2, DOWs)), ?assertEqual(0, find_dow(3, DOWs)), ?assertEqual(0, find_dow(4, DOWs)), ?assertEqual(4, find_dow(5, DOWs)), DOWs1 = resolve_dow([thu,sat]), ?assertEqual([4,6], DOWs1), ?assertEqual(3, find_dow(1, DOWs1)), ?assertEqual(2, find_dow(2, DOWs1)), ?assertEqual(1, find_dow(3, DOWs1)), ?assertEqual(0, find_dow(4, DOWs1)), ?assertEqual(1, find_dow(5, DOWs1)), ?assertEqual(0, find_dow(6, DOWs1)), ?assertEqual(4, find_dow(7, DOWs1)), ok. normalize_test() -> Date = {date(), {0,0,0}}, ?assertEqual({once,{relative,1000}}, normalize({once, 1}, Date)), ?assertEqual({once,{absolute,43200000}}, normalize({once, {12,pm}}, Date)), ?assertThrow({time_given_in_the_past,{2,3,4}}, normalize({once, {2,3,4}}, {date(), {2,3,5}})), ?assertEqual({once,{absolute,7384000}}, normalize({once, {2,3,4}}, Date)), ?assertEqual({daily,[{50400000,50400000,0}]}, normalize({daily, {2,pm}}, Date)), ?assertEqual({daily,[{0,86399000,20000}]}, normalize({daily, {every, {20,s}}}, Date)), ?assertEqual({daily,[{0,86399000,200}]}, normalize({daily, {every, {200,ms}}}, Date)), ?assertEqual({daily,[{0,86399000,2000}]}, normalize({daily, {every, {2000,millisecond}}}, Date)), ?assertEqual({daily,[{3600000,3600000,0},{7200000,7200000,0}]}, normalize({daily, [{2,am},{1,am}]}, Date)), ?assertEqual({daily,[{0,86399000,5000},{0,86399000,20000}]}, normalize({daily, [{every, {5,s}}, {every, {20,s}}]}, Date)), ?assertEqual({daily,[{3600000,7200000,20000}]}, normalize({daily, {every, {20,s}, {between, {1,am}, {2,am}}}}, Date)), ?assertEqual({weekly,[1], [{3600000,3600000,0}]}, normalize({weekly, mon, {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [mon,wed], {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [wed,mon], {1,am}}, Date)), ?assertEqual({monthly,{{[31],2019,2,28},{2019,1, [],[0]}},[{3600000,3600000,0}]}, normalize({monthly, 0, {1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[],[0]}},[{3600000,3600000,0}]}, normalize({monthly, [0], {1,am}}, {{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[], 2019,3,31},{2019,2,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly,[31], {1,am}}, {{2019,2,1},{0,0,0}})), ?assertEqual({monthly,{{[1, 31],2020,1,1}, {2019,12,[1],[0]}},[{3600000,3600000,0}]},normalize({monthly,[1,0],{1,am}},{{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[30,31],2020,1,30},{2019,12,[30,31],[]}},[{3600000,3600000,0}]},normalize({monthly,[30,31],{1,am}},{{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2019,3,31},{2019,1,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly, 31, {1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[29],2024,2,29},{2024,1,[29],[]}},[{3600000,3600000,0}]}, normalize({monthly, 29, {1,am}}, {{2024,1,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly, 31, {1,am}}, {{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[1], 2019,2,1}, {2019,1,[1],[-30]}},[{3600000,3600000,0}]}, normalize({monthly,[1,-30],{1,am}},{{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[1], 2019,3,1}, {2019,1,[],[-30]}}, [{3600000,3600000,0}]}, normalize({monthly,-30,{1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[30],2019,2,27},{2019,1,[],[-1]}}, [{0,86399000,20000}]}, normalize({monthly, -1, {every, {20,s}}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[28],2019,2,25},{2019,1,[],[-3]}}, [{0,0,0},{3600000,3600000,0}]}, normalize({monthly, -3, [{12,am}, {1,am}]}, {{2019,1,1},{0,0,0}})), ok. until_next_time_month_test() -> T = ecrn_util:localtime_to_epoch({{2019,1,1},{0,0,0}}), Test = fun(Epoch, Days, When) -> I = ecrn_agent:until_next_time(Epoch, {monthly, Days, When}), ecrn_util:epoch_to_datetime_string(Epoch+I) end, ?assertEqual("2019-01-31 01:00:00.000", Test(T, [0], {every, {20,s}, {between, {1,am}, {2,am}}})), ?assertEqual("2019-01-10 01:00:00.000", Test(T, [0,10], {every, {20,s}, {between, {1,am}, {2,am}}})), ?assertEqual("2019-01-03 00:00:00.000", Test(T, 3, {every, {20,s}})), ok. -endif. diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index fccc019..aa12fa4 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,64 +1,73 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> %application:start(crypto), application:start(eunit), %application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> setup(), {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. setup() -> case application:get_env(erlcron, crontab) of {ok, Crontab} -> Def = application:get_env(erlcron, defaults, #{}), is_map(Def) orelse erlang:error("erlcron/defaults config must be a map!"), lists:foreach(fun(CronJob) -> - erlcron:cron(CronJob, Def) + case erlcron:cron(CronJob, Def) of + ok -> + ok; + already_started -> + ok; + ignored -> + ok; + {error, Reason} -> + erlang:error({failed_to_add_cron_job, CronJob, Reason}) + end end, Crontab); undefined -> ok end. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index d1acc9a..10e6c61 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,110 +1,162 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2, add_job/3, all_jobs/0, terminate/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). add_job(JobRef, Job) -> add_job(JobRef, Job, #{}). %% @doc %% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job(), erlcron:cron_opts()) -> - erlcron:job_ref(). + erlcron:job_ref() | ignored | already_started | {error, term()}. add_job(JobRef, Job = {_, _Task}, CronOpts) when is_map(CronOpts) -> - add_job2(JobRef, Job, CronOpts); + add_job2(JobRef, Job, check_opts(JobRef, CronOpts)); add_job(JobRef, {When, Task, JobOpts}, CronOpts) when is_map(JobOpts) -> - add_job2(JobRef, {When, Task}, maps:merge(CronOpts, JobOpts)). - -add_job2(JobRef, Job = {_, Task}, Opts) - when is_function(Task, 2) - ; is_function(Task, 0) - ; is_tuple(Task), tuple_size(Task)==3 - , is_atom(element(1,Task)) - , is_atom(element(2,Task)) - , is_list(element(3,Task)) -> + add_job2(JobRef, {When, Task}, check_opts(JobRef, maps:merge(CronOpts, JobOpts))). + +add_job2(JobRef, Job = {_, Task}, Opts) -> case check_host(Opts) of true -> - case supervisor:start_child(?SERVER, [JobRef, Job]) of + check_task(JobRef, Task), + case supervisor:start_child(?SERVER, [JobRef, Job, Opts]) of {ok, _} -> JobRef; - {error, {already_started, _}} -> {error, already_started}; + {error, {already_started, _}} -> already_started; Other -> Other end; false -> - false + ignored end. %% @doc %% Get a list of all active jobs -spec all_jobs() -> [pid()]. all_jobs() -> [P || {_,P,_,_} <- supervisor:which_children(?SERVER)]. %% @doc %% Terminate a job terminate(Pid) when is_pid(Pid) -> supervisor:terminate_child(?SERVER, Pid). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> SupFlags = #{ strategy => simple_one_for_one, intensity => application:get_env(erlcron, sup_job_intensity, 3), period => application:get_env(erlcron, sup_job_period, 10) }, AChild = #{id => ecrn_agent, start => {ecrn_agent, start_link, []}, restart => transient, shutdown => brutal_kill, type => worker, modules => [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. %%%=================================================================== %%% Internal functions %%%=================================================================== +check_opts(JobRef, Map) -> + maps:foreach(fun + (hostnames, L) when is_list(L) -> + ok; + (on_job_start, MF) when tuple_size(MF)==2; is_function(MF, 1) -> + ok; + (on_job_end, MF) when tuple_size(MF)==2; is_function(MF, 2) -> + ok; + (K, V) -> + erlang:error({invalid_option_value, JobRef, {K, V}}) + end, Map), + Map. + check_host(Opts) -> case maps:find(hostnames, Opts) of {ok, Hosts} when is_list(Hosts) -> {ok, Host} = inet:gethostname(), lists:member(Host, [to_list(H) || H <- Hosts]); error -> true end. +check_task(JobRef, Task) when is_tuple(Task), (tuple_size(Task)==2 orelse tuple_size(Task)==3) -> + M = element(1, Task), + case code:ensure_loaded(M) of + {module, M} -> + ok; + {error, Err1} -> + erlang:error({module_not_loaded, JobRef, Task, Err1}) + end, + check_exists(JobRef, Task); +check_task(_, Task) when is_function(Task, 0) -> + ok; +check_task(_, Task) when is_function(Task, 2) -> + ok; +check_task(JobRef, Task) -> + erlang:error({invalid_job_task, JobRef, Task}). + +check_exists(JobRef, {M,F}) -> + check_exists2(JobRef, {M,F,undefined}); +check_exists(JobRef, {_,_,A} = MFA) when is_list(A) -> + check_exists2(JobRef, MFA). + +check_exists2(JobRef, {M,F,A} = Task) -> + case erlang:module_loaded(M) of + false -> + case code:ensure_loaded(M) of + {module, M} -> + ok; + {error, Err1} -> + erlang:error({module_not_loaded, JobRef, Task, Err1}) + end; + true -> + ok + end, + case A of + undefined -> + check_arity(JobRef, M, F, [0,2]); + _ when is_list(A) -> + check_arity(JobRef, M, F, [length(A)]) + end. + +check_arity(JobRef, M, F, Lengths) -> + lists:any(fun(Arity) -> erlang:function_exported(M,F,Arity) end, Lengths) + orelse erlang:error({wrong_arity_of_job_task, JobRef, {M,F,Lengths}}). + to_list(H) when is_binary(H) -> binary_to_list(H); to_list(H) when is_list(H) -> H. diff --git a/src/erlcron.erl b/src/erlcron.erl index 62b553b..e87ee1e 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,228 +1,283 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, - cron/1, cron/2, - at/2, at/3, - daily/2, daily/3, - weekly/3, weekly/4, - monthly/3,monthly/4, + cron/1, cron/2, cron/3, + at/2, at/3, at/4, + daily/2, daily/3, daily/4, + weekly/3, weekly/4, weekly/5, + monthly/3,monthly/4, monthly/5, cancel/1, epoch/0, epoch_seconds/0, datetime/0, ref_datetime/0, set_datetime/1, set_datetime/2, reset_datetime/0, get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0, milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | h | min | m | sec | s}. -type period() :: cron_time() | {every, duration()} | {every, duration(), constraint()}. -type dom() :: integer(). -type dow_day() :: mon | tue | wed | thu | fri | sat | sun. -type dow() :: dow_day() | [dow_day()]. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | fun(() -> term()) | fun((JobRef::atom()|reference(), calendar:datetime()) -> term()). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom()|[dom()], period()}. -type job() :: {run_when(), callable()} | {run_when(), callable(), job_opts()}. %% should be opaque but dialyzer does not allow it --type job_ref() :: reference() | atom(). - --type job_opts() :: #{hostnames => [binary()|string()]}. -%% Job options +-type job_ref() :: reference() | atom() | binary(). +%% A job reference. + +-type job_opts() :: + #{hostnames => [binary()|string()], + id => term(), + on_job_start => {Mod::atom(), Fun::atom()} + | fun((JobRef::job_ref()) -> any()), + on_job_end => {Mod::atom(), Fun::atom()} + | fun((JobRef::job_ref(), + Res :: {ok, term()} | {error, {Reason::term(), Stack::list()}}) + -> term()) + }. +%% Job options: %% <dl> -%% <dt>{hostnames, [Hostname]}</dt> -%% <dd>List of hostnames where the job is allowed to run</dd> +%% <dt>hostnames => [Hostname]</dt> +%% <dd>List of hostnames where the job is allowed to run</dd> +%% <dt>id => ID</dt> +%% <dd>An identifier of the job passed to `on_job_start' and `on_job_end' +%% callbacks. It can be any term.</dd> +%% <dt>on_job_start => {Mod, Fun} | fun(JobRef, ID) -> any()</dt> +%% <dd>`Mod:Fun(Ref::job_ref(), ID::any())' function to call on job start. +%% The result is ignored.</dd> +%% <dt>{on_job_start, {Mod, Fun}} | fun(JobRef, ID, Result) -> term()</dt> +%% <dd>`Mod:Fun(Ref::job_ref(), ID::any(), Result)' function to call after +%% a job has ended. `Result' is `{ok, JobResult::term()}' or +%% `{error, `{Reason, StackTrace}}' if there is an exception.</dd> %% </dl> -type cron_opts() :: job_opts(). %% Cron default options applicable to all jobs. See job_opts(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. --spec cron(job()) -> job_ref(). +-spec cron(job()) -> + job_ref() | ignored | already_started | {error, term()}. cron(Job) -> cron(make_ref(), Job, #{}). --spec cron(job()|job_ref(), job()|cron_opts()) -> job_ref(). +-spec cron(job()|job_ref(), job()|cron_opts()) -> + job_ref() | ignored | already_started | {error, term()}. cron(Job, DefOpts) when is_map(DefOpts) -> cron(make_ref(), Job, DefOpts); -cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef)) +cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) , is_tuple(Job) -> cron(JobRef, Job, #{}). +%% @doc Schedule a job identified by a `JobRef'. +%% A job reference can be a reference, atom, or binary. If it is +%% an atom, a job will be locally registered by that name. %% Returns false if the job is not permitted to run on the current host --spec cron(job_ref(), job(), job_opts()) -> job_ref() | false. -cron(JobRef, Job, Opts) when (is_atom(JobRef) orelse is_reference(JobRef)) +-spec cron(job_ref(), job(), job_opts()) -> + job_ref() | ignored | already_started | {error, term()}. +cron(JobRef, Job, Opts) when (is_atom(JobRef) orelse is_reference(JobRef) orelse is_binary(JobRef)) , is_tuple(Job), is_map(Opts) -> ecrn_cron_sup:add_job(JobRef, Job, Opts). %% @doc -%% Convenience method to specify a job to run once at the given time. --spec at(cron_time() | seconds(), callable()) -> job_ref(). +%% Convenience method to specify a job to run once at the given time +%% or after the amount of time specified. +-spec at(cron_time() | seconds(), callable()) -> + job_ref() | ignored | already_started | {error, term()}. at(When, Fun) -> at(make_ref(), When, Fun). --spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref(). +-spec at(job_ref(), cron_time() | seconds(), function()) -> + job_ref() | ignored | already_started | {error, term()}. at(JobRef, When, Fun) -> cron(JobRef, {{once, When}, Fun}). +-spec at(job_ref(), cron_time() | seconds(), function(), job_opts()) -> + job_ref() | ignored | already_started | {error, term()}. +at(JobRef, When, Fun, #{} = Opts) -> + cron(JobRef, {{once, When}, Fun}, Opts). + %% @doc %% Convenience method to specify a job run to run on a daily basis %% at a specific time. --spec daily(cron_time() | seconds(), function()) -> job_ref(). +-spec daily(cron_time() | seconds(), function()) -> + job_ref() | ignored | already_started | {error, term()}. daily(When, Fun) -> daily(make_ref(), When, Fun). --spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref(). +-spec daily(job_ref(), cron_time() | seconds(), function()) -> + job_ref() | ignored | already_started | {error, term()}. daily(JobRef, When, Fun) -> cron(JobRef, {{daily, When}, Fun}). +-spec daily(job_ref(), cron_time() | seconds(), function(), job_opts()) -> + job_ref() | ignored | already_started | {error, term()}. +daily(JobRef, When, Fun, #{} = Opts) -> + cron(JobRef, {{daily, When}, Fun}, Opts). + %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. --spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref(). +-spec weekly(dow(), cron_time() | seconds(), function()) -> + job_ref() | ignored | already_started | {error, term()}. weekly(DOW, When, Fun) -> weekly(make_ref(), DOW, When, Fun). --spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref(). +-spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> + job_ref() | ignored | already_started | {error, term()}. weekly(JobRef, DOW, When, Fun) -> cron(JobRef, {{weekly, DOW, When}, Fun}). +-spec weekly(job_ref(), dow(), cron_time() | seconds(), function(), job_opts()) -> + job_ref() | ignored | already_started | {error, term()}. +weekly(JobRef, DOW, When, Fun, #{} = Opts) -> + cron(JobRef, {{weekly, DOW, When}, Fun}, Opts). + %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. --spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref(). +-spec monthly(dom(), cron_time() | seconds(), function()) -> + job_ref() | ignored | already_started | {error, term()}. monthly(DOM, When, Fun) -> monthly(make_ref(), DOM, When, Fun). --spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref(). +-spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> + job_ref() | ignored | already_started | {error, term()}. monthly(JobRef, DOM, When, Fun) -> cron(JobRef, {{monthly, DOM, When}, Fun}). +-spec monthly(job_ref(), dom(), cron_time() | seconds(), function(), job_opts()) -> + job_ref() | ignored | already_started | {error, term()}. +monthly(JobRef, DOM, When, Fun, #{} = Opts) -> + cron(JobRef, {{monthly, DOM, When}, Fun}, Opts). + %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time in seconds millisince epoch. -spec epoch() -> milliseconds(). epoch() -> ecrn_util:epoch_milliseconds(). %% @doc %% Get the current date time in seconds since epoch. -spec epoch_seconds() -> seconds(). epoch_seconds() -> ecrn_util:epoch_seconds(). %% @doc %% Get the current date time of the erlcron system adjusted to reference. %% -spec datetime() -> {calendar:datetime(), milliseconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Get the reference date time of the erlcron system. %% -spec ref_datetime() -> {calendar:datetime(), milliseconds()}. ref_datetime() -> ecrn_control:ref_datetime(). %% @doc %% Set the current date time of the running erlcron system using local time. -spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime) -> set_datetime(DateTime, local). %% @doc %% Set the current date time of the running erlcron system using either local %% or universal time. The `TZ` parameter must contain an atom `local|universal`. -spec set_datetime(calendar:datetime(), local|universal) -> ok. set_datetime({D,T} = DateTime, TZ) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:set_datetime(DateTime, TZ). %% @doc %% Reset the reference datetime of erlcron system to current epoch time. -spec reset_datetime() -> ok. reset_datetime() -> ecrn_control:reset_datetime(). %% Get references of all running jobs -spec get_all_jobs() -> [job_ref()]. get_all_jobs() -> ecrn_reg:get_all_refs(). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime). diff --git a/test/ecrn_test.erl b/test/ecrn_test.erl index 42dc178..cca13de 100644 --- a/test/ecrn_test.erl +++ b/test/ecrn_test.erl @@ -1,217 +1,263 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_test). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), application:start(erlcron) end, fun(_) -> application:stop(erlcron) end, [{timeout, 30, [ ?FuncTest(set_alarm), + ?FuncTest(start_stop_funs), ?FuncTest(travel_back_in_time), ?FuncTest(cancel_alarm), ?FuncTest(big_time_jump), ?FuncTest(cron), ?FuncTest(cron_run_job_on_host), ?FuncTest(cron_skip_job_on_host), ?FuncTest(validation) ]}, {timeout, 30, [ ?FuncTest(weekly) ]}, {timeout, 30, [ ?FuncTest(weekly_every) ]} ]}. set_alarm() -> erlcron:set_datetime({{2000,1,1},{8,0,0}}), Self = self(), erlcron:at(test1, {9,0,0}, fun() -> Self ! ack1 end), erlcron:at(test2, {9,0,1}, fun() -> Self ! ack2 end), erlcron:daily(test3, {every, {1,s}, {between, {9,0,2}, {9,0,4}}}, fun() -> Self ! ack3 end), erlcron:set_datetime({{2000,1,1},{8,59,59}}), %% The alarm should trigger this nearly immediately. ?assertMatch(1, collect(ack1, 1500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(1, collect(ack2, 2500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(3, collect(ack3, 3000, 3)), erlcron:cancel(test3). cancel_alarm() -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), - Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> - Self ! ack - end), + Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(0, collect(ack, 125, 1)). +start_stop_funs() -> + Day = {2000,1,1}, + erlcron:set_datetime({Day,{8,0,0}}), + AlarmTimeOfDay = {8,0,1}, + + Self = self(), + Opts = #{on_job_start => fun(Ref) -> Self ! {start, Ref} end, + on_job_end => fun(Ref, Res) -> Self ! {finish, Ref, Res} end}, + Ref1 = erlcron:at(test1, AlarmTimeOfDay, fun(_, _) -> Self ! ack, 1234 end, Opts), + ?assertEqual(test1, Ref1), + ?assertMatch(1, collect({start, test1}, 1500, 1)), + ?assertMatch(1, collect(ack, 125, 1)), + ?assertMatch(1, collect({finish, test1, {ok, 1234}}, 1500, 1)), + + erlcron:set_datetime({Day,{8,0,0}}), + Len = length(lists:seq(1, rand:uniform(10)+2)), + Ref2 = erlcron:at(test2, AlarmTimeOfDay, fun(_, _) -> 1 = Len end, Opts), + + ?assertEqual(test2, Ref2), + ?assertMatch(1, collect({start, test2}, 1500, 1)), + ?assertMatch(0, collect(1, 125, 1)), + ?assertMatch({finish, test2, {error,{{badmatch, _}, [_|_]}}}, receive _M -> _M after 1500 -> timeout end). + %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump() -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:daily(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:daily(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)). travel_back_in_time() -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past, universal), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assertMatch(true, ExpectedSeconds =< calendar:datetime_to_gregorian_seconds(Past)), ?assertMatch(true, ExpectedSeconds < Seconds). -%% Time jumps ahead one day so we should see the alarms from both days. cron() -> Day1 = {2000,1,1}, - AlarmTimeOfDay = {15,29,58}, + AlarmTimeOfDay = {15,29,59}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), - Job = {{daily, {3, 30, pm}}, - fun(_, _) -> - Self ! ack - end}, + Ref1 = make_ref(), + Job1 = {{daily, {3, 30, pm}}, fun(Ref, _) -> Self ! {ack, Ref} end}, + Ref1 = erlcron:cron(Ref1, Job1), + + Job2 = {{daily, {3, 30, pm}}, fun(Ref, _) -> Self ! {ack, Ref} end}, + test2 = erlcron:cron(test2, Job2), + + Job3 = {{daily, {3, 30, pm}}, fun() -> Self ! {ack, test3} end}, + test3 = erlcron:cron(test3, Job3), + + Job4 = {{daily, {3, 30, pm}}, {?MODULE, sample_arity0}, + #{on_job_end => fun(Ref, {ok, undefined}) -> Self ! {ack, Ref} end}}, + test4 = erlcron:cron(test4, Job4), + + Job5 = {{daily, {3, 30, pm}}, {?MODULE, sample_arity2}, + #{on_job_end => fun(_Ref, {ok, Res}) -> Self ! Res end}}, + test5 = erlcron:cron(test5, Job5), + Job6 = {{daily, {3, 30, pm}}, {?MODULE, sample_arityN, [test6, Self]}}, + test6 = erlcron:cron(test6, Job6), - erlcron:cron(Job), + ?assertMatch(1, collect({ack, Ref1}, 1000, 1)), + ?assertMatch(1, collect({ack, test2}, 1000, 1)), + ?assertMatch(1, collect({ack, test3}, 1000, 1)), + ?assertMatch(1, collect({ack, test4}, 1000, 1)), + ?assertMatch(1, collect({ack, test5}, 1000, 1)), + ?assertMatch(1, collect({ack, test6}, 1000, 1)). - ?assertMatch(1, collect(ack, 2500, 1)). +sample_arity0() -> + undefined. +sample_arity2(Ref, _) -> + {ack, Ref}. +sample_arityN(Ref, Pid) -> + Pid ! {ack, Ref}. %% Run job on this host cron_run_job_on_host() -> {ok, Host} = inet:gethostname(), erlcron:set_datetime({{2000, 1, 1}, {12, 59, 59}}), Self = self(), Ref = make_ref(), Job = {{once, {1, 00, pm}}, fun(_,_) -> Self ! Ref end, #{hostnames => [Host]}}, ?assert(is_reference(erlcron:cron(Job))), ?assertMatch(1, collect(Ref, 2500, 1)). %% Don't add job when executed on a disallowed host cron_skip_job_on_host() -> {ok, Host} = inet:gethostname(), Self = self(), Ref = make_ref(), Job = {{once, {1, 00, pm}}, fun(_,_) -> Self ! Ref end, #{hostnames => [Host ++ "123"]}}, - ?assertEqual(false, erlcron:cron(Job)). + ?assertEqual(ignored, erlcron:cron(Job)). validation() -> erlcron:set_datetime({{2000,1,1}, {15,0,0}}), ?assertMatch(ok, ecrn_agent:validate({once, {3, 30, pm}})), erlcron:set_datetime({{2000,1,1}, {15,31,0}}), ?assertMatch({error,{specified_time_past_seconds_ago, -60}}, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({once, 3600})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {0,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,sec}, {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, fri, {every, {5,sec}}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 4, {2, am}})), ?assertMatch({error,{invalid_time,{55,22,am}}}, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch({error,{invalid_days_in_schedule,{monthly,"A",{55,am}}}}, ecrn_agent:validate({monthly, 65, {55, am}})). weekly() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, sun], {9,0,0}}, fun() -> Self ! weekly end}), Pattern = [1, 1, 0, 0, 0, 0, 0, 1], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). weekly_every() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, mon], {every, {29, sec}, {between, {9, 0, 0}, {9, 1, 0}}}}, fun() -> Self ! weekly end}), Pattern = [3, 0, 3, 0, 0, 0, 0, 3], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). %%%=================================================================== %%% Internal Functions %%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). collect(Msg, Timeout, Count) -> collect(Msg, Timeout, 0, Count). collect(_Msg, _Timeout, Count, Count) -> Count; collect(Msg, Timeout, I, Count) -> receive Msg -> collect(Msg, Timeout, I+1, Count) after Timeout -> I end. % check that for each day generated by DateF(I) for increasing I, Pattern[I] % weekly messages are received collect_weekly(DateF, TimeBefore, TimeAfter, Pattern) -> collect_weekly(DateF, TimeBefore, TimeAfter, Pattern, 0). collect_weekly(DateF, TimeBefore, TimeAfter, [N | PatternTail], I) -> erlcron:set_datetime({DateF(I), TimeBefore}), ?assertMatch(0, collect(weekly, 1000, 1)), erlcron:set_datetime({DateF(I), TimeAfter}), ?assertMatch(N, collect(weekly, 1000, N)), collect_weekly(DateF, TimeBefore, TimeAfter, PatternTail, I+1); collect_weekly(_DateF, _TimeBefore, _TimeAfter, [], _I) -> ok.
erlware/erlcron
bd72cc586d187b86b63ef8a7f9b85b52ad0cee98
Add job options and fix failing test
diff --git a/.gitignore b/.gitignore index c054362..02d1d7a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ ebin/*.beam ebin/*.app deps/* _build rebar3 TEST*.xml +.deps_plt +.eunit/ +.rebar/ diff --git a/README.md b/README.md index 446ca9b..3f90640 100644 --- a/README.md +++ b/README.md @@ -1,169 +1,177 @@ Erlcron ======= Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The syntax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. Unlike cron's one-minute resolution, erlcron has a millisecond resolution. It does handle Daylight Savings Time changes (but not the cases when the system clock is altered by small increments, in which case the next execution of a scheduled task may be imprecise). Cron Job Description Examples: ```erlang {{once, {3, 30, pm}, fun() -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}, fun(JobRef, CurrDateTime) -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, fun(_JobRef, _DateTime) -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, {fun(_JobRef, _DateTime) -> io:fwrite("It's 2 Wednesday morning~n") end} {{weekly, [tue,wed], {2, am}}, {fun(_, Now) -> io:format("Now is ~p~n", [Now]) end} {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} {{monthly, [1, 7, 14], {2, am}}, {io, fwrite, ["Every 1st, 7th, 14th of the month!~n"]}} {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} {{monthly, [0, -1], {2, am}}, {io, fwrite, ["Last two days of the month!~n"]}} {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} %% Days of month less or equal to zero are subtracted from the end of the month {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} ``` Adding a cron to the system: ```erlang Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job). ``` Cron jobs can be given named atom references: ```erlang erlcron:cron(test_job1, {{once, {3,pm}}, {io, fwrite, "It's 3pm"}}). ``` A simple way to add a daily cron: erlcron:daily({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. ```erlang erlcron:at(300, Fun). ``` Cancel a running job. ```erlang erlcron:cancel(JobRef). ``` Get the current reference (universal) date time of the system. ```erlang erlcron:datetime(). ``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:set_datetime(DateTime). ``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(DateTime). ``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(Nodes, DateTime). ``` The application cron can be pre-configured through environment variables in the config file that all applications can load in the Erlang VM start. The app.config file can be as follow: ```erlang [ {erlcron, [ {crontab, [ {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, - {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}}, + %% A job may be specified to be run only if the current host + %% is in the list of given hostnames. If default crontab + %% options are provided in the `defaults` setting, + %% the job-specific options will override corresponding + %% default options. + {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}, #{hostnames => ["somehost"]}, {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} + ]}, - ]} + %% Instead of specifying individual options for each job, you can + %% define default options here. + {defaults, #{hostnames => ["myhost"]}} ]} ]. ``` So, when the app will be started, all configurations will be loaded. Note that the limitation is that in the config file is impossible load an anonymous function (or lambda function) so, you only can use {M,F,A} format. diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index f90e7c5..fccc019 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,61 +1,64 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> %application:start(crypto), application:start(eunit), %application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> setup(), {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. setup() -> - case application:get_env(erlcron, crontab) of + case application:get_env(erlcron, crontab) of {ok, Crontab} -> + Def = application:get_env(erlcron, defaults, #{}), + is_map(Def) orelse + erlang:error("erlcron/defaults config must be a map!"), lists:foreach(fun(CronJob) -> - erlcron:cron(CronJob) + erlcron:cron(CronJob, Def) end, Crontab); undefined -> ok end. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index bab769b..d1acc9a 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,77 +1,110 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2, + add_job/3, all_jobs/0, terminate/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). - %% @doc -%% Add a chron job to be supervised +%% Add a cron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). -add_job(JobRef, Job = {_, Task}) when is_function(Task, 2) - ; is_function(Task, 0) - ; is_tuple(Task), tuple_size(Task)==3 - , is_atom(element(1,Task)) - , is_atom(element(2,Task)) - , is_list(element(3,Task)) -> - case supervisor:start_child(?SERVER, [JobRef, Job]) of - {ok, _} -> JobRef; - {error, {already_started, _}} -> {error, already_started}; - Other -> Other +add_job(JobRef, Job) -> + add_job(JobRef, Job, #{}). + +%% @doc +%% Add a cron job to be supervised +-spec add_job(erlcron:job_ref(), erlcron:job(), erlcron:cron_opts()) -> + erlcron:job_ref(). +add_job(JobRef, Job = {_, _Task}, CronOpts) when is_map(CronOpts) -> + add_job2(JobRef, Job, CronOpts); +add_job(JobRef, {When, Task, JobOpts}, CronOpts) when is_map(JobOpts) -> + add_job2(JobRef, {When, Task}, maps:merge(CronOpts, JobOpts)). + +add_job2(JobRef, Job = {_, Task}, Opts) + when is_function(Task, 2) + ; is_function(Task, 0) + ; is_tuple(Task), tuple_size(Task)==3 + , is_atom(element(1,Task)) + , is_atom(element(2,Task)) + , is_list(element(3,Task)) -> + case check_host(Opts) of + true -> + case supervisor:start_child(?SERVER, [JobRef, Job]) of + {ok, _} -> JobRef; + {error, {already_started, _}} -> {error, already_started}; + Other -> Other + end; + false -> + false end. %% @doc %% Get a list of all active jobs -spec all_jobs() -> [pid()]. all_jobs() -> [P || {_,P,_,_} <- supervisor:which_children(?SERVER)]. %% @doc %% Terminate a job terminate(Pid) when is_pid(Pid) -> supervisor:terminate_child(?SERVER, Pid). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> SupFlags = #{ strategy => simple_one_for_one, intensity => application:get_env(erlcron, sup_job_intensity, 3), period => application:get_env(erlcron, sup_job_period, 10) }, AChild = #{id => ecrn_agent, start => {ecrn_agent, start_link, []}, restart => transient, shutdown => brutal_kill, type => worker, modules => [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. + +%%%=================================================================== +%%% Internal functions +%%%=================================================================== +check_host(Opts) -> + case maps:find(hostnames, Opts) of + {ok, Hosts} when is_list(Hosts) -> + {ok, Host} = inet:gethostname(), + lists:member(Host, [to_list(H) || H <- Hosts]); + error -> + true + end. + +to_list(H) when is_binary(H) -> binary_to_list(H); +to_list(H) when is_list(H) -> H. diff --git a/src/erlcron.erl b/src/erlcron.erl index e6a0264..62b553b 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,201 +1,228 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, cron/2, at/2, at/3, daily/2, daily/3, weekly/3, weekly/4, monthly/3,monthly/4, cancel/1, epoch/0, epoch_seconds/0, datetime/0, ref_datetime/0, set_datetime/1, + set_datetime/2, reset_datetime/0, get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0, milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | h | min | m | sec | s}. -type period() :: cron_time() | {every, duration()} | {every, duration(), constraint()}. -type dom() :: integer(). -type dow_day() :: mon | tue | wed | thu | fri | sat | sun. -type dow() :: dow_day() | [dow_day()]. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | fun(() -> term()) | fun((JobRef::atom()|reference(), calendar:datetime()) -> term()). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom()|[dom()], period()}. --type job() :: {run_when(), callable()}. +-type job() :: {run_when(), callable()} + | {run_when(), callable(), job_opts()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference() | atom(). +-type job_opts() :: #{hostnames => [binary()|string()]}. +%% Job options +%% <dl> +%% <dt>{hostnames, [Hostname]}</dt> +%% <dd>List of hostnames where the job is allowed to run</dd> +%% </dl> + +-type cron_opts() :: job_opts(). +%% Cron default options applicable to all jobs. See job_opts(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref(). cron(Job) -> - cron(make_ref(), Job). + cron(make_ref(), Job, #{}). + +-spec cron(job()|job_ref(), job()|cron_opts()) -> job_ref(). +cron(Job, DefOpts) when is_map(DefOpts) -> + cron(make_ref(), Job, DefOpts); --spec cron(job_ref(), job()) -> job_ref(). cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef)) , is_tuple(Job) -> - ecrn_cron_sup:add_job(JobRef, Job). + cron(JobRef, Job, #{}). + +%% Returns false if the job is not permitted to run on the current host +-spec cron(job_ref(), job(), job_opts()) -> job_ref() | false. +cron(JobRef, Job, Opts) when (is_atom(JobRef) orelse is_reference(JobRef)) + , is_tuple(Job), is_map(Opts) -> + ecrn_cron_sup:add_job(JobRef, Job, Opts). %% @doc %% Convenience method to specify a job to run once at the given time. -spec at(cron_time() | seconds(), callable()) -> job_ref(). at(When, Fun) -> at(make_ref(), When, Fun). -spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref(). at(JobRef, When, Fun) -> cron(JobRef, {{once, When}, Fun}). %% @doc %% Convenience method to specify a job run to run on a daily basis %% at a specific time. -spec daily(cron_time() | seconds(), function()) -> job_ref(). daily(When, Fun) -> daily(make_ref(), When, Fun). -spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref(). daily(JobRef, When, Fun) -> cron(JobRef, {{daily, When}, Fun}). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref(). weekly(DOW, When, Fun) -> weekly(make_ref(), DOW, When, Fun). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref(). weekly(JobRef, DOW, When, Fun) -> cron(JobRef, {{weekly, DOW, When}, Fun}). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref(). monthly(DOM, When, Fun) -> monthly(make_ref(), DOM, When, Fun). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref(). monthly(JobRef, DOM, When, Fun) -> cron(JobRef, {{monthly, DOM, When}, Fun}). %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time in seconds millisince epoch. -spec epoch() -> milliseconds(). epoch() -> ecrn_util:epoch_milliseconds(). %% @doc %% Get the current date time in seconds since epoch. -spec epoch_seconds() -> seconds(). epoch_seconds() -> ecrn_util:epoch_seconds(). %% @doc %% Get the current date time of the erlcron system adjusted to reference. %% -spec datetime() -> {calendar:datetime(), milliseconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Get the reference date time of the erlcron system. %% -spec ref_datetime() -> {calendar:datetime(), milliseconds()}. ref_datetime() -> ecrn_control:ref_datetime(). %% @doc -%% Set the current date time of the running erlcron system. +%% Set the current date time of the running erlcron system using local time. -spec set_datetime(calendar:datetime()) -> ok. -set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> - ecrn_control:set_datetime(DateTime). +set_datetime(DateTime) -> + set_datetime(DateTime, local). + +%% @doc +%% Set the current date time of the running erlcron system using either local +%% or universal time. The `TZ` parameter must contain an atom `local|universal`. +-spec set_datetime(calendar:datetime(), local|universal) -> ok. +set_datetime({D,T} = DateTime, TZ) when tuple_size(D)==3, tuple_size(T)==3 -> + ecrn_control:set_datetime(DateTime, TZ). %% @doc %% Reset the reference datetime of erlcron system to current epoch time. -spec reset_datetime() -> ok. reset_datetime() -> ecrn_control:reset_datetime(). %% Get references of all running jobs -spec get_all_jobs() -> [job_ref()]. get_all_jobs() -> ecrn_reg:get_all_refs(). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> {Replies, BadNodes} when Replies :: [{node(), ok | {error, term()}}], BadNodes :: [node()]. multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime). diff --git a/test/ecrn_test.erl b/test/ecrn_test.erl index 1bcc396..42dc178 100644 --- a/test/ecrn_test.erl +++ b/test/ecrn_test.erl @@ -1,197 +1,217 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_test). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), application:start(erlcron) end, fun(_) -> application:stop(erlcron) end, [{timeout, 30, [ ?FuncTest(set_alarm), ?FuncTest(travel_back_in_time), ?FuncTest(cancel_alarm), ?FuncTest(big_time_jump), ?FuncTest(cron), + ?FuncTest(cron_run_job_on_host), + ?FuncTest(cron_skip_job_on_host), ?FuncTest(validation) ]}, {timeout, 30, [ ?FuncTest(weekly) ]}, {timeout, 30, [ ?FuncTest(weekly_every) ]} ]}. set_alarm() -> erlcron:set_datetime({{2000,1,1},{8,0,0}}), Self = self(), erlcron:at(test1, {9,0,0}, fun() -> Self ! ack1 end), erlcron:at(test2, {9,0,1}, fun() -> Self ! ack2 end), erlcron:daily(test3, {every, {1,s}, {between, {9,0,2}, {9,0,4}}}, fun() -> Self ! ack3 end), erlcron:set_datetime({{2000,1,1},{8,59,59}}), %% The alarm should trigger this nearly immediately. ?assertMatch(1, collect(ack1, 1500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(1, collect(ack2, 2500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(3, collect(ack3, 3000, 3)), erlcron:cancel(test3). cancel_alarm() -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(0, collect(ack, 125, 1)). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump() -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:daily(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:daily(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)). travel_back_in_time() -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, - erlcron:set_datetime(Past), + erlcron:set_datetime(Past, universal), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assertMatch(true, ExpectedSeconds =< calendar:datetime_to_gregorian_seconds(Past)), ?assertMatch(true, ExpectedSeconds < Seconds). - %% Time jumps ahead one day so we should see the alarms from both days. cron() -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,58}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Job = {{daily, {3, 30, pm}}, fun(_, _) -> Self ! ack end}, erlcron:cron(Job), ?assertMatch(1, collect(ack, 2500, 1)). +%% Run job on this host +cron_run_job_on_host() -> + {ok, Host} = inet:gethostname(), + erlcron:set_datetime({{2000, 1, 1}, {12, 59, 59}}), + Self = self(), + Ref = make_ref(), + Job = {{once, {1, 00, pm}}, fun(_,_) -> Self ! Ref end, #{hostnames => [Host]}}, + + ?assert(is_reference(erlcron:cron(Job))), + ?assertMatch(1, collect(Ref, 2500, 1)). + +%% Don't add job when executed on a disallowed host +cron_skip_job_on_host() -> + {ok, Host} = inet:gethostname(), + Self = self(), + Ref = make_ref(), + Job = {{once, {1, 00, pm}}, fun(_,_) -> Self ! Ref end, #{hostnames => [Host ++ "123"]}}, + ?assertEqual(false, erlcron:cron(Job)). + validation() -> erlcron:set_datetime({{2000,1,1}, {15,0,0}}), ?assertMatch(ok, ecrn_agent:validate({once, {3, 30, pm}})), erlcron:set_datetime({{2000,1,1}, {15,31,0}}), ?assertMatch({error,{specified_time_past_seconds_ago, -60}}, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({once, 3600})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {0,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,sec}, {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, fri, {every, {5,sec}}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 4, {2, am}})), ?assertMatch({error,{invalid_time,{55,22,am}}}, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch({error,{invalid_days_in_schedule,{monthly,"A",{55,am}}}}, ecrn_agent:validate({monthly, 65, {55, am}})). weekly() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, sun], {9,0,0}}, fun() -> Self ! weekly end}), Pattern = [1, 1, 0, 0, 0, 0, 0, 1], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). weekly_every() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, mon], {every, {29, sec}, {between, {9, 0, 0}, {9, 1, 0}}}}, fun() -> Self ! weekly end}), Pattern = [3, 0, 3, 0, 0, 0, 0, 3], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). %%%=================================================================== %%% Internal Functions %%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). collect(Msg, Timeout, Count) -> collect(Msg, Timeout, 0, Count). collect(_Msg, _Timeout, Count, Count) -> Count; collect(Msg, Timeout, I, Count) -> receive Msg -> collect(Msg, Timeout, I+1, Count) after Timeout -> I end. % check that for each day generated by DateF(I) for increasing I, Pattern[I] % weekly messages are received collect_weekly(DateF, TimeBefore, TimeAfter, Pattern) -> collect_weekly(DateF, TimeBefore, TimeAfter, Pattern, 0). collect_weekly(DateF, TimeBefore, TimeAfter, [N | PatternTail], I) -> erlcron:set_datetime({DateF(I), TimeBefore}), ?assertMatch(0, collect(weekly, 1000, 1)), erlcron:set_datetime({DateF(I), TimeAfter}), ?assertMatch(N, collect(weekly, 1000, N)), collect_weekly(DateF, TimeBefore, TimeAfter, PatternTail, I+1); collect_weekly(_DateF, _TimeBefore, _TimeAfter, [], _I) -> ok.
erlware/erlcron
90385b75da41ac7d033c8d57714e3ed0b4695418
Start use git vsn
diff --git a/src/erlcron.app.src b/src/erlcron.app.src index f9fc463..54662ae 100644 --- a/src/erlcron.app.src +++ b/src/erlcron.app.src @@ -1,7 +1,7 @@ {application,erlcron, [{description,"Erlang Implementation of cron"}, - {vsn,"0.1"}, + {vsn,git}, {modules,[]}, {registered,[ecrn_agent]}, {applications,[kernel,stdlib]}, {mod,{ecrn_app,[]}}]}.
erlware/erlcron
3a9dddb7fe079ade5f3e39ec248c7fa75a8f057c
Add GitHub Actions
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..e6d4c17 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,25 @@ +--- +name: Bug report +about: Create a report of bug for erlcron +title: '' +labels: '' +assignees: '' +--- + +## `erlcron` version +[Put release version here and update tag link(0.0.0) ...](https://github.com/erlware/erlcron.git) + +## `OS` version +<!-- Put the `OS` version ... --> + +## Steps to reproduce +<!-- (Optional)Describe steps to reproduce bug ... --> + +## Current behavior +<!-- Describe current behavior ... --> + +## Expected behavior +<!-- Describe expected behavior ... --> + +## Config +<!-- (Optional)Put configuration ... --> diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..c4d1407 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,28 @@ +--- +name: Feature request +about: Suggest an idea for erlcron +title: '' +labels: '' +assignees: '' +--- + +## `erlcron` version +[Put release version here and update tag link(0.0.0)...](https://github.com/erlware/erlcron.git) + +## `OS` version +<!-- Put the `OS` version ... --> + +## Description +* **Motivation** +<!-- (Optional)Describe motivation ... --> +* **Proposal** +<!-- (Optional)Describe proposal of the solution ... --> + +## Current behavior +<!-- (Optional)Describe current behavior ... --> + +## Expected behavior +<!-- (Optional)Describe expected behavior ... --> + +## Config +<!-- (Optional)Put configuration ... --> diff --git a/.github/ISSUE_TEMPLATE/other_issues.md b/.github/ISSUE_TEMPLATE/other_issues.md new file mode 100644 index 0000000..75c571f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/other_issues.md @@ -0,0 +1,9 @@ +--- +name: Other Issues +about: Something that's are not covered by the other templates +title: '' +labels: '' +assignees: '' +--- + +<!-- Please consider opening a discussion if this is not really an issue --> diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..223bb60 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + pull_request: + branches: [ $default-branch ] + release: + types: + - created + +jobs: + test: + name: "Erlang Test" + runs-on: ubuntu-latest + strategy: + matrix: + otp: [23, 24, 25] + fail-fast: false + container: + image: erlang:${{ matrix.otp }} + steps: + - uses: actions/checkout@v3 + - name: Test + run: make diff --git a/.gitignore b/.gitignore index 32c7afb..c054362 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ ebin/*.beam ebin/*.app -.* -deps/* \ No newline at end of file +deps/* +_build +rebar3 +TEST*.xml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 3c80414..0000000 --- a/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -sudo: false -language: erlang -otp_release: - - 20.0 - - 21.0 - - 22.0 - -before_script: "make get-deps" -script: "make test" -branches: - only: - - master diff --git a/rebar.config b/rebar.config index 5129c17..85f36dd 100644 --- a/rebar.config +++ b/rebar.config @@ -1,18 +1,18 @@ %% -*- mode: Erlang; fill-column: 80; comment-column: 75; -*- %% Dependencies ================================================================ {deps, []}. -%% Rebar Plugins ============================================================== +%% Rebar Plugins =============================================================== {plugins, []}. %% Compiler Options ============================================================ {erl_opts, [debug_info, warnings_as_errors]}. %% EUnit ======================================================================= {eunit_opts, [verbose, {report, {eunit_surefire, [{dir, "."}]}}]}. {cover_enabled, true}. {cover_print_enabled, true}. diff --git a/rebar.lock b/rebar.lock new file mode 100644 index 0000000..57afcca --- /dev/null +++ b/rebar.lock @@ -0,0 +1 @@ +[]. diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 5e4866e..22b5e97 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,174 +1,176 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, datetime/1, ref_datetime/0, ref_datetime/1, set_datetime/1, set_datetime/2, reset_datetime/0, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). -record(state, {ref_time :: calendar:datetime(), epoch_at_ref :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). -spec cancel(erlcron:job_ref()) -> boolean(). cancel(AlarmRef) -> ecrn_reg:cancel(AlarmRef). %% @doc %% Returns current datetime with reference adjustment in universal time zone. -spec datetime() -> {calendar:datetime(), erlcron:milliseconds()}. datetime() -> gen_server:call(?SERVER, datetime). %% @doc %% Returns current datetime with reference adjustment in universal/local time zone. -spec datetime(local|universal) -> {calendar:datetime(), erlcron:milliseconds()}. datetime(universal) -> datetime(); datetime(local) -> {DT, Epoch} = datetime(), {erlang:universaltime_to_localtime(DT), Epoch}. %% @doc Returns reference datetime in universal time zone. -spec ref_datetime() -> {calendar:datetime(), erlcron:milliseconds()}. ref_datetime() -> gen_server:call(?SERVER, ref_datetime). %% @doc Returns reference datetime in universal or local time zone. -spec ref_datetime(local|universal) -> {calendar:datetime(), erlcron:milliseconds()}. ref_datetime(universal) -> ref_datetime(); ref_datetime(local) -> {DT, Epoch} = ref_datetime(), {erlang:universaltime_to_localtime(DT), Epoch}. %% @doc sets the date-time for the erlcron -spec set_datetime(calendar:datetime()) -> ok | {error, term()}. set_datetime(DateTime) -> set_datetime(DateTime, local). -spec set_datetime(calendar:datetime(), local|universal) -> ok | {error, term()}. set_datetime(DT={_,_}, local) -> gen_server:call(?SERVER, {set_datetime, erlang:localtime_to_universaltime(DT)}, infinity); set_datetime(DateTime={_,_}, universal) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc Reset reference datetime to current epoch datetime -spec reset_datetime() -> ok | {error, term()}. reset_datetime() -> gen_server:call(?SERVER, reset_datetime, infinity). %% @doc sets the date-time with the erlcron on all nodes --spec multi_set_datetime([node()], calendar:datetime()) -> ok | {error, term()}. +-spec multi_set_datetime([node()], calendar:datetime()) -> {Replies, BadNodes} when + Replies :: [{node(), ok | {error, term()}}], + BadNodes :: [node()]. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> DateTime = erlang:universaltime(), {ok, #state{ref_time=DateTime, epoch_at_ref=ecrn_util:epoch_milliseconds()}}. %% @private handle_call(datetime, _From, State = #state{ref_time = DateTime, epoch_at_ref = Actual}) -> DT = erlang:universaltime_to_posixtime(DateTime), Now = ecrn_util:epoch_milliseconds(), Diff = Now - Actual, DiffS = to_seconds(Diff), RefNow = DT + DiffS, Msecs = Diff - DiffS*1000, NowDT = erlang:posixtime_to_universaltime(RefNow), {reply, {NowDT, RefNow*1000 + Msecs}, State}; handle_call(ref_datetime, _From, State = #state{ref_time = DateTime, epoch_at_ref = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{ref_time=DateTime, epoch_at_ref=ecrn_util:epoch_milliseconds()}, {reply, call_all(NewState), NewState}; handle_call(reset_datetime, _From, State) -> Now = ecrn_util:epoch_milliseconds(), DateTime = erlang:posixtime_to_universaltime(to_seconds(Now)), NewState = State#state{ref_time=DateTime, epoch_at_ref=Now}, {reply, call_all(NewState), NewState}. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== %notify_all(#state{ref_time=DateTime, epoch_at_ref=Now}=State) -> % [ecrn_agent:set_datetime(P, DateTime, Now, universal) || P <- ecrn_reg:get_all_pids()], % State. call_all(#state{ref_time=DateTime, epoch_at_ref=Now}) -> Res = lists:foldl(fun(P, A) -> case ecrn_agent:set_datetime(P, DateTime, Now, universal) of ok -> A; {error, Err} -> Ref = try ecrn_reg:get_refs(P) catch _:_ -> [] end, [{Ref, P, Err} | A] end end, [], ecrn_reg:get_all_pids()), case Res of [] -> ok; _ -> {error, {failed_to_set_time, Res}} end. to_seconds(MilliSec) -> MilliSec div 1000. diff --git a/src/erlcron.erl b/src/erlcron.erl index 3bc4e5f..bfddfe3 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,197 +1,201 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, cron/2, at/2, at/3, daily/2, daily/3, weekly/3, weekly/4, monthly/3,monthly/4, cancel/1, epoch/0, epoch_seconds/0, datetime/0, ref_datetime/0, set_datetime/1, reset_datetime/0, get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0, milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | h | min | m | sec | s}. -type period() :: cron_time() | {every, duration()} | {every, duration(), constraint()}. -type dom() :: integer(). -type dow_day() :: mon | tue | wed | thu | fri | sat | sun. -type dow() :: dow_day() | [dow_day()]. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | fun(() -> ok) | fun((JobRef::atom()|reference(), calendar:datetime()) -> ok). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom()|[dom()], period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference() | atom(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref(). cron(Job) -> cron(make_ref(), Job). -spec cron(job_ref(), job()) -> job_ref(). cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef)) , is_tuple(Job) -> ecrn_cron_sup:add_job(JobRef, Job). %% @doc %% Run the specified job once after the amount of time specified. -spec at(cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> at(make_ref(), When, Fun). -spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref(). at(JobRef, When, Fun) -> cron(JobRef, {{once, When}, Fun}). %% @doc %% Convenience method to specify a job run to run on a daily basis %% at a specific time. -spec daily(cron_time() | seconds(), function()) -> job_ref(). daily(When, Fun) -> daily(make_ref(), When, Fun). -spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref(). daily(JobRef, When, Fun) -> cron(JobRef, {{daily, When}, Fun}). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref(). weekly(DOW, When, Fun) -> weekly(make_ref(), DOW, When, Fun). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref(). weekly(JobRef, DOW, When, Fun) -> cron(JobRef, {{weekly, DOW, When}, Fun}). %% @doc %% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref(). monthly(DOM, When, Fun) -> monthly(make_ref(), DOM, When, Fun). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref(). monthly(JobRef, DOM, When, Fun) -> cron(JobRef, {{monthly, DOM, When}, Fun}). %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time in seconds millisince epoch. -spec epoch() -> milliseconds(). epoch() -> ecrn_util:epoch_milliseconds(). %% @doc %% Get the current date time in seconds since epoch. -spec epoch_seconds() -> seconds(). epoch_seconds() -> ecrn_util:epoch_seconds(). %% @doc %% Get the current date time of the erlcron system adjusted to reference. -%% +%% -spec datetime() -> {calendar:datetime(), milliseconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Get the reference date time of the erlcron system. -%% +%% -spec ref_datetime() -> {calendar:datetime(), milliseconds()}. ref_datetime() -> ecrn_control:ref_datetime(). %% @doc %% Set the current date time of the running erlcron system. -spec set_datetime(calendar:datetime()) -> ok. set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:set_datetime(DateTime). %% @doc %% Reset the reference datetime of erlcron system to current epoch time. -spec reset_datetime() -> ok. reset_datetime() -> ecrn_control:reset_datetime(). %% Get references of all running jobs -spec get_all_jobs() -> [job_ref()]. get_all_jobs() -> ecrn_reg:get_all_refs(). %% @doc %% Set the current date time of the erlcron system running on different nodes. --spec multi_set_datetime(calendar:datetime()) -> ok. +-spec multi_set_datetime(calendar:datetime()) -> {Replies, BadNodes} when + Replies :: [{node(), ok | {error, term()}}], + BadNodes :: [node()]. multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes --spec multi_set_datetime([node()], calendar:datetime()) -> ok. +-spec multi_set_datetime([node()], calendar:datetime()) -> {Replies, BadNodes} when + Replies :: [{node(), ok | {error, term()}}], + BadNodes :: [node()]. multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime). diff --git a/test/ecrn_test.erl b/test/ecrn_test.erl index 9ef77d4..1bcc396 100644 --- a/test/ecrn_test.erl +++ b/test/ecrn_test.erl @@ -1,197 +1,197 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_test). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), application:start(erlcron) end, fun(_) -> application:stop(erlcron) end, [{timeout, 30, [ ?FuncTest(set_alarm), ?FuncTest(travel_back_in_time), ?FuncTest(cancel_alarm), ?FuncTest(big_time_jump), ?FuncTest(cron), ?FuncTest(validation) ]}, {timeout, 30, [ ?FuncTest(weekly) ]}, {timeout, 30, [ ?FuncTest(weekly_every) ]} ]}. set_alarm() -> erlcron:set_datetime({{2000,1,1},{8,0,0}}), Self = self(), erlcron:at(test1, {9,0,0}, fun() -> Self ! ack1 end), erlcron:at(test2, {9,0,1}, fun() -> Self ! ack2 end), erlcron:daily(test3, {every, {1,s}, {between, {9,0,2}, {9,0,4}}}, fun() -> Self ! ack3 end), erlcron:set_datetime({{2000,1,1},{8,59,59}}), %% The alarm should trigger this nearly immediately. ?assertMatch(1, collect(ack1, 1500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(1, collect(ack2, 2500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(3, collect(ack3, 3000, 3)), erlcron:cancel(test3). cancel_alarm() -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(0, collect(ack, 125, 1)). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump() -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:daily(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:daily(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)). travel_back_in_time() -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), - ?assertMatch(true, ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), + ?assertMatch(true, ExpectedSeconds =< calendar:datetime_to_gregorian_seconds(Past)), ?assertMatch(true, ExpectedSeconds < Seconds). %% Time jumps ahead one day so we should see the alarms from both days. cron() -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,58}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Job = {{daily, {3, 30, pm}}, fun(_, _) -> Self ! ack end}, erlcron:cron(Job), ?assertMatch(1, collect(ack, 2500, 1)). validation() -> erlcron:set_datetime({{2000,1,1}, {15,0,0}}), ?assertMatch(ok, ecrn_agent:validate({once, {3, 30, pm}})), erlcron:set_datetime({{2000,1,1}, {15,31,0}}), ?assertMatch({error,{specified_time_past_seconds_ago, -60}}, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({once, 3600})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {0,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,sec}, {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, fri, {every, {5,sec}}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 4, {2, am}})), ?assertMatch({error,{invalid_time,{55,22,am}}}, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch({error,{invalid_days_in_schedule,{monthly,"A",{55,am}}}}, ecrn_agent:validate({monthly, 65, {55, am}})). weekly() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, sun], {9,0,0}}, fun() -> Self ! weekly end}), Pattern = [1, 1, 0, 0, 0, 0, 0, 1], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). weekly_every() -> DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, erlcron:set_datetime({DateF(0), {7,0,0}}), Self = self(), erlcron:cron(weekly, {{weekly, [sat, mon], {every, {29, sec}, {between, {9, 0, 0}, {9, 1, 0}}}}, fun() -> Self ! weekly end}), Pattern = [3, 0, 3, 0, 0, 0, 0, 3], collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), erlcron:cancel(weekly). %%%=================================================================== %%% Internal Functions %%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). collect(Msg, Timeout, Count) -> collect(Msg, Timeout, 0, Count). collect(_Msg, _Timeout, Count, Count) -> Count; collect(Msg, Timeout, I, Count) -> receive Msg -> collect(Msg, Timeout, I+1, Count) after Timeout -> I end. % check that for each day generated by DateF(I) for increasing I, Pattern[I] % weekly messages are received collect_weekly(DateF, TimeBefore, TimeAfter, Pattern) -> collect_weekly(DateF, TimeBefore, TimeAfter, Pattern, 0). collect_weekly(DateF, TimeBefore, TimeAfter, [N | PatternTail], I) -> erlcron:set_datetime({DateF(I), TimeBefore}), ?assertMatch(0, collect(weekly, 1000, 1)), erlcron:set_datetime({DateF(I), TimeAfter}), ?assertMatch(N, collect(weekly, 1000, N)), collect_weekly(DateF, TimeBefore, TimeAfter, PatternTail, I+1); collect_weekly(_DateF, _TimeBefore, _TimeAfter, [], _I) -> ok.
erlware/erlcron
7e8e5342176f126c240c045a9fa40b531a7ad0bb
Fix typos
diff --git a/Makefile b/Makefile index a08f383..349d3de 100644 --- a/Makefile +++ b/Makefile @@ -1,92 +1,92 @@ # Copyright Erlware, LLC. All Rights Reserved. # # This file is provided to you under the BSD License; you may not use # this file except in compliance with the License. You may obtain a # copy of the License. ERLFLAGS= -pa $(CURDIR)/.eunit -pa $(CURDIR)/ebin -pa $(CURDIR)/deps/*/ebin DEPS_PLT=$(CURDIR)/.deps_plt # ============================================================================= # Verify that the programs we need to run are installed on this system # ============================================================================= ERL = $(shell which erl) ifeq ($(ERL),) $(error "Erlang not available on this system") endif REBAR=$(shell which rebar) ifeq ($(REBAR),) $(error "Rebar not available on this system") endif .PHONY: all compile doc clean test dialyzer typer shell distclean pdf \ get-deps escript clean-common-test-data rebuild all: compile dialyzer test # ============================================================================= # Rules to build the system # ============================================================================= get-deps: $(REBAR) get-deps $(REBAR) compile compile: $(REBAR) skip_deps=true compile doc: $(REBAR) skip_deps=true doc eunit: compile clean-common-test-data $(REBAR) skip_deps=true eunit ct: compile clean-common-test-data $(REBAR) skip_deps=true ct test: compile eunit ct $(DEPS_PLT): @echo Building local plt at $(DEPS_PLT) @echo dialyzer --output_plt $(DEPS_PLT) --build_plt \ --apps erts kernel stdlib dialyzer: $(DEPS_PLT) dialyzer --plt $(DEPS_PLT) --fullpath \ -pa $(CURDIR)/ebin --src src typer: typer --plt $(DEPS_PLT) -r ./src shell: get-deps compile # You often want *rebuilt* rebar tests to be available to the # shell you have to call eunit (to get the tests # rebuilt). However, eunit runs the tests, which probably -# fails (thats probably why You want them in the shell). This +# fails (that's probably why You want them in the shell). This # runs eunit but tells make to ignore the result. - @$(REBAR) skip_deps=true eunit @$(ERL) $(ERLFLAGS) pdf: pandoc README.md -o README.pdf clean-common-test-data: # We have to do this because of the unique way we generate test # data. Without this rebar eunit gets very confused - rm -rf $(CURDIR)/test/*_SUITE_data clean: clean-common-test-data - rm -rf $(CURDIR)/test/*.beam - rm -rf $(CURDIR)/logs $(REBAR) skip_deps=true clean distclean: clean - rm -rf $(DEPS_PLT) - rm -rvf $(CURDIR)/deps/* rebuild: distclean get-deps compile dialyzer test diff --git a/README.md b/README.md index d864df2..e5e88e1 100644 --- a/README.md +++ b/README.md @@ -1,169 +1,169 @@ Erlcron ======= Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. -The synax of a job description is quite different from crontab. It is +The syntax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. Unlike cron's one-minute resolution, erlcron has a millisecond resolution. It does handle Daylight Savings Time changes (but not the cases when the system clock is altered by small increments, in which case the next execution of a scheduled task may be imprecise). Cron Job Description Examples: ```erlang {{once, {3, 30, pm}, fun() -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}, fun(JobRef, CurrDateTime) -> io:fwrite("Hello world!~n") end} {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, fun() -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, {fun() -> io:fwrite("It's 2 Wednesday morning~n") end} {{weekly, [tue,wed], {2, am}}, {fun(_, Now) -> io:format("Now is ~p~n", [Now]) end} {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} {{monthly, [1, 7, 14], {2, am}}, {io, fwrite, ["Every 1st, 7th, 14th of the month!~n"]}} {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} {{monthly, [0, -1], {2, am}}, {io, fwrite, ["Last two days of the month!~n"]}} {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} %% Days of month less or equal to zero are subtracted from the end of the month {{monthly, 0, {2, am}}, {io, fwrite, ["Last day of the month!~n"]}} ``` Adding a cron to the system: ```erlang Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job). ``` Cron jobs can be given named atom references: ```erlang erlcron:cron(test_job1, {{once, {3,pm}}, {io, fwrite, "It's 3pm"}}). ``` A simple way to add a daily cron: erlcron:daily({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. ```erlang erlcron:at(300, Fun). ``` Cancel a running job. ```erlang erlcron:cancel(JobRef). ``` -Get the current reference (univeral) date time of the system. +Get the current reference (universal) date time of the system. ```erlang erlcron:datetime(). ``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:set_datetime(DateTime). ``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(DateTime). ``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(Nodes, DateTime). ``` -The application cron can be pre-configured throught environment variables +The application cron can be pre-configured through environment variables in the config file that all applications can load in the Erlang VM start. The app.config file can be as follow: ```erlang [ {erlcron, [ {crontab, [ {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}}, {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} ]} ]} ]. ``` So, when the app will be started, all configurations will be loaded. Note that the limitation is that in the config file is impossible load an anonymous function (or lambda function) so, you only can use {M,F,A} format. diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 857c7b2..3627daf 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,582 +1,582 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, next_run/1, get_datetime/1, get_datetime/2, set_datetime/3, set_datetime/4, recalculate/1, validate/1, until_next_time/2, normalize/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, ref_epoch, epoch_at_ref, fast_forward=false, last_time, next_run, % Time in EPOCH seconds until task's next execution last_run, % Time in EPOCH seconds when the task was last run orig_when }). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 1000). -define(MAX_TIMEOUT_SEC, 1800). -define(MAX_TIMEOUT_MSEC, 1800000). -define(SEC_IN_A_DAY, 86400). %% compatibility -ifdef(OTP_RELEASE). %% this implies 21 or higher -define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). -define(GET_STACK(Stacktrace), Stacktrace). -include_lib("kernel/include/logger.hrl"). -else. -define(EXCEPTION(Class, Reason, _), Class:Reason). -define(GET_STACK(_), erlang:get_stacktrace()). -define(LOG_ERROR(Report), error_logger:error_report(Report)). -define(LOG_WARNING(Report), error_logger:warning_report(Report)). -endif. %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc -%% Starts the server with the apropriate job and the appropriate ref +%% Starts the server with the appropriate job and the appropriate ref -spec start_link(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, {When, _Task} = Job) when is_reference(JobRef) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link(?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []); start_link(JobRef, {When, _Task} = Job) when is_atom(JobRef) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link({local, JobRef}, ?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> get_datetime(Pid, local). -spec get_datetime(pid(), local|universal) -> calendar:datetime(). get_datetime(Pid, local) -> erlang:universaltime_to_localtime(get_datetime(Pid, universal)); get_datetime(Pid, universal) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) when is_pid(Pid); is_atom(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> set_datetime(Pid, DateTime, Actual, local). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds(), UTC::local|universal) -> ok | {error, term()}. set_datetime(Pid, DateTime, Actual, UTC) -> DT = case UTC of local -> erlang:localtime_to_universaltime(DateTime); universal -> DateTime end, Res = gen_server:call(Pid, {set_datetime, DT, Actual}, infinity), Res. -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Get job's next execution time -spec next_run(pid()) -> erlang:timestamp(). next_run(Pid) -> gen_server:call(Pid, next_run). %% @doc %% Validate that a run_when spec specified is correct. -spec validate(erlcron:run_when()) -> ok | {error, term()}. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), NewState = set_internal_time(State, DateTime, ActualMsec), try NormalSpec = normalize(Spec, DateTime), {Msec,_} = until_next_time(NewState#state{job={NormalSpec, undefined}}), Msec > 0 orelse throw({specified_time_past_seconds_ago, to_seconds(Msec)}), ok catch _Error:Reason -> {error, Reason} end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, {When, Task}, Sched, DateTime, ActualMsec]) -> try State = set_internal_time(#state{alarm_ref=JobRef, job={Sched, Task}, last_run=0, next_run=0, orig_when=When}, DateTime, ActualMsec), case until_next_milliseconds(State) of {ok, {NewState, Timeout}} -> ecrn_reg:register(JobRef, self()), {ok, NewState, Timeout}; {error, {_, Reason}} -> throw(Reason) end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, JobRef}, {run_when, When}, {reason, E}, {stack, ?GET_STACK(ST)}]), {stop, normal} end. %% @private handle_call(next_run, _From, #state{next_run=Time} = State) -> reply_and_wait(Time, State); handle_call(get_datetime, _From, State) -> Epoch = ecrn_util:epoch_milliseconds(), Msec = current_epoch(Epoch, State), DT = to_universal_datetime(Msec), reply_and_wait(DT, State#state{last_time=Epoch}); handle_call({set_datetime, DateTime, CurrEpochMsec}, _From, State) -> try NewRefEpoch = to_milliseconds(erlang:universaltime_to_posixtime(DateTime)), case fast_forward(State#state{fast_forward=true}, NewRefEpoch, DateTime, 1) of true -> NewState = set_internal_time(State#state{next_run=0}, DateTime, CurrEpochMsec), reply_and_wait(ok, NewState); false -> {stop, normal, ok, State} end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, State#state.alarm_ref}, {run_when, element(1, State#state.orig_when)}, {reason, E}, {stack, ?GET_STACK(ST)}]), reply_and_wait({error, E}, State) end; handle_call(Msg, _From, State) -> {stop, State, {not_implemented, Msg}}. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast(Other, State) -> {stop, {not_implemented, Other}, State}. %% @private handle_info(timeout, S) -> process_timeout(S); handle_info({'EXIT', _, Reason}, State) -> {stop, Reason, State}; handle_info(_Msg, State) -> {noreply, State, 1000}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== normalize_when(When) -> {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), Sched = normalize(When, erlang:universaltime_to_localtime(DateTime)), {Sched, DateTime, ActualMsec}. process_timeout(#state{last_time=LastTime, next_run=NextRun, last_run=LastRun}=S) -> Epoch = ecrn_util:epoch_milliseconds(), NowMsec = current_epoch(Epoch, S), {Reply, State} = if LastTime < Epoch, NextRun > LastRun, NowMsec >= NextRun -> {do_job_run(S), S#state{last_run=NextRun, next_run=0}}; NextRun == LastRun -> S#state.fast_forward orelse timer:sleep(1), {noreply, S#state{next_run=0}}; true -> {noreply, S#state{last_time=Epoch}} end, reply_and_wait(Reply, State). do_job_run(#state{alarm_ref=Ref, next_run=Time, job={When, Job}} = S) -> execute(Job, Ref, Time), case When of {once, _} -> stop; _ -> S#state.fast_forward orelse timer:sleep(1), noreply end. execute(Job, Ref, Time) when is_function(Job, 2) -> proc_lib:spawn(fun() -> Job(Ref, Time) end); execute(Job, _, _) when is_function(Job, 0) -> proc_lib:spawn(Job); execute({M, F, A}, _, _) when is_atom(M), is_atom(F), is_list(A) -> proc_lib:spawn(M, F, A). reply_and_wait(stop, State) -> {stop, normal, State}; reply_and_wait(Reply, #state{next_run=0} = State) -> reply_and_wait2(Reply, until_next_milliseconds(State)); reply_and_wait(Reply, #state{next_run=Next, last_run=Last} = State) when Next-Last =< 0 -> reply_and_wait2(Reply, {ok, {State, 1000}}); reply_and_wait(Reply, #state{last_time=Now, next_run=NextMsec} = State) -> NowTime = current_epoch(Now, State), Timeout = round_timeout(NextMsec-NowTime), reply_and_wait2(Reply, {ok, {State, Timeout}}). reply_and_wait2(noreply, {ok, {State, Timeout}}) -> {noreply, State, Timeout}; reply_and_wait2(Reply, {ok, {State, Timeout}}) -> {reply, Reply, State, Timeout}; reply_and_wait2(noreply, {error, {State, _}}) -> {stop, normal, State}; reply_and_wait2(Reply, {error, {State, _}}) -> {stop, normal, Reply, State}. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% The returned duration is set to the maximum of 1 hour at which %% point the duration is recalculated, so that daylight savings time %% adjustments don't affect the precision of when a task is run. -spec until_next_milliseconds(#state{}) -> {ok, {#state{}, erlcron:milliseconds()}} | {error, {#state{}, term()}}. until_next_milliseconds(#state{} = S) -> try Epoch = ecrn_util:epoch_milliseconds(), {Msec, S1} = until_next_time(S#state{last_time=Epoch}), {ok, update_next_run(S1, max(0, Msec))} catch ?EXCEPTION(_, E, ST) -> {error, {S, {E, ?GET_STACK(ST)}}} end. -spec update_next_run(#state{}, erlcron:seconds()) -> {#state{}, erlcron:milliseconds()}. update_next_run(#state{} = State, ?SEC_IN_A_DAY) -> {State, ?MAX_TIMEOUT_MSEC}; update_next_run(#state{last_time=Now} = State, Milliseconds) -> Timeout = round_timeout(Milliseconds), EpochS = current_epoch(Now, State), {State#state{next_run=EpochS+Milliseconds}, Timeout}. round_timeout(Milliseconds) -> trunc(max(0, min(Milliseconds, ?MAX_TIMEOUT_MSEC))). -type normalized_period() :: [{integer(), integer(), integer()}]. -type normalized_sched() :: {once, {relative|absolute, integer()}} | {daily, normalized_period()} | {weekly, [integer()], normalized_period()} | {monthly,integer(), normalized_period()}. -spec normalize(erlcron:run_when(), calendar:datetime()) -> normalized_sched(). normalize({once, I}, _) when is_integer(I) -> {once, {relative, to_milliseconds(I)}}; normalize({once, {H,M,S}=T}, {_, Time}) when is_integer(H), is_integer(M), is_integer(S) , H >= 0, H < 24, M >= 0, M < 59, S >= 0, S < 59 -> T < Time andalso throw({time_given_in_the_past, T}), {once, {absolute, resolve_time(T)}}; normalize({once, Period}, _) -> {once, {absolute, resolve_time(Period)}}; normalize({daily, Period}, _) -> {daily, lists:sort(resolve_period(Period))}; normalize({weekly, DoW, Period}, _) -> {weekly, resolve_dow(DoW), lists:sort(resolve_period(Period))}; normalize({monthly, Day, Period}, TodayDate) when is_integer(Day) -> normalize({monthly, [Day], Period}, TodayDate); normalize({monthly, Days, Period}=T, {{Y,M,_},_}) when is_list(Days) -> case [Day || Day <- Days, not is_integer(Day) orelse Day < -30 orelse Day > 31] of [] -> ok; _ -> throw({invalid_days_in_schedule, T}) end, {PosDays, NegDays} = lists:partition(fun(I) -> I > 0 end, Days), {ThisNextMonthDays, _State} = update_dom(Y,M, {undefined, {0,0, PosDays, NegDays}}, #state{job={T, undefined}}), {monthly, ThisNextMonthDays, lists:sort(resolve_period(Period))}; normalize(Other, _) -> throw({invalid_schedule, Other}). update_dom(Y,M, {_, {Y,M,_,_}}=When, State) -> {When, State}; update_dom(Y,M, {_, {_,_,PosDays,NegDays}}, State = #state{job = {{monthly, _, _Period}, Task}}) -> {_, _, ThisMonthDays} = month_days(Y, M, PosDays, NegDays, true), {NY,NM, NextMonFirstDay} = next_month_days(Y, M, PosDays, NegDays), ThisNextMonthDays = {ThisMonthDays, NY, NM, NextMonFirstDay}, When = {ThisNextMonthDays, {Y,M,PosDays,NegDays}}, {When, State#state{job={{monthly, When}, Task}}}. next_month_days(Y, 12, PosDays, NegDays) -> month_days(Y+1, 1, PosDays, NegDays, false); next_month_days(Y, M, [], NegDays) -> month_days(Y, M+1, [], NegDays, false); next_month_days(Y, M, PosDays, NegDays) -> % When checking next month, and PosDays contains days 29,30,31 % make sure that combining that with {Y,M} gives a valid date D = lists:min(PosDays), M1 = M+1, case calendar:valid_date({Y,M1,D}) of true -> month_days(Y, M1, PosDays, NegDays, false); false -> next_month_days(Y, M1, PosDays, NegDays) end. month_days(Y, M, PosDays, NegDays, false) -> LastDay = calendar:last_day_of_the_month(Y, M), Days = [I+LastDay || I <- NegDays] ++ PosDays, case [I || I <- Days, I =< LastDay, I > 0] of [] -> next_month_days(Y, M, PosDays, NegDays); L -> {Y, M, lists:min(L)} end; month_days(Y, M, PosDays, [], true) -> LastDay = calendar:last_day_of_the_month(Y, M), {Y, M, [I || I <- lists:sort(PosDays), I =< LastDay]}; month_days(Y, M, PosDays, NegDays, true) -> LastDay = calendar:last_day_of_the_month(Y, M), AllDays = PosDays ++ [I+LastDay || I <- NegDays], UniqDays= lists:sort(sets:to_list(sets:from_list(AllDays))), check_days(Y, M, UniqDays), {Y, M, [I || I <- UniqDays, I =< LastDay, I > 0]}. check_days(Y,M,Days) -> lists:foreach(fun(I) -> Date = {Y,M,I}, calendar:valid_date(Date) orelse throw({invalid_date, Date}) end, lists:takewhile(fun(I) -> I > 28 end, lists:reverse(Days))). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_time(erlcron:milliseconds(), erlcron:run_when()) -> erlcron:milliseconds(). until_next_time(NowEpochTime, Sched) when is_integer(NowEpochTime), is_tuple(Sched) -> DateTime = erlang:posixtime_to_universaltime(to_ceiling_seconds(NowEpochTime)), NormSched = normalize(Sched, DateTime), State = set_internal_time(#state{job={NormSched, undefined}}, DateTime, NowEpochTime), {Res, _State1} = until_next_time(State), Res. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% @private -spec until_next_time(state()) -> {erlcron:milliseconds(), state()}. until_next_time(State = #state{job={Sched, _Task}}) -> until_next_time2(State, Sched). until_next_time2(State, {once, {relative, Msec}}) when is_integer(Msec) -> {Msec, State}; until_next_time2(State, {once, {absolute, Msec}}) when is_integer(Msec) -> {normalize_to_relative(State, Msec), State}; until_next_time2(State, {daily, Period}) -> {until_next_daytime(State, Period, current_time(State)), State}; until_next_time2(State, {weekly, DoW, Period}) -> {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), Days = find_dow(Today, DoW), NextDays = fun() -> I = Today+1, N = if I>7 -> 1; true -> I end, find_dow(N, DoW) end, {until_next_time_from_now(State, Period, Days, NextDays), State}; until_next_time2(State, {monthly, When, Period}) -> {{ThisYear, ThisMonth, Today}=YMD, _} = current_date(State), {{{ThisMonthDays, NextY, NextM, NextMonthFirstDOM}, _}, State1} = update_dom(ThisYear, ThisMonth, When, State), {YMD1, YMD2} = case lists:dropwhile(fun(I) -> I < Today end, ThisMonthDays) of [DOM1, DOM2 | _] -> {{ThisYear,ThisMonth,DOM1}, {ThisYear,ThisMonth,DOM2}}; [DOM|_] -> {{ThisYear,ThisMonth,DOM}, {NextY,NextM,NextMonthFirstDOM}}; [] -> {{NextY, NextM, NextMonthFirstDOM}, {0,0,0}} end, TodayGreg = to_greg_days(YMD), NextGreg = to_greg_days(YMD1), Days = NextGreg - TodayGreg, NextDays = fun() -> to_greg_days(YMD2) - TodayGreg end, {until_next_time_from_now(State1, Period, Days, NextDays), State1}. until_next_time_from_now(State, Period, 0, NextDays) when is_function(NextDays, 0) -> CurrentTime = current_time(State), F = fun() -> until_days_from_now(State, Period, NextDays()) end, case last_time(Period) of T when CurrentTime > T -> F(); _ -> EndTime = last_time(Period), case next_time(Period, CurrentTime) of I when I > EndTime -> F(); I -> I - CurrentTime end end; until_next_time_from_now(State, Period, Days, _NextDays) when Days > 0 -> until_days_from_now(State, Period, Days-1). to_greg_days({Y,M,D}) -> calendar:date_to_gregorian_days(Y,M,D). %% @doc Calculates the time since midnight in milliseconds until the next time this %% period is to occur during the day. -spec until_next_daytime(state(), normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_next_daytime(State, Period, MsecsFromMidnight) -> StartTime = first_time(Period), EndTime = last_time(Period), if MsecsFromMidnight > EndTime -> until_tomorrow(State, StartTime); true -> case next_time(Period, MsecsFromMidnight) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> T - MsecsFromMidnight end end. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow(state(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_tomorrow(State, StartTime) -> StartTime + 24*3600000 - current_time(State). %% @doc Calculates the duration in milliseconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), normalized_period(), integer()) -> erlcron:milliseconds(). until_days_from_now(State, Period, Days) -> MsecsUntilTomorrow = until_tomorrow(State, 0), MsecsUntilTomorrow + Days * 24 * 3600000 + until_next_daytime(State, Period, 0). %% @doc Calculates the first time in a given period. -spec first_time(normalized_period()) -> erlcron:milliseconds(). first_time([]) -> ?SEC_IN_A_DAY; first_time([{FromTime, _ToTime, _RepeatSec}|_]) -> FromTime. %% @doc Calculates the last time in a given period. -spec last_time(normalized_period()) -> erlcron:milliseconds(). last_time([]) -> ?SEC_IN_A_DAY; last_time(Period) when is_list(Period) -> F = fun({FromTime, _ToTime, 0}) -> FromTime; ({FromTime, ToTime, RepeatSec}) -> FromTime + ((ToTime-FromTime) div RepeatSec) * RepeatSec end, lists:max([F(R) || R <- Period]). %% @doc Calculates the first time in the given period after the given time. -spec next_time(normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). next_time([], _Time) -> ?SEC_IN_A_DAY; next_time(Period, Time) when is_list(Period), is_integer(Time) -> F = fun({FromTime, _ToTime, _RepeatSec}) when Time =< FromTime -> FromTime; ({_FromTime, _ToTime, 0}) -> ?SEC_IN_A_DAY; ({FromTime, _ToTime, RepeatSec}) -> A1 = ((Time-FromTime) div RepeatSec) * RepeatSec, A = if A1 < Time -> A1 + RepeatSec; true -> A1 end, FromTime + A end, case [F(R) || R = {_, ToTm, _} <- Period, Time =< ToTm] of [] -> ?SEC_IN_A_DAY; LL -> lists:min(LL) end. %% @doc Returns the current time, in milliseconds past midnight in local time zone. -spec current_time(state()) -> erlcron:milliseconds(). current_time(State = #state{last_time=Now}) -> % Take ceiling of time to the next second Msec = case (Now div 1000) * 1000 of Now -> 0; N -> Now-N end, {_, {H,M,S}} = current_date(State), to_milliseconds(S + M * 60 + H * 3600) + Msec. %% @doc Returns current date in local time current_date(#state{last_time=Now, ref_epoch=E, epoch_at_ref=S}) when is_integer(Now), Now > 0 -> Elapsed = Now - S, to_local_datetime(Elapsed + E). current_epoch(EpochMsec, #state{ref_epoch=RefEpoch, epoch_at_ref=Epoch}) -> Elapsed = EpochMsec - Epoch, Elapsed + RefEpoch. normalize_to_relative(State, Milliseconds) -> NowSec = current_time(State), Milliseconds - NowSec. %% @doc Returns a list of times given a periodic specification. -spec resolve_period([erlcron:period()] | erlcron:period()) -> [{erlcron:milliseconds(), erlcron:milliseconds(), erlcron:milliseconds()}]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration}) -> resolve_period({every, Duration, {between, {0,0,0}, {23,59,59}}}); resolve_period({every, Duration, {between, TimeA, TimeB}} = P) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), StartTime =< EndTime orelse throw({invalid_period, P}), [{StartTime, EndTime, Period}]; resolve_period(Time) -> T = resolve_time(Time), [{T, T, 0}]. %% @doc Returns seconds past midnight for a given time. -spec resolve_time(erlcron:cron_time()) -> erlcron:milliseconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> to_milliseconds(S + M * 60 + H * 3600); resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60 + S); resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60); resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> to_milliseconds(H * 3600); resolve_time({12, pm}) -> diff --git a/src/erlcron.erl b/src/erlcron.erl index eea0756..3bc4e5f 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,197 +1,197 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, cron/2, at/2, at/3, daily/2, daily/3, weekly/3, weekly/4, monthly/3,monthly/4, cancel/1, epoch/0, epoch_seconds/0, datetime/0, ref_datetime/0, set_datetime/1, reset_datetime/0, get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0, milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | h | min | m | sec | s}. -type period() :: cron_time() | {every, duration()} | {every, duration(), constraint()}. -type dom() :: integer(). -type dow_day() :: mon | tue | wed | thu | fri | sat | sun. -type dow() :: dow_day() | [dow_day()]. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | fun(() -> ok) | fun((JobRef::atom()|reference(), calendar:datetime()) -> ok). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom()|[dom()], period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference() | atom(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref(). cron(Job) -> cron(make_ref(), Job). -spec cron(job_ref(), job()) -> job_ref(). cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef)) , is_tuple(Job) -> ecrn_cron_sup:add_job(JobRef, Job). %% @doc -%% Run the specified job once after the amount of time specifed. +%% Run the specified job once after the amount of time specified. -spec at(cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> at(make_ref(), When, Fun). -spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref(). at(JobRef, When, Fun) -> cron(JobRef, {{once, When}, Fun}). %% @doc -%% Convienience method to specify a job run to run on a daily basis +%% Convenience method to specify a job run to run on a daily basis %% at a specific time. -spec daily(cron_time() | seconds(), function()) -> job_ref(). daily(When, Fun) -> daily(make_ref(), When, Fun). -spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref(). daily(JobRef, When, Fun) -> cron(JobRef, {{daily, When}, Fun}). %% @doc -%% Convienience method to specify a job run to run on a weekly basis +%% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref(). weekly(DOW, When, Fun) -> weekly(make_ref(), DOW, When, Fun). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref(). weekly(JobRef, DOW, When, Fun) -> cron(JobRef, {{weekly, DOW, When}, Fun}). %% @doc -%% Convienience method to specify a job run to run on a weekly basis +%% Convenience method to specify a job run to run on a weekly basis %% at a specific time. -spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref(). monthly(DOM, When, Fun) -> monthly(make_ref(), DOM, When, Fun). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref(). monthly(JobRef, DOM, When, Fun) -> cron(JobRef, {{monthly, DOM, When}, Fun}). %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time in seconds millisince epoch. -spec epoch() -> milliseconds(). epoch() -> ecrn_util:epoch_milliseconds(). %% @doc %% Get the current date time in seconds since epoch. -spec epoch_seconds() -> seconds(). epoch_seconds() -> ecrn_util:epoch_seconds(). %% @doc %% Get the current date time of the erlcron system adjusted to reference. %% -spec datetime() -> {calendar:datetime(), milliseconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Get the reference date time of the erlcron system. %% -spec ref_datetime() -> {calendar:datetime(), milliseconds()}. ref_datetime() -> ecrn_control:ref_datetime(). %% @doc %% Set the current date time of the running erlcron system. -spec set_datetime(calendar:datetime()) -> ok. set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:set_datetime(DateTime). %% @doc %% Reset the reference datetime of erlcron system to current epoch time. -spec reset_datetime() -> ok. reset_datetime() -> ecrn_control:reset_datetime(). %% Get references of all running jobs -spec get_all_jobs() -> [job_ref()]. get_all_jobs() -> ecrn_reg:get_all_refs(). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> ok. multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
2b5ad781e7a9ffb53323ffa7340582c7a891be5c
fix datetime() false return
diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 8191db6..5e4866e 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,174 +1,174 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, datetime/1, ref_datetime/0, ref_datetime/1, set_datetime/1, set_datetime/2, reset_datetime/0, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). -record(state, {ref_time :: calendar:datetime(), epoch_at_ref :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). -spec cancel(erlcron:job_ref()) -> boolean(). cancel(AlarmRef) -> ecrn_reg:cancel(AlarmRef). %% @doc %% Returns current datetime with reference adjustment in universal time zone. -spec datetime() -> {calendar:datetime(), erlcron:milliseconds()}. datetime() -> gen_server:call(?SERVER, datetime). %% @doc %% Returns current datetime with reference adjustment in universal/local time zone. -spec datetime(local|universal) -> {calendar:datetime(), erlcron:milliseconds()}. datetime(universal) -> datetime(); datetime(local) -> {DT, Epoch} = datetime(), {erlang:universaltime_to_localtime(DT), Epoch}. %% @doc Returns reference datetime in universal time zone. -spec ref_datetime() -> {calendar:datetime(), erlcron:milliseconds()}. ref_datetime() -> gen_server:call(?SERVER, ref_datetime). %% @doc Returns reference datetime in universal or local time zone. -spec ref_datetime(local|universal) -> {calendar:datetime(), erlcron:milliseconds()}. ref_datetime(universal) -> ref_datetime(); ref_datetime(local) -> {DT, Epoch} = ref_datetime(), {erlang:universaltime_to_localtime(DT), Epoch}. %% @doc sets the date-time for the erlcron -spec set_datetime(calendar:datetime()) -> ok | {error, term()}. set_datetime(DateTime) -> set_datetime(DateTime, local). -spec set_datetime(calendar:datetime(), local|universal) -> ok | {error, term()}. set_datetime(DT={_,_}, local) -> gen_server:call(?SERVER, {set_datetime, erlang:localtime_to_universaltime(DT)}, infinity); set_datetime(DateTime={_,_}, universal) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc Reset reference datetime to current epoch datetime -spec reset_datetime() -> ok | {error, term()}. reset_datetime() -> gen_server:call(?SERVER, reset_datetime, infinity). %% @doc sets the date-time with the erlcron on all nodes -spec multi_set_datetime([node()], calendar:datetime()) -> ok | {error, term()}. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> DateTime = erlang:universaltime(), {ok, #state{ref_time=DateTime, epoch_at_ref=ecrn_util:epoch_milliseconds()}}. %% @private handle_call(datetime, _From, State = #state{ref_time = DateTime, epoch_at_ref = Actual}) -> DT = erlang:universaltime_to_posixtime(DateTime), Now = ecrn_util:epoch_milliseconds(), Diff = Now - Actual, DiffS = to_seconds(Diff), - RefNow = DT + Diff, + RefNow = DT + DiffS, Msecs = Diff - DiffS*1000, NowDT = erlang:posixtime_to_universaltime(RefNow), {reply, {NowDT, RefNow*1000 + Msecs}, State}; handle_call(ref_datetime, _From, State = #state{ref_time = DateTime, epoch_at_ref = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{ref_time=DateTime, epoch_at_ref=ecrn_util:epoch_milliseconds()}, {reply, call_all(NewState), NewState}; handle_call(reset_datetime, _From, State) -> Now = ecrn_util:epoch_milliseconds(), DateTime = erlang:posixtime_to_universaltime(to_seconds(Now)), NewState = State#state{ref_time=DateTime, epoch_at_ref=Now}, {reply, call_all(NewState), NewState}. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== %notify_all(#state{ref_time=DateTime, epoch_at_ref=Now}=State) -> % [ecrn_agent:set_datetime(P, DateTime, Now, universal) || P <- ecrn_reg:get_all_pids()], % State. call_all(#state{ref_time=DateTime, epoch_at_ref=Now}) -> Res = lists:foldl(fun(P, A) -> case ecrn_agent:set_datetime(P, DateTime, Now, universal) of ok -> A; {error, Err} -> Ref = try ecrn_reg:get_refs(P) catch _:_ -> [] end, [{Ref, P, Err} | A] end end, [], ecrn_reg:get_all_pids()), case Res of [] -> ok; _ -> {error, {failed_to_set_time, Res}} end. to_seconds(MilliSec) -> MilliSec div 1000.
erlware/erlcron
c18724f25d92ca42eb23c266f99b855a9dbc0c96
add tests for weekly jobs
diff --git a/test/ecrn_test.erl b/test/ecrn_test.erl index 5b64f63..9ef77d4 100644 --- a/test/ecrn_test.erl +++ b/test/ecrn_test.erl @@ -1,157 +1,197 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_test). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -define(FuncTest(A), {atom_to_list(A), fun A/0}). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> application:load(erlcron), application:set_env(erlcron, sup_intensity, 0), application:set_env(erlcron, sup_period, 1), application:start(erlcron) end, fun(_) -> application:stop(erlcron) end, - {timeout, 30, [ + [{timeout, 30, [ ?FuncTest(set_alarm), ?FuncTest(travel_back_in_time), ?FuncTest(cancel_alarm), ?FuncTest(big_time_jump), ?FuncTest(cron), ?FuncTest(validation) - ]}}. + ]}, + {timeout, 30, [ + ?FuncTest(weekly) + ]}, + {timeout, 30, [ + ?FuncTest(weekly_every) + ]} + ]}. set_alarm() -> erlcron:set_datetime({{2000,1,1},{8,0,0}}), Self = self(), erlcron:at(test1, {9,0,0}, fun() -> Self ! ack1 end), erlcron:at(test2, {9,0,1}, fun() -> Self ! ack2 end), erlcron:daily(test3, {every, {1,s}, {between, {9,0,2}, {9,0,4}}}, fun() -> Self ! ack3 end), erlcron:set_datetime({{2000,1,1},{8,59,59}}), %% The alarm should trigger this nearly immediately. ?assertMatch(1, collect(ack1, 1500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(1, collect(ack2, 2500, 1)), %% The alarm should trigger this 1 second later. ?assertMatch(3, collect(ack3, 3000, 3)), erlcron:cancel(test3). cancel_alarm() -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(0, collect(ack, 125, 1)). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump() -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:daily(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:daily(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)), ?assertMatch(1, collect(ack1, 1500, 1)), ?assertMatch(1, collect(ack2, 1500, 1)). travel_back_in_time() -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assertMatch(true, ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), ?assertMatch(true, ExpectedSeconds < Seconds). %% Time jumps ahead one day so we should see the alarms from both days. cron() -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,58}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Job = {{daily, {3, 30, pm}}, fun(_, _) -> Self ! ack end}, erlcron:cron(Job), ?assertMatch(1, collect(ack, 2500, 1)). validation() -> erlcron:set_datetime({{2000,1,1}, {15,0,0}}), ?assertMatch(ok, ecrn_agent:validate({once, {3, 30, pm}})), erlcron:set_datetime({{2000,1,1}, {15,31,0}}), ?assertMatch({error,{specified_time_past_seconds_ago, -60}}, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({once, 3600})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {0,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,s}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,sec}, {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(ok, ecrn_agent:validate({daily, {3, 30, pm}})), ?assertMatch(ok, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({weekly, fri, {every, {5,sec}}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(ok, ecrn_agent:validate({monthly, 4, {2, am}})), ?assertMatch({error,{invalid_time,{55,22,am}}}, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch({error,{invalid_days_in_schedule,{monthly,"A",{55,am}}}}, ecrn_agent:validate({monthly, 65, {55, am}})). +weekly() -> + DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, + erlcron:set_datetime({DateF(0), {7,0,0}}), + Self = self(), + erlcron:cron(weekly, {{weekly, [sat, sun], {9,0,0}}, fun() -> Self ! weekly end}), + Pattern = [1, 1, 0, 0, 0, 0, 0, 1], + collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), + erlcron:cancel(weekly). + +weekly_every() -> + DateF = fun (Offset) -> {2000, 1, 1 + Offset} end, + erlcron:set_datetime({DateF(0), {7,0,0}}), + Self = self(), + erlcron:cron(weekly, {{weekly, [sat, mon], + {every, {29, sec}, {between, {9, 0, 0}, {9, 1, 0}}}}, + fun() -> Self ! weekly end}), + Pattern = [3, 0, 3, 0, 0, 0, 0, 3], + collect_weekly(DateF, {8, 0, 0}, {10, 0, 0}, Pattern), + erlcron:cancel(weekly). + %%%=================================================================== %%% Internal Functions %%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). collect(Msg, Timeout, Count) -> collect(Msg, Timeout, 0, Count). collect(_Msg, _Timeout, Count, Count) -> Count; collect(Msg, Timeout, I, Count) -> receive Msg -> collect(Msg, Timeout, I+1, Count) after Timeout -> I end. + +% check that for each day generated by DateF(I) for increasing I, Pattern[I] +% weekly messages are received +collect_weekly(DateF, TimeBefore, TimeAfter, Pattern) -> + collect_weekly(DateF, TimeBefore, TimeAfter, Pattern, 0). + +collect_weekly(DateF, TimeBefore, TimeAfter, [N | PatternTail], I) -> + erlcron:set_datetime({DateF(I), TimeBefore}), + ?assertMatch(0, collect(weekly, 1000, 1)), + erlcron:set_datetime({DateF(I), TimeAfter}), + ?assertMatch(N, collect(weekly, 1000, N)), + collect_weekly(DateF, TimeBefore, TimeAfter, PatternTail, I+1); +collect_weekly(_DateF, _TimeBefore, _TimeAfter, [], _I) -> ok.
erlware/erlcron
f447e3a023adacb78dabcb19942d2301c4d91928
fix for adjacent days in weekly pattern
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index cb51c87..857c7b2 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,758 +1,758 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, next_run/1, get_datetime/1, get_datetime/2, set_datetime/3, set_datetime/4, recalculate/1, validate/1, until_next_time/2, normalize/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, ref_epoch, epoch_at_ref, fast_forward=false, last_time, next_run, % Time in EPOCH seconds until task's next execution last_run, % Time in EPOCH seconds when the task was last run orig_when }). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 1000). -define(MAX_TIMEOUT_SEC, 1800). -define(MAX_TIMEOUT_MSEC, 1800000). -define(SEC_IN_A_DAY, 86400). %% compatibility -ifdef(OTP_RELEASE). %% this implies 21 or higher -define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). -define(GET_STACK(Stacktrace), Stacktrace). -include_lib("kernel/include/logger.hrl"). -else. -define(EXCEPTION(Class, Reason, _), Class:Reason). -define(GET_STACK(_), erlang:get_stacktrace()). -define(LOG_ERROR(Report), error_logger:error_report(Report)). -define(LOG_WARNING(Report), error_logger:warning_report(Report)). -endif. %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref -spec start_link(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, {When, _Task} = Job) when is_reference(JobRef) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link(?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []); start_link(JobRef, {When, _Task} = Job) when is_atom(JobRef) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link({local, JobRef}, ?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> get_datetime(Pid, local). -spec get_datetime(pid(), local|universal) -> calendar:datetime(). get_datetime(Pid, local) -> erlang:universaltime_to_localtime(get_datetime(Pid, universal)); get_datetime(Pid, universal) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) when is_pid(Pid); is_atom(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> set_datetime(Pid, DateTime, Actual, local). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds(), UTC::local|universal) -> ok | {error, term()}. set_datetime(Pid, DateTime, Actual, UTC) -> DT = case UTC of local -> erlang:localtime_to_universaltime(DateTime); universal -> DateTime end, Res = gen_server:call(Pid, {set_datetime, DT, Actual}, infinity), Res. -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Get job's next execution time -spec next_run(pid()) -> erlang:timestamp(). next_run(Pid) -> gen_server:call(Pid, next_run). %% @doc %% Validate that a run_when spec specified is correct. -spec validate(erlcron:run_when()) -> ok | {error, term()}. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), NewState = set_internal_time(State, DateTime, ActualMsec), try NormalSpec = normalize(Spec, DateTime), {Msec,_} = until_next_time(NewState#state{job={NormalSpec, undefined}}), Msec > 0 orelse throw({specified_time_past_seconds_ago, to_seconds(Msec)}), ok catch _Error:Reason -> {error, Reason} end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, {When, Task}, Sched, DateTime, ActualMsec]) -> try State = set_internal_time(#state{alarm_ref=JobRef, job={Sched, Task}, last_run=0, next_run=0, orig_when=When}, DateTime, ActualMsec), case until_next_milliseconds(State) of {ok, {NewState, Timeout}} -> ecrn_reg:register(JobRef, self()), {ok, NewState, Timeout}; {error, {_, Reason}} -> throw(Reason) end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, JobRef}, {run_when, When}, {reason, E}, {stack, ?GET_STACK(ST)}]), {stop, normal} end. %% @private handle_call(next_run, _From, #state{next_run=Time} = State) -> reply_and_wait(Time, State); handle_call(get_datetime, _From, State) -> Epoch = ecrn_util:epoch_milliseconds(), Msec = current_epoch(Epoch, State), DT = to_universal_datetime(Msec), reply_and_wait(DT, State#state{last_time=Epoch}); handle_call({set_datetime, DateTime, CurrEpochMsec}, _From, State) -> try NewRefEpoch = to_milliseconds(erlang:universaltime_to_posixtime(DateTime)), case fast_forward(State#state{fast_forward=true}, NewRefEpoch, DateTime, 1) of true -> NewState = set_internal_time(State#state{next_run=0}, DateTime, CurrEpochMsec), reply_and_wait(ok, NewState); false -> {stop, normal, ok, State} end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, State#state.alarm_ref}, {run_when, element(1, State#state.orig_when)}, {reason, E}, {stack, ?GET_STACK(ST)}]), reply_and_wait({error, E}, State) end; handle_call(Msg, _From, State) -> {stop, State, {not_implemented, Msg}}. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast(Other, State) -> {stop, {not_implemented, Other}, State}. %% @private handle_info(timeout, S) -> process_timeout(S); handle_info({'EXIT', _, Reason}, State) -> {stop, Reason, State}; handle_info(_Msg, State) -> {noreply, State, 1000}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== normalize_when(When) -> {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), Sched = normalize(When, erlang:universaltime_to_localtime(DateTime)), {Sched, DateTime, ActualMsec}. process_timeout(#state{last_time=LastTime, next_run=NextRun, last_run=LastRun}=S) -> Epoch = ecrn_util:epoch_milliseconds(), NowMsec = current_epoch(Epoch, S), {Reply, State} = if LastTime < Epoch, NextRun > LastRun, NowMsec >= NextRun -> {do_job_run(S), S#state{last_run=NextRun, next_run=0}}; NextRun == LastRun -> S#state.fast_forward orelse timer:sleep(1), {noreply, S#state{next_run=0}}; true -> {noreply, S#state{last_time=Epoch}} end, reply_and_wait(Reply, State). do_job_run(#state{alarm_ref=Ref, next_run=Time, job={When, Job}} = S) -> execute(Job, Ref, Time), case When of {once, _} -> stop; _ -> S#state.fast_forward orelse timer:sleep(1), noreply end. execute(Job, Ref, Time) when is_function(Job, 2) -> proc_lib:spawn(fun() -> Job(Ref, Time) end); execute(Job, _, _) when is_function(Job, 0) -> proc_lib:spawn(Job); execute({M, F, A}, _, _) when is_atom(M), is_atom(F), is_list(A) -> proc_lib:spawn(M, F, A). reply_and_wait(stop, State) -> {stop, normal, State}; reply_and_wait(Reply, #state{next_run=0} = State) -> reply_and_wait2(Reply, until_next_milliseconds(State)); reply_and_wait(Reply, #state{next_run=Next, last_run=Last} = State) when Next-Last =< 0 -> reply_and_wait2(Reply, {ok, {State, 1000}}); reply_and_wait(Reply, #state{last_time=Now, next_run=NextMsec} = State) -> NowTime = current_epoch(Now, State), Timeout = round_timeout(NextMsec-NowTime), reply_and_wait2(Reply, {ok, {State, Timeout}}). reply_and_wait2(noreply, {ok, {State, Timeout}}) -> {noreply, State, Timeout}; reply_and_wait2(Reply, {ok, {State, Timeout}}) -> {reply, Reply, State, Timeout}; reply_and_wait2(noreply, {error, {State, _}}) -> {stop, normal, State}; reply_and_wait2(Reply, {error, {State, _}}) -> {stop, normal, Reply, State}. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% The returned duration is set to the maximum of 1 hour at which %% point the duration is recalculated, so that daylight savings time %% adjustments don't affect the precision of when a task is run. -spec until_next_milliseconds(#state{}) -> {ok, {#state{}, erlcron:milliseconds()}} | {error, {#state{}, term()}}. until_next_milliseconds(#state{} = S) -> try Epoch = ecrn_util:epoch_milliseconds(), {Msec, S1} = until_next_time(S#state{last_time=Epoch}), {ok, update_next_run(S1, max(0, Msec))} catch ?EXCEPTION(_, E, ST) -> {error, {S, {E, ?GET_STACK(ST)}}} end. -spec update_next_run(#state{}, erlcron:seconds()) -> {#state{}, erlcron:milliseconds()}. update_next_run(#state{} = State, ?SEC_IN_A_DAY) -> {State, ?MAX_TIMEOUT_MSEC}; update_next_run(#state{last_time=Now} = State, Milliseconds) -> Timeout = round_timeout(Milliseconds), EpochS = current_epoch(Now, State), {State#state{next_run=EpochS+Milliseconds}, Timeout}. round_timeout(Milliseconds) -> trunc(max(0, min(Milliseconds, ?MAX_TIMEOUT_MSEC))). -type normalized_period() :: [{integer(), integer(), integer()}]. -type normalized_sched() :: {once, {relative|absolute, integer()}} | {daily, normalized_period()} | {weekly, [integer()], normalized_period()} | {monthly,integer(), normalized_period()}. -spec normalize(erlcron:run_when(), calendar:datetime()) -> normalized_sched(). normalize({once, I}, _) when is_integer(I) -> {once, {relative, to_milliseconds(I)}}; normalize({once, {H,M,S}=T}, {_, Time}) when is_integer(H), is_integer(M), is_integer(S) , H >= 0, H < 24, M >= 0, M < 59, S >= 0, S < 59 -> T < Time andalso throw({time_given_in_the_past, T}), {once, {absolute, resolve_time(T)}}; normalize({once, Period}, _) -> {once, {absolute, resolve_time(Period)}}; normalize({daily, Period}, _) -> {daily, lists:sort(resolve_period(Period))}; normalize({weekly, DoW, Period}, _) -> {weekly, resolve_dow(DoW), lists:sort(resolve_period(Period))}; normalize({monthly, Day, Period}, TodayDate) when is_integer(Day) -> normalize({monthly, [Day], Period}, TodayDate); normalize({monthly, Days, Period}=T, {{Y,M,_},_}) when is_list(Days) -> case [Day || Day <- Days, not is_integer(Day) orelse Day < -30 orelse Day > 31] of [] -> ok; _ -> throw({invalid_days_in_schedule, T}) end, {PosDays, NegDays} = lists:partition(fun(I) -> I > 0 end, Days), {ThisNextMonthDays, _State} = update_dom(Y,M, {undefined, {0,0, PosDays, NegDays}}, #state{job={T, undefined}}), {monthly, ThisNextMonthDays, lists:sort(resolve_period(Period))}; normalize(Other, _) -> throw({invalid_schedule, Other}). update_dom(Y,M, {_, {Y,M,_,_}}=When, State) -> {When, State}; update_dom(Y,M, {_, {_,_,PosDays,NegDays}}, State = #state{job = {{monthly, _, _Period}, Task}}) -> {_, _, ThisMonthDays} = month_days(Y, M, PosDays, NegDays, true), {NY,NM, NextMonFirstDay} = next_month_days(Y, M, PosDays, NegDays), ThisNextMonthDays = {ThisMonthDays, NY, NM, NextMonFirstDay}, When = {ThisNextMonthDays, {Y,M,PosDays,NegDays}}, {When, State#state{job={{monthly, When}, Task}}}. next_month_days(Y, 12, PosDays, NegDays) -> month_days(Y+1, 1, PosDays, NegDays, false); next_month_days(Y, M, [], NegDays) -> month_days(Y, M+1, [], NegDays, false); next_month_days(Y, M, PosDays, NegDays) -> % When checking next month, and PosDays contains days 29,30,31 % make sure that combining that with {Y,M} gives a valid date D = lists:min(PosDays), M1 = M+1, case calendar:valid_date({Y,M1,D}) of true -> month_days(Y, M1, PosDays, NegDays, false); false -> next_month_days(Y, M1, PosDays, NegDays) end. month_days(Y, M, PosDays, NegDays, false) -> LastDay = calendar:last_day_of_the_month(Y, M), Days = [I+LastDay || I <- NegDays] ++ PosDays, case [I || I <- Days, I =< LastDay, I > 0] of [] -> next_month_days(Y, M, PosDays, NegDays); L -> {Y, M, lists:min(L)} end; month_days(Y, M, PosDays, [], true) -> LastDay = calendar:last_day_of_the_month(Y, M), {Y, M, [I || I <- lists:sort(PosDays), I =< LastDay]}; month_days(Y, M, PosDays, NegDays, true) -> LastDay = calendar:last_day_of_the_month(Y, M), AllDays = PosDays ++ [I+LastDay || I <- NegDays], UniqDays= lists:sort(sets:to_list(sets:from_list(AllDays))), check_days(Y, M, UniqDays), {Y, M, [I || I <- UniqDays, I =< LastDay, I > 0]}. check_days(Y,M,Days) -> lists:foreach(fun(I) -> Date = {Y,M,I}, calendar:valid_date(Date) orelse throw({invalid_date, Date}) end, lists:takewhile(fun(I) -> I > 28 end, lists:reverse(Days))). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_time(erlcron:milliseconds(), erlcron:run_when()) -> erlcron:milliseconds(). until_next_time(NowEpochTime, Sched) when is_integer(NowEpochTime), is_tuple(Sched) -> DateTime = erlang:posixtime_to_universaltime(to_ceiling_seconds(NowEpochTime)), NormSched = normalize(Sched, DateTime), State = set_internal_time(#state{job={NormSched, undefined}}, DateTime, NowEpochTime), {Res, _State1} = until_next_time(State), Res. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% @private -spec until_next_time(state()) -> {erlcron:milliseconds(), state()}. until_next_time(State = #state{job={Sched, _Task}}) -> until_next_time2(State, Sched). until_next_time2(State, {once, {relative, Msec}}) when is_integer(Msec) -> {Msec, State}; until_next_time2(State, {once, {absolute, Msec}}) when is_integer(Msec) -> {normalize_to_relative(State, Msec), State}; until_next_time2(State, {daily, Period}) -> {until_next_daytime(State, Period, current_time(State)), State}; until_next_time2(State, {weekly, DoW, Period}) -> {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), Days = find_dow(Today, DoW), NextDays = fun() -> I = Today+1, N = if I>7 -> 1; true -> I end, find_dow(N, DoW) end, {until_next_time_from_now(State, Period, Days, NextDays), State}; until_next_time2(State, {monthly, When, Period}) -> {{ThisYear, ThisMonth, Today}=YMD, _} = current_date(State), {{{ThisMonthDays, NextY, NextM, NextMonthFirstDOM}, _}, State1} = update_dom(ThisYear, ThisMonth, When, State), {YMD1, YMD2} = case lists:dropwhile(fun(I) -> I < Today end, ThisMonthDays) of [DOM1, DOM2 | _] -> {{ThisYear,ThisMonth,DOM1}, {ThisYear,ThisMonth,DOM2}}; [DOM|_] -> {{ThisYear,ThisMonth,DOM}, {NextY,NextM,NextMonthFirstDOM}}; [] -> {{NextY, NextM, NextMonthFirstDOM}, {0,0,0}} end, TodayGreg = to_greg_days(YMD), NextGreg = to_greg_days(YMD1), Days = NextGreg - TodayGreg, NextDays = fun() -> to_greg_days(YMD2) - TodayGreg end, {until_next_time_from_now(State1, Period, Days, NextDays), State1}. until_next_time_from_now(State, Period, 0, NextDays) when is_function(NextDays, 0) -> CurrentTime = current_time(State), - F = fun() -> until_days_from_now(State, Period, NextDays()-1) end, + F = fun() -> until_days_from_now(State, Period, NextDays()) end, case last_time(Period) of T when CurrentTime > T -> F(); _ -> EndTime = last_time(Period), case next_time(Period, CurrentTime) of I when I > EndTime -> F(); I -> I - CurrentTime end end; until_next_time_from_now(State, Period, Days, _NextDays) when Days > 0 -> until_days_from_now(State, Period, Days-1). to_greg_days({Y,M,D}) -> calendar:date_to_gregorian_days(Y,M,D). %% @doc Calculates the time since midnight in milliseconds until the next time this %% period is to occur during the day. -spec until_next_daytime(state(), normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_next_daytime(State, Period, MsecsFromMidnight) -> StartTime = first_time(Period), EndTime = last_time(Period), if MsecsFromMidnight > EndTime -> until_tomorrow(State, StartTime); true -> case next_time(Period, MsecsFromMidnight) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> T - MsecsFromMidnight end end. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow(state(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_tomorrow(State, StartTime) -> StartTime + 24*3600000 - current_time(State). %% @doc Calculates the duration in milliseconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), normalized_period(), integer()) -> erlcron:milliseconds(). until_days_from_now(State, Period, Days) -> MsecsUntilTomorrow = until_tomorrow(State, 0), MsecsUntilTomorrow + Days * 24 * 3600000 + until_next_daytime(State, Period, 0). %% @doc Calculates the first time in a given period. -spec first_time(normalized_period()) -> erlcron:milliseconds(). first_time([]) -> ?SEC_IN_A_DAY; first_time([{FromTime, _ToTime, _RepeatSec}|_]) -> FromTime. %% @doc Calculates the last time in a given period. -spec last_time(normalized_period()) -> erlcron:milliseconds(). last_time([]) -> ?SEC_IN_A_DAY; last_time(Period) when is_list(Period) -> F = fun({FromTime, _ToTime, 0}) -> FromTime; ({FromTime, ToTime, RepeatSec}) -> FromTime + ((ToTime-FromTime) div RepeatSec) * RepeatSec end, lists:max([F(R) || R <- Period]). %% @doc Calculates the first time in the given period after the given time. -spec next_time(normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). next_time([], _Time) -> ?SEC_IN_A_DAY; next_time(Period, Time) when is_list(Period), is_integer(Time) -> F = fun({FromTime, _ToTime, _RepeatSec}) when Time =< FromTime -> FromTime; ({_FromTime, _ToTime, 0}) -> ?SEC_IN_A_DAY; ({FromTime, _ToTime, RepeatSec}) -> A1 = ((Time-FromTime) div RepeatSec) * RepeatSec, A = if A1 < Time -> A1 + RepeatSec; true -> A1 end, FromTime + A end, case [F(R) || R = {_, ToTm, _} <- Period, Time =< ToTm] of [] -> ?SEC_IN_A_DAY; LL -> lists:min(LL) end. %% @doc Returns the current time, in milliseconds past midnight in local time zone. -spec current_time(state()) -> erlcron:milliseconds(). current_time(State = #state{last_time=Now}) -> % Take ceiling of time to the next second Msec = case (Now div 1000) * 1000 of Now -> 0; N -> Now-N end, {_, {H,M,S}} = current_date(State), to_milliseconds(S + M * 60 + H * 3600) + Msec. %% @doc Returns current date in local time current_date(#state{last_time=Now, ref_epoch=E, epoch_at_ref=S}) when is_integer(Now), Now > 0 -> Elapsed = Now - S, to_local_datetime(Elapsed + E). current_epoch(EpochMsec, #state{ref_epoch=RefEpoch, epoch_at_ref=Epoch}) -> Elapsed = EpochMsec - Epoch, Elapsed + RefEpoch. normalize_to_relative(State, Milliseconds) -> NowSec = current_time(State), Milliseconds - NowSec. %% @doc Returns a list of times given a periodic specification. -spec resolve_period([erlcron:period()] | erlcron:period()) -> [{erlcron:milliseconds(), erlcron:milliseconds(), erlcron:milliseconds()}]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration}) -> resolve_period({every, Duration, {between, {0,0,0}, {23,59,59}}}); resolve_period({every, Duration, {between, TimeA, TimeB}} = P) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), StartTime =< EndTime orelse throw({invalid_period, P}), [{StartTime, EndTime, Period}]; resolve_period(Time) -> T = resolve_time(Time), [{T, T, 0}]. %% @doc Returns seconds past midnight for a given time. -spec resolve_time(erlcron:cron_time()) -> erlcron:milliseconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> to_milliseconds(S + M * 60 + H * 3600); resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60 + S); resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60); resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> to_milliseconds(H * 3600); resolve_time({12, pm}) -> to_milliseconds(12 * 3600); resolve_time({H, pm}) when H < 12 -> to_milliseconds((H + 12) * 3600); resolve_time(Other) -> throw({invalid_time, Other}). %% @doc Returns seconds for a given duration. -spec resolve_dur(erlcron:duration()) -> erlcron:milliseconds(). resolve_dur({Hour, H}) when H==h; H==hr -> to_milliseconds(Hour * 3600); resolve_dur({Min, M}) when M==m; M==min -> to_milliseconds(Min * 60); resolve_dur({Sec, S}) when S==s; S==sec -> to_milliseconds(Sec); resolve_dur({Mil, M}) when M==ms; M==milli; M==millisecond -> Mil; resolve_dur(Other) -> throw({invalid_duration, Other}). %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow(erlcron:dow()) -> [integer()]. resolve_dow(I) when is_atom(I) -> [resolve_dow2(I)]; resolve_dow([I]) -> [resolve_dow2(I)]; resolve_dow(L) when is_list(L) -> lists:sort([resolve_dow2(I) || I <- L]). resolve_dow2(mon) -> 1; resolve_dow2(tue) -> 2; resolve_dow2(wed) -> 3; resolve_dow2(thu) -> 4; resolve_dow2(fri) -> 5; resolve_dow2(sat) -> 6; resolve_dow2(sun) -> 7. -spec find_dow(integer(), [integer()]) -> integer(). find_dow(_TodayDOW, []) -> throw(invalid_dow_period); find_dow(TodayDOW, [FirstDOW|_]=DOWs) -> find_dow(TodayDOW, DOWs, FirstDOW). find_dow(TodayDOW, [TodayDOW|_], _) -> 0; find_dow(TodayDOW, [DOW|_], _FirstDOW) when TodayDOW < DOW -> DOW-TodayDOW; find_dow(TodayDOW, [DOW|T], FirstDOW) when TodayDOW > DOW -> find_dow(TodayDOW, T, FirstDOW); find_dow(TodayDOW, [], FirstDOW) -> FirstDOW+7 - TodayDOW. set_internal_time(State, RefDate, CurEpochMsec) -> EpochS = to_seconds(CurEpochMsec), FloorE = to_milliseconds(EpochS), Msec = to_milliseconds(erlang:universaltime_to_posixtime(RefDate)), State1 = State#state{ref_epoch=Msec, epoch_at_ref=FloorE}, %Now = Msec + CurEpochMsec - FloorE, State1#state{last_time=CurEpochMsec}. %% @doc NewDate is in universal time. fast_forward(#state{ref_epoch=OldRefEpoch, next_run=NextRun}=S, NewRefEpoch, NewDate, Count) -> {Msec, State1} = until_next_time(S#state{last_time=OldRefEpoch, epoch_at_ref=OldRefEpoch}), Span = NewRefEpoch - OldRefEpoch, if Span =< Msec; Msec =:= 0 -> true; true -> RefMsec = OldRefEpoch + Msec, State2 = State1#state{ref_epoch = RefMsec+1, last_run=NextRun, next_run=RefMsec}, do_job_run(State2), case State2#state.job of {{once, _}, _} when Count =:= 1 -> Msec =< 0 andalso ?LOG_WARNING([{info, "One-time job executed immediately due to negative time shift"}, {time_shift_secs, to_seconds(Msec)}, {job_ref, State2#state.alarm_ref}, {job_when, State2#state.orig_when}]), false; _ -> fast_forward(State2, NewRefEpoch, NewDate, Count+1) end end. to_local_datetime(Milliseconds) when is_integer(Milliseconds) -> DT = to_universal_datetime(Milliseconds), erlang:universaltime_to_localtime(DT). to_universal_datetime(Milliseconds) -> erlang:posixtime_to_universaltime(to_seconds(Milliseconds)). to_milliseconds(Secs) -> Secs * 1000. to_seconds(MilliSec) -> MilliSec div 1000. to_ceiling_seconds(Msec) -> S = to_seconds(Msec), case to_milliseconds(S) of Msec -> S; _ -> S+1 end. %%%=================================================================== %%% Tests %%%=================================================================== -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -ifdef(EUNIT). dow_test() -> DOWs = resolve_dow([tue,wed,thu]), ?assertEqual([7], resolve_dow(sun)), ?assertEqual([7], resolve_dow([sun])), ?assertEqual([1,2], resolve_dow([mon,tue])), ?assertEqual([2,3,4], DOWs), ?assertEqual(1, find_dow(1, DOWs)), ?assertEqual(0, find_dow(2, DOWs)), ?assertEqual(0, find_dow(3, DOWs)), ?assertEqual(0, find_dow(4, DOWs)), ?assertEqual(4, find_dow(5, DOWs)), DOWs1 = resolve_dow([thu,sat]), ?assertEqual([4,6], DOWs1), ?assertEqual(3, find_dow(1, DOWs1)), ?assertEqual(2, find_dow(2, DOWs1)), ?assertEqual(1, find_dow(3, DOWs1)), ?assertEqual(0, find_dow(4, DOWs1)), ?assertEqual(1, find_dow(5, DOWs1)), ?assertEqual(0, find_dow(6, DOWs1)), ?assertEqual(4, find_dow(7, DOWs1)), ok. normalize_test() -> Date = {date(), {0,0,0}}, ?assertEqual({once,{relative,1000}}, normalize({once, 1}, Date)), ?assertEqual({once,{absolute,43200000}}, normalize({once, {12,pm}}, Date)), ?assertThrow({time_given_in_the_past,{2,3,4}}, normalize({once, {2,3,4}}, {date(), {2,3,5}})), ?assertEqual({once,{absolute,7384000}}, normalize({once, {2,3,4}}, Date)), ?assertEqual({daily,[{50400000,50400000,0}]}, normalize({daily, {2,pm}}, Date)), ?assertEqual({daily,[{0,86399000,20000}]}, normalize({daily, {every, {20,s}}}, Date)), ?assertEqual({daily,[{0,86399000,200}]}, normalize({daily, {every, {200,ms}}}, Date)), ?assertEqual({daily,[{0,86399000,2000}]}, normalize({daily, {every, {2000,millisecond}}}, Date)), ?assertEqual({daily,[{3600000,3600000,0},{7200000,7200000,0}]}, normalize({daily, [{2,am},{1,am}]}, Date)), ?assertEqual({daily,[{0,86399000,5000},{0,86399000,20000}]}, normalize({daily, [{every, {5,s}}, {every, {20,s}}]}, Date)), ?assertEqual({daily,[{3600000,7200000,20000}]}, normalize({daily, {every, {20,s}, {between, {1,am}, {2,am}}}}, Date)), ?assertEqual({weekly,[1], [{3600000,3600000,0}]}, normalize({weekly, mon, {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [mon,wed], {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [wed,mon], {1,am}}, Date)), ?assertEqual({monthly,{{[31],2019,2,28},{2019,1, [],[0]}},[{3600000,3600000,0}]}, normalize({monthly, 0, {1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[],[0]}},[{3600000,3600000,0}]}, normalize({monthly, [0], {1,am}}, {{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[], 2019,3,31},{2019,2,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly,[31], {1,am}}, {{2019,2,1},{0,0,0}})), ?assertEqual({monthly,{{[1, 31],2020,1,1}, {2019,12,[1],[0]}},[{3600000,3600000,0}]},normalize({monthly,[1,0],{1,am}},{{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[30,31],2020,1,30},{2019,12,[30,31],[]}},[{3600000,3600000,0}]},normalize({monthly,[30,31],{1,am}},{{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2019,3,31},{2019,1,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly, 31, {1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[29],2024,2,29},{2024,1,[29],[]}},[{3600000,3600000,0}]}, normalize({monthly, 29, {1,am}}, {{2024,1,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly, 31, {1,am}}, {{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[1], 2019,2,1}, {2019,1,[1],[-30]}},[{3600000,3600000,0}]}, normalize({monthly,[1,-30],{1,am}},{{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[1], 2019,3,1}, {2019,1,[],[-30]}}, [{3600000,3600000,0}]}, normalize({monthly,-30,{1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[30],2019,2,27},{2019,1,[],[-1]}}, [{0,86399000,20000}]}, normalize({monthly, -1, {every, {20,s}}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[28],2019,2,25},{2019,1,[],[-3]}}, [{0,0,0},{3600000,3600000,0}]}, normalize({monthly, -3, [{12,am}, {1,am}]}, {{2019,1,1},{0,0,0}})), ok. until_next_time_month_test() -> T = ecrn_util:localtime_to_epoch({{2019,1,1},{0,0,0}}), Test = fun(Epoch, Days, When) -> I = ecrn_agent:until_next_time(Epoch, {monthly, Days, When}), ecrn_util:epoch_to_datetime_string(Epoch+I) end, ?assertEqual("2019-01-31 01:00:00.000", Test(T, [0], {every, {20,s}, {between, {1,am}, {2,am}}})), ?assertEqual("2019-01-10 01:00:00.000", Test(T, [0,10], {every, {20,s}, {between, {1,am}, {2,am}}})), ?assertEqual("2019-01-03 00:00:00.000", Test(T, 3, {every, {20,s}})), ok. -endif.
erlware/erlcron
c06c4982c24a681b192061d8440ee4f347494eb6
Add support for millisecond duration/resulotion
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index f0ecd89..cb51c87 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -82,674 +82,677 @@ get_datetime(Pid) -> get_datetime(Pid, local). -spec get_datetime(pid(), local|universal) -> calendar:datetime(). get_datetime(Pid, local) -> erlang:universaltime_to_localtime(get_datetime(Pid, universal)); get_datetime(Pid, universal) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) when is_pid(Pid); is_atom(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> set_datetime(Pid, DateTime, Actual, local). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds(), UTC::local|universal) -> ok | {error, term()}. set_datetime(Pid, DateTime, Actual, UTC) -> DT = case UTC of local -> erlang:localtime_to_universaltime(DateTime); universal -> DateTime end, Res = gen_server:call(Pid, {set_datetime, DT, Actual}, infinity), Res. -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Get job's next execution time -spec next_run(pid()) -> erlang:timestamp(). next_run(Pid) -> gen_server:call(Pid, next_run). %% @doc %% Validate that a run_when spec specified is correct. -spec validate(erlcron:run_when()) -> ok | {error, term()}. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), NewState = set_internal_time(State, DateTime, ActualMsec), try NormalSpec = normalize(Spec, DateTime), {Msec,_} = until_next_time(NewState#state{job={NormalSpec, undefined}}), Msec > 0 orelse throw({specified_time_past_seconds_ago, to_seconds(Msec)}), ok catch _Error:Reason -> {error, Reason} end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, {When, Task}, Sched, DateTime, ActualMsec]) -> try State = set_internal_time(#state{alarm_ref=JobRef, job={Sched, Task}, last_run=0, next_run=0, orig_when=When}, DateTime, ActualMsec), case until_next_milliseconds(State) of {ok, {NewState, Timeout}} -> ecrn_reg:register(JobRef, self()), {ok, NewState, Timeout}; {error, {_, Reason}} -> throw(Reason) end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, JobRef}, {run_when, When}, {reason, E}, {stack, ?GET_STACK(ST)}]), {stop, normal} end. %% @private handle_call(next_run, _From, #state{next_run=Time} = State) -> reply_and_wait(Time, State); handle_call(get_datetime, _From, State) -> Epoch = ecrn_util:epoch_milliseconds(), Msec = current_epoch(Epoch, State), DT = to_universal_datetime(Msec), reply_and_wait(DT, State#state{last_time=Epoch}); handle_call({set_datetime, DateTime, CurrEpochMsec}, _From, State) -> try NewRefEpoch = to_milliseconds(erlang:universaltime_to_posixtime(DateTime)), case fast_forward(State#state{fast_forward=true}, NewRefEpoch, DateTime, 1) of true -> NewState = set_internal_time(State#state{next_run=0}, DateTime, CurrEpochMsec), reply_and_wait(ok, NewState); false -> {stop, normal, ok, State} end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, State#state.alarm_ref}, {run_when, element(1, State#state.orig_when)}, {reason, E}, {stack, ?GET_STACK(ST)}]), reply_and_wait({error, E}, State) end; handle_call(Msg, _From, State) -> {stop, State, {not_implemented, Msg}}. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast(Other, State) -> {stop, {not_implemented, Other}, State}. %% @private handle_info(timeout, S) -> process_timeout(S); handle_info({'EXIT', _, Reason}, State) -> {stop, Reason, State}; handle_info(_Msg, State) -> {noreply, State, 1000}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== normalize_when(When) -> {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), Sched = normalize(When, erlang:universaltime_to_localtime(DateTime)), {Sched, DateTime, ActualMsec}. process_timeout(#state{last_time=LastTime, next_run=NextRun, last_run=LastRun}=S) -> Epoch = ecrn_util:epoch_milliseconds(), NowMsec = current_epoch(Epoch, S), {Reply, State} = if LastTime < Epoch, NextRun > LastRun, NowMsec >= NextRun -> {do_job_run(S), S#state{last_run=NextRun, next_run=0}}; NextRun == LastRun -> S#state.fast_forward orelse timer:sleep(1), {noreply, S#state{next_run=0}}; true -> {noreply, S#state{last_time=Epoch}} end, reply_and_wait(Reply, State). do_job_run(#state{alarm_ref=Ref, next_run=Time, job={When, Job}} = S) -> execute(Job, Ref, Time), case When of {once, _} -> stop; _ -> S#state.fast_forward orelse timer:sleep(1), noreply end. execute(Job, Ref, Time) when is_function(Job, 2) -> proc_lib:spawn(fun() -> Job(Ref, Time) end); execute(Job, _, _) when is_function(Job, 0) -> proc_lib:spawn(Job); execute({M, F, A}, _, _) when is_atom(M), is_atom(F), is_list(A) -> proc_lib:spawn(M, F, A). reply_and_wait(stop, State) -> {stop, normal, State}; reply_and_wait(Reply, #state{next_run=0} = State) -> reply_and_wait2(Reply, until_next_milliseconds(State)); reply_and_wait(Reply, #state{next_run=Next, last_run=Last} = State) when Next-Last =< 0 -> reply_and_wait2(Reply, {ok, {State, 1000}}); reply_and_wait(Reply, #state{last_time=Now, next_run=NextMsec} = State) -> NowTime = current_epoch(Now, State), Timeout = round_timeout(NextMsec-NowTime), reply_and_wait2(Reply, {ok, {State, Timeout}}). reply_and_wait2(noreply, {ok, {State, Timeout}}) -> {noreply, State, Timeout}; reply_and_wait2(Reply, {ok, {State, Timeout}}) -> {reply, Reply, State, Timeout}; reply_and_wait2(noreply, {error, {State, _}}) -> {stop, normal, State}; reply_and_wait2(Reply, {error, {State, _}}) -> {stop, normal, Reply, State}. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% The returned duration is set to the maximum of 1 hour at which %% point the duration is recalculated, so that daylight savings time %% adjustments don't affect the precision of when a task is run. -spec until_next_milliseconds(#state{}) -> {ok, {#state{}, erlcron:milliseconds()}} | {error, {#state{}, term()}}. until_next_milliseconds(#state{} = S) -> try Epoch = ecrn_util:epoch_milliseconds(), {Msec, S1} = until_next_time(S#state{last_time=Epoch}), {ok, update_next_run(S1, max(0, Msec))} catch ?EXCEPTION(_, E, ST) -> {error, {S, {E, ?GET_STACK(ST)}}} end. -spec update_next_run(#state{}, erlcron:seconds()) -> {#state{}, erlcron:milliseconds()}. update_next_run(#state{} = State, ?SEC_IN_A_DAY) -> {State, ?MAX_TIMEOUT_MSEC}; update_next_run(#state{last_time=Now} = State, Milliseconds) -> Timeout = round_timeout(Milliseconds), EpochS = current_epoch(Now, State), {State#state{next_run=EpochS+Milliseconds}, Timeout}. round_timeout(Milliseconds) -> trunc(max(0, min(Milliseconds, ?MAX_TIMEOUT_MSEC))). -type normalized_period() :: [{integer(), integer(), integer()}]. -type normalized_sched() :: {once, {relative|absolute, integer()}} | {daily, normalized_period()} | {weekly, [integer()], normalized_period()} | {monthly,integer(), normalized_period()}. -spec normalize(erlcron:run_when(), calendar:datetime()) -> normalized_sched(). normalize({once, I}, _) when is_integer(I) -> {once, {relative, to_milliseconds(I)}}; normalize({once, {H,M,S}=T}, {_, Time}) when is_integer(H), is_integer(M), is_integer(S) , H >= 0, H < 24, M >= 0, M < 59, S >= 0, S < 59 -> T < Time andalso throw({time_given_in_the_past, T}), {once, {absolute, resolve_time(T)}}; normalize({once, Period}, _) -> {once, {absolute, resolve_time(Period)}}; normalize({daily, Period}, _) -> {daily, lists:sort(resolve_period(Period))}; normalize({weekly, DoW, Period}, _) -> {weekly, resolve_dow(DoW), lists:sort(resolve_period(Period))}; normalize({monthly, Day, Period}, TodayDate) when is_integer(Day) -> normalize({monthly, [Day], Period}, TodayDate); normalize({monthly, Days, Period}=T, {{Y,M,_},_}) when is_list(Days) -> case [Day || Day <- Days, not is_integer(Day) orelse Day < -30 orelse Day > 31] of [] -> ok; _ -> throw({invalid_days_in_schedule, T}) end, {PosDays, NegDays} = lists:partition(fun(I) -> I > 0 end, Days), {ThisNextMonthDays, _State} = update_dom(Y,M, {undefined, {0,0, PosDays, NegDays}}, #state{job={T, undefined}}), {monthly, ThisNextMonthDays, lists:sort(resolve_period(Period))}; normalize(Other, _) -> throw({invalid_schedule, Other}). update_dom(Y,M, {_, {Y,M,_,_}}=When, State) -> {When, State}; update_dom(Y,M, {_, {_,_,PosDays,NegDays}}, State = #state{job = {{monthly, _, _Period}, Task}}) -> {_, _, ThisMonthDays} = month_days(Y, M, PosDays, NegDays, true), {NY,NM, NextMonFirstDay} = next_month_days(Y, M, PosDays, NegDays), ThisNextMonthDays = {ThisMonthDays, NY, NM, NextMonFirstDay}, When = {ThisNextMonthDays, {Y,M,PosDays,NegDays}}, {When, State#state{job={{monthly, When}, Task}}}. next_month_days(Y, 12, PosDays, NegDays) -> month_days(Y+1, 1, PosDays, NegDays, false); next_month_days(Y, M, [], NegDays) -> month_days(Y, M+1, [], NegDays, false); next_month_days(Y, M, PosDays, NegDays) -> % When checking next month, and PosDays contains days 29,30,31 % make sure that combining that with {Y,M} gives a valid date D = lists:min(PosDays), M1 = M+1, case calendar:valid_date({Y,M1,D}) of true -> month_days(Y, M1, PosDays, NegDays, false); false -> next_month_days(Y, M1, PosDays, NegDays) end. month_days(Y, M, PosDays, NegDays, false) -> LastDay = calendar:last_day_of_the_month(Y, M), Days = [I+LastDay || I <- NegDays] ++ PosDays, case [I || I <- Days, I =< LastDay, I > 0] of [] -> next_month_days(Y, M, PosDays, NegDays); L -> {Y, M, lists:min(L)} end; month_days(Y, M, PosDays, [], true) -> LastDay = calendar:last_day_of_the_month(Y, M), {Y, M, [I || I <- lists:sort(PosDays), I =< LastDay]}; month_days(Y, M, PosDays, NegDays, true) -> LastDay = calendar:last_day_of_the_month(Y, M), AllDays = PosDays ++ [I+LastDay || I <- NegDays], UniqDays= lists:sort(sets:to_list(sets:from_list(AllDays))), check_days(Y, M, UniqDays), {Y, M, [I || I <- UniqDays, I =< LastDay, I > 0]}. check_days(Y,M,Days) -> lists:foreach(fun(I) -> Date = {Y,M,I}, calendar:valid_date(Date) orelse throw({invalid_date, Date}) end, lists:takewhile(fun(I) -> I > 28 end, lists:reverse(Days))). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_time(erlcron:milliseconds(), erlcron:run_when()) -> erlcron:milliseconds(). until_next_time(NowEpochTime, Sched) when is_integer(NowEpochTime), is_tuple(Sched) -> DateTime = erlang:posixtime_to_universaltime(to_ceiling_seconds(NowEpochTime)), NormSched = normalize(Sched, DateTime), State = set_internal_time(#state{job={NormSched, undefined}}, DateTime, NowEpochTime), {Res, _State1} = until_next_time(State), Res. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% @private -spec until_next_time(state()) -> {erlcron:milliseconds(), state()}. until_next_time(State = #state{job={Sched, _Task}}) -> until_next_time2(State, Sched). until_next_time2(State, {once, {relative, Msec}}) when is_integer(Msec) -> {Msec, State}; until_next_time2(State, {once, {absolute, Msec}}) when is_integer(Msec) -> {normalize_to_relative(State, Msec), State}; until_next_time2(State, {daily, Period}) -> {until_next_daytime(State, Period, current_time(State)), State}; until_next_time2(State, {weekly, DoW, Period}) -> {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), Days = find_dow(Today, DoW), NextDays = fun() -> I = Today+1, N = if I>7 -> 1; true -> I end, find_dow(N, DoW) end, {until_next_time_from_now(State, Period, Days, NextDays), State}; until_next_time2(State, {monthly, When, Period}) -> {{ThisYear, ThisMonth, Today}=YMD, _} = current_date(State), {{{ThisMonthDays, NextY, NextM, NextMonthFirstDOM}, _}, State1} = update_dom(ThisYear, ThisMonth, When, State), {YMD1, YMD2} = case lists:dropwhile(fun(I) -> I < Today end, ThisMonthDays) of [DOM1, DOM2 | _] -> {{ThisYear,ThisMonth,DOM1}, {ThisYear,ThisMonth,DOM2}}; [DOM|_] -> {{ThisYear,ThisMonth,DOM}, {NextY,NextM,NextMonthFirstDOM}}; [] -> {{NextY, NextM, NextMonthFirstDOM}, {0,0,0}} end, TodayGreg = to_greg_days(YMD), NextGreg = to_greg_days(YMD1), Days = NextGreg - TodayGreg, NextDays = fun() -> to_greg_days(YMD2) - TodayGreg end, {until_next_time_from_now(State1, Period, Days, NextDays), State1}. until_next_time_from_now(State, Period, 0, NextDays) when is_function(NextDays, 0) -> CurrentTime = current_time(State), F = fun() -> until_days_from_now(State, Period, NextDays()-1) end, case last_time(Period) of T when CurrentTime > T -> F(); _ -> EndTime = last_time(Period), case next_time(Period, CurrentTime) of I when I > EndTime -> F(); I -> I - CurrentTime end end; until_next_time_from_now(State, Period, Days, _NextDays) when Days > 0 -> until_days_from_now(State, Period, Days-1). to_greg_days({Y,M,D}) -> calendar:date_to_gregorian_days(Y,M,D). %% @doc Calculates the time since midnight in milliseconds until the next time this %% period is to occur during the day. -spec until_next_daytime(state(), normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_next_daytime(State, Period, MsecsFromMidnight) -> StartTime = first_time(Period), EndTime = last_time(Period), if MsecsFromMidnight > EndTime -> until_tomorrow(State, StartTime); true -> case next_time(Period, MsecsFromMidnight) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> T - MsecsFromMidnight end end. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow(state(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_tomorrow(State, StartTime) -> StartTime + 24*3600000 - current_time(State). %% @doc Calculates the duration in milliseconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), normalized_period(), integer()) -> erlcron:milliseconds(). until_days_from_now(State, Period, Days) -> MsecsUntilTomorrow = until_tomorrow(State, 0), MsecsUntilTomorrow + Days * 24 * 3600000 + until_next_daytime(State, Period, 0). %% @doc Calculates the first time in a given period. -spec first_time(normalized_period()) -> erlcron:milliseconds(). first_time([]) -> ?SEC_IN_A_DAY; first_time([{FromTime, _ToTime, _RepeatSec}|_]) -> FromTime. %% @doc Calculates the last time in a given period. -spec last_time(normalized_period()) -> erlcron:milliseconds(). last_time([]) -> ?SEC_IN_A_DAY; last_time(Period) when is_list(Period) -> F = fun({FromTime, _ToTime, 0}) -> FromTime; ({FromTime, ToTime, RepeatSec}) -> FromTime + ((ToTime-FromTime) div RepeatSec) * RepeatSec end, lists:max([F(R) || R <- Period]). %% @doc Calculates the first time in the given period after the given time. -spec next_time(normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). next_time([], _Time) -> ?SEC_IN_A_DAY; next_time(Period, Time) when is_list(Period), is_integer(Time) -> F = fun({FromTime, _ToTime, _RepeatSec}) when Time =< FromTime -> FromTime; ({_FromTime, _ToTime, 0}) -> ?SEC_IN_A_DAY; ({FromTime, _ToTime, RepeatSec}) -> A1 = ((Time-FromTime) div RepeatSec) * RepeatSec, A = if A1 < Time -> A1 + RepeatSec; true -> A1 end, FromTime + A end, case [F(R) || R = {_, ToTm, _} <- Period, Time =< ToTm] of [] -> ?SEC_IN_A_DAY; LL -> lists:min(LL) end. %% @doc Returns the current time, in milliseconds past midnight in local time zone. -spec current_time(state()) -> erlcron:milliseconds(). current_time(State = #state{last_time=Now}) -> % Take ceiling of time to the next second Msec = case (Now div 1000) * 1000 of Now -> 0; N -> Now-N end, {_, {H,M,S}} = current_date(State), to_milliseconds(S + M * 60 + H * 3600) + Msec. %% @doc Returns current date in local time current_date(#state{last_time=Now, ref_epoch=E, epoch_at_ref=S}) when is_integer(Now), Now > 0 -> Elapsed = Now - S, to_local_datetime(Elapsed + E). current_epoch(EpochMsec, #state{ref_epoch=RefEpoch, epoch_at_ref=Epoch}) -> Elapsed = EpochMsec - Epoch, Elapsed + RefEpoch. normalize_to_relative(State, Milliseconds) -> NowSec = current_time(State), Milliseconds - NowSec. %% @doc Returns a list of times given a periodic specification. -spec resolve_period([erlcron:period()] | erlcron:period()) -> [{erlcron:milliseconds(), erlcron:milliseconds(), erlcron:milliseconds()}]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration}) -> resolve_period({every, Duration, {between, {0,0,0}, {23,59,59}}}); resolve_period({every, Duration, {between, TimeA, TimeB}} = P) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), StartTime =< EndTime orelse throw({invalid_period, P}), [{StartTime, EndTime, Period}]; resolve_period(Time) -> T = resolve_time(Time), [{T, T, 0}]. %% @doc Returns seconds past midnight for a given time. -spec resolve_time(erlcron:cron_time()) -> erlcron:milliseconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> to_milliseconds(S + M * 60 + H * 3600); resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60 + S); resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60); resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> to_milliseconds(H * 3600); resolve_time({12, pm}) -> to_milliseconds(12 * 3600); resolve_time({H, pm}) when H < 12 -> to_milliseconds((H + 12) * 3600); resolve_time(Other) -> throw({invalid_time, Other}). %% @doc Returns seconds for a given duration. -spec resolve_dur(erlcron:duration()) -> erlcron:milliseconds(). resolve_dur({Hour, H}) when H==h; H==hr -> to_milliseconds(Hour * 3600); resolve_dur({Min, M}) when M==m; M==min -> to_milliseconds(Min * 60); resolve_dur({Sec, S}) when S==s; S==sec -> to_milliseconds(Sec); +resolve_dur({Mil, M}) when M==ms; M==milli; M==millisecond -> Mil; resolve_dur(Other) -> throw({invalid_duration, Other}). %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow(erlcron:dow()) -> [integer()]. resolve_dow(I) when is_atom(I) -> [resolve_dow2(I)]; resolve_dow([I]) -> [resolve_dow2(I)]; resolve_dow(L) when is_list(L) -> lists:sort([resolve_dow2(I) || I <- L]). resolve_dow2(mon) -> 1; resolve_dow2(tue) -> 2; resolve_dow2(wed) -> 3; resolve_dow2(thu) -> 4; resolve_dow2(fri) -> 5; resolve_dow2(sat) -> 6; resolve_dow2(sun) -> 7. -spec find_dow(integer(), [integer()]) -> integer(). find_dow(_TodayDOW, []) -> throw(invalid_dow_period); find_dow(TodayDOW, [FirstDOW|_]=DOWs) -> find_dow(TodayDOW, DOWs, FirstDOW). find_dow(TodayDOW, [TodayDOW|_], _) -> 0; find_dow(TodayDOW, [DOW|_], _FirstDOW) when TodayDOW < DOW -> DOW-TodayDOW; find_dow(TodayDOW, [DOW|T], FirstDOW) when TodayDOW > DOW -> find_dow(TodayDOW, T, FirstDOW); find_dow(TodayDOW, [], FirstDOW) -> FirstDOW+7 - TodayDOW. set_internal_time(State, RefDate, CurEpochMsec) -> EpochS = to_seconds(CurEpochMsec), FloorE = to_milliseconds(EpochS), Msec = to_milliseconds(erlang:universaltime_to_posixtime(RefDate)), State1 = State#state{ref_epoch=Msec, epoch_at_ref=FloorE}, %Now = Msec + CurEpochMsec - FloorE, State1#state{last_time=CurEpochMsec}. %% @doc NewDate is in universal time. fast_forward(#state{ref_epoch=OldRefEpoch, next_run=NextRun}=S, NewRefEpoch, NewDate, Count) -> {Msec, State1} = until_next_time(S#state{last_time=OldRefEpoch, epoch_at_ref=OldRefEpoch}), Span = NewRefEpoch - OldRefEpoch, if Span =< Msec; Msec =:= 0 -> true; true -> RefMsec = OldRefEpoch + Msec, State2 = State1#state{ref_epoch = RefMsec+1, last_run=NextRun, next_run=RefMsec}, do_job_run(State2), case State2#state.job of {{once, _}, _} when Count =:= 1 -> Msec =< 0 andalso ?LOG_WARNING([{info, "One-time job executed immediately due to negative time shift"}, {time_shift_secs, to_seconds(Msec)}, {job_ref, State2#state.alarm_ref}, {job_when, State2#state.orig_when}]), false; _ -> fast_forward(State2, NewRefEpoch, NewDate, Count+1) end end. to_local_datetime(Milliseconds) when is_integer(Milliseconds) -> DT = to_universal_datetime(Milliseconds), erlang:universaltime_to_localtime(DT). to_universal_datetime(Milliseconds) -> erlang:posixtime_to_universaltime(to_seconds(Milliseconds)). to_milliseconds(Secs) -> Secs * 1000. to_seconds(MilliSec) -> MilliSec div 1000. to_ceiling_seconds(Msec) -> S = to_seconds(Msec), case to_milliseconds(S) of Msec -> S; _ -> S+1 end. %%%=================================================================== %%% Tests %%%=================================================================== -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -ifdef(EUNIT). dow_test() -> DOWs = resolve_dow([tue,wed,thu]), ?assertEqual([7], resolve_dow(sun)), ?assertEqual([7], resolve_dow([sun])), ?assertEqual([1,2], resolve_dow([mon,tue])), ?assertEqual([2,3,4], DOWs), ?assertEqual(1, find_dow(1, DOWs)), ?assertEqual(0, find_dow(2, DOWs)), ?assertEqual(0, find_dow(3, DOWs)), ?assertEqual(0, find_dow(4, DOWs)), ?assertEqual(4, find_dow(5, DOWs)), DOWs1 = resolve_dow([thu,sat]), ?assertEqual([4,6], DOWs1), ?assertEqual(3, find_dow(1, DOWs1)), ?assertEqual(2, find_dow(2, DOWs1)), ?assertEqual(1, find_dow(3, DOWs1)), ?assertEqual(0, find_dow(4, DOWs1)), ?assertEqual(1, find_dow(5, DOWs1)), ?assertEqual(0, find_dow(6, DOWs1)), ?assertEqual(4, find_dow(7, DOWs1)), ok. normalize_test() -> Date = {date(), {0,0,0}}, ?assertEqual({once,{relative,1000}}, normalize({once, 1}, Date)), ?assertEqual({once,{absolute,43200000}}, normalize({once, {12,pm}}, Date)), ?assertThrow({time_given_in_the_past,{2,3,4}}, normalize({once, {2,3,4}}, {date(), {2,3,5}})), ?assertEqual({once,{absolute,7384000}}, normalize({once, {2,3,4}}, Date)), ?assertEqual({daily,[{50400000,50400000,0}]}, normalize({daily, {2,pm}}, Date)), ?assertEqual({daily,[{0,86399000,20000}]}, normalize({daily, {every, {20,s}}}, Date)), + ?assertEqual({daily,[{0,86399000,200}]}, normalize({daily, {every, {200,ms}}}, Date)), + ?assertEqual({daily,[{0,86399000,2000}]}, normalize({daily, {every, {2000,millisecond}}}, Date)), ?assertEqual({daily,[{3600000,3600000,0},{7200000,7200000,0}]}, normalize({daily, [{2,am},{1,am}]}, Date)), ?assertEqual({daily,[{0,86399000,5000},{0,86399000,20000}]}, normalize({daily, [{every, {5,s}}, {every, {20,s}}]}, Date)), ?assertEqual({daily,[{3600000,7200000,20000}]}, normalize({daily, {every, {20,s}, {between, {1,am}, {2,am}}}}, Date)), ?assertEqual({weekly,[1], [{3600000,3600000,0}]}, normalize({weekly, mon, {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [mon,wed], {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [wed,mon], {1,am}}, Date)), ?assertEqual({monthly,{{[31],2019,2,28},{2019,1, [],[0]}},[{3600000,3600000,0}]}, normalize({monthly, 0, {1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[],[0]}},[{3600000,3600000,0}]}, normalize({monthly, [0], {1,am}}, {{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[], 2019,3,31},{2019,2,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly,[31], {1,am}}, {{2019,2,1},{0,0,0}})), ?assertEqual({monthly,{{[1, 31],2020,1,1}, {2019,12,[1],[0]}},[{3600000,3600000,0}]},normalize({monthly,[1,0],{1,am}},{{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[30,31],2020,1,30},{2019,12,[30,31],[]}},[{3600000,3600000,0}]},normalize({monthly,[30,31],{1,am}},{{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2019,3,31},{2019,1,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly, 31, {1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[29],2024,2,29},{2024,1,[29],[]}},[{3600000,3600000,0}]}, normalize({monthly, 29, {1,am}}, {{2024,1,1},{0,0,0}})), ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly, 31, {1,am}}, {{2019,12,1},{0,0,0}})), ?assertEqual({monthly,{{[1], 2019,2,1}, {2019,1,[1],[-30]}},[{3600000,3600000,0}]}, normalize({monthly,[1,-30],{1,am}},{{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[1], 2019,3,1}, {2019,1,[],[-30]}}, [{3600000,3600000,0}]}, normalize({monthly,-30,{1,am}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[30],2019,2,27},{2019,1,[],[-1]}}, [{0,86399000,20000}]}, normalize({monthly, -1, {every, {20,s}}}, {{2019,1,1},{0,0,0}})), ?assertEqual({monthly,{{[28],2019,2,25},{2019,1,[],[-3]}}, [{0,0,0},{3600000,3600000,0}]}, normalize({monthly, -3, [{12,am}, {1,am}]}, {{2019,1,1},{0,0,0}})), ok. until_next_time_month_test() -> T = ecrn_util:localtime_to_epoch({{2019,1,1},{0,0,0}}), Test = fun(Epoch, Days, When) -> I = ecrn_agent:until_next_time(Epoch, {monthly, Days, When}), ecrn_util:epoch_to_datetime_string(Epoch+I) end, ?assertEqual("2019-01-31 01:00:00.000", Test(T, [0], {every, {20,s}, {between, {1,am}, {2,am}}})), ?assertEqual("2019-01-10 01:00:00.000", Test(T, [0,10], {every, {20,s}, {between, {1,am}, {2,am}}})), ?assertEqual("2019-01-03 00:00:00.000", Test(T, 3, {every, {20,s}})), ok. -endif.
erlware/erlcron
511e56ba629ccb5f1c10b1d746945741f171a90d
Add functions to return reference vs current date time
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 7343e1b..f0ecd89 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,728 +1,728 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, next_run/1, get_datetime/1, get_datetime/2, set_datetime/3, set_datetime/4, recalculate/1, validate/1, until_next_time/2, normalize/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, ref_epoch, epoch_at_ref, fast_forward=false, last_time, next_run, % Time in EPOCH seconds until task's next execution last_run, % Time in EPOCH seconds when the task was last run orig_when }). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 1000). -define(MAX_TIMEOUT_SEC, 1800). -define(MAX_TIMEOUT_MSEC, 1800000). -define(SEC_IN_A_DAY, 86400). %% compatibility -ifdef(OTP_RELEASE). %% this implies 21 or higher -define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). -define(GET_STACK(Stacktrace), Stacktrace). -include_lib("kernel/include/logger.hrl"). -else. -define(EXCEPTION(Class, Reason, _), Class:Reason). -define(GET_STACK(_), erlang:get_stacktrace()). -define(LOG_ERROR(Report), error_logger:error_report(Report)). -define(LOG_WARNING(Report), error_logger:warning_report(Report)). -endif. %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref -spec start_link(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, {When, _Task} = Job) when is_reference(JobRef) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link(?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []); start_link(JobRef, {When, _Task} = Job) when is_atom(JobRef) -> {Sched, DateTime, ActualMsec} = normalize_when(When), gen_server:start_link({local, JobRef}, ?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> get_datetime(Pid, local). -spec get_datetime(pid(), local|universal) -> calendar:datetime(). get_datetime(Pid, local) -> erlang:universaltime_to_localtime(get_datetime(Pid, universal)); get_datetime(Pid, universal) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) when is_pid(Pid); is_atom(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> set_datetime(Pid, DateTime, Actual, local). -spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds(), UTC::local|universal) -> ok | {error, term()}. set_datetime(Pid, DateTime, Actual, UTC) -> DT = case UTC of local -> erlang:localtime_to_universaltime(DateTime); universal -> DateTime end, Res = gen_server:call(Pid, {set_datetime, DT, Actual}, infinity), Res. -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Get job's next execution time -spec next_run(pid()) -> erlang:timestamp(). next_run(Pid) -> gen_server:call(Pid, next_run). %% @doc %% Validate that a run_when spec specified is correct. -spec validate(erlcron:run_when()) -> ok | {error, term()}. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, - {DateTime, ActualMsec} = ecrn_control:datetime(universal), + {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), NewState = set_internal_time(State, DateTime, ActualMsec), try NormalSpec = normalize(Spec, DateTime), {Msec,_} = until_next_time(NewState#state{job={NormalSpec, undefined}}), Msec > 0 orelse throw({specified_time_past_seconds_ago, to_seconds(Msec)}), ok catch _Error:Reason -> {error, Reason} end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, {When, Task}, Sched, DateTime, ActualMsec]) -> try State = set_internal_time(#state{alarm_ref=JobRef, job={Sched, Task}, last_run=0, next_run=0, orig_when=When}, DateTime, ActualMsec), case until_next_milliseconds(State) of {ok, {NewState, Timeout}} -> ecrn_reg:register(JobRef, self()), {ok, NewState, Timeout}; {error, {_, Reason}} -> throw(Reason) end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, JobRef}, {run_when, When}, {reason, E}, {stack, ?GET_STACK(ST)}]), {stop, normal} end. %% @private handle_call(next_run, _From, #state{next_run=Time} = State) -> reply_and_wait(Time, State); handle_call(get_datetime, _From, State) -> Epoch = ecrn_util:epoch_milliseconds(), Msec = current_epoch(Epoch, State), DT = to_universal_datetime(Msec), reply_and_wait(DT, State#state{last_time=Epoch}); handle_call({set_datetime, DateTime, CurrEpochMsec}, _From, State) -> try NewRefEpoch = to_milliseconds(erlang:universaltime_to_posixtime(DateTime)), case fast_forward(State#state{fast_forward=true}, NewRefEpoch, DateTime, 1) of true -> NewState = set_internal_time(State#state{next_run=0}, DateTime, CurrEpochMsec), reply_and_wait(ok, NewState); false -> {stop, normal, ok, State} end catch ?EXCEPTION(_, E, ST) -> ?LOG_ERROR([{error, "Error setting timeout for job"}, {job_ref, State#state.alarm_ref}, {run_when, element(1, State#state.orig_when)}, {reason, E}, {stack, ?GET_STACK(ST)}]), reply_and_wait({error, E}, State) end; handle_call(Msg, _From, State) -> {stop, State, {not_implemented, Msg}}. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast(Other, State) -> {stop, {not_implemented, Other}, State}. %% @private handle_info(timeout, S) -> process_timeout(S); handle_info({'EXIT', _, Reason}, State) -> {stop, Reason, State}; handle_info(_Msg, State) -> {noreply, State, 1000}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== normalize_when(When) -> - {DateTime, ActualMsec} = ecrn_control:datetime(universal), + {DateTime, ActualMsec} = ecrn_control:ref_datetime(universal), Sched = normalize(When, erlang:universaltime_to_localtime(DateTime)), {Sched, DateTime, ActualMsec}. process_timeout(#state{last_time=LastTime, next_run=NextRun, last_run=LastRun}=S) -> Epoch = ecrn_util:epoch_milliseconds(), NowMsec = current_epoch(Epoch, S), {Reply, State} = if LastTime < Epoch, NextRun > LastRun, NowMsec >= NextRun -> {do_job_run(S), S#state{last_run=NextRun, next_run=0}}; NextRun == LastRun -> S#state.fast_forward orelse timer:sleep(1), {noreply, S#state{next_run=0}}; true -> {noreply, S#state{last_time=Epoch}} end, reply_and_wait(Reply, State). do_job_run(#state{alarm_ref=Ref, next_run=Time, job={When, Job}} = S) -> execute(Job, Ref, Time), case When of {once, _} -> stop; _ -> S#state.fast_forward orelse timer:sleep(1), noreply end. execute(Job, Ref, Time) when is_function(Job, 2) -> proc_lib:spawn(fun() -> Job(Ref, Time) end); execute(Job, _, _) when is_function(Job, 0) -> proc_lib:spawn(Job); execute({M, F, A}, _, _) when is_atom(M), is_atom(F), is_list(A) -> proc_lib:spawn(M, F, A). reply_and_wait(stop, State) -> {stop, normal, State}; reply_and_wait(Reply, #state{next_run=0} = State) -> reply_and_wait2(Reply, until_next_milliseconds(State)); reply_and_wait(Reply, #state{next_run=Next, last_run=Last} = State) when Next-Last =< 0 -> reply_and_wait2(Reply, {ok, {State, 1000}}); reply_and_wait(Reply, #state{last_time=Now, next_run=NextMsec} = State) -> NowTime = current_epoch(Now, State), Timeout = round_timeout(NextMsec-NowTime), reply_and_wait2(Reply, {ok, {State, Timeout}}). reply_and_wait2(noreply, {ok, {State, Timeout}}) -> {noreply, State, Timeout}; reply_and_wait2(Reply, {ok, {State, Timeout}}) -> {reply, Reply, State, Timeout}; reply_and_wait2(noreply, {error, {State, _}}) -> {stop, normal, State}; reply_and_wait2(Reply, {error, {State, _}}) -> {stop, normal, Reply, State}. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% The returned duration is set to the maximum of 1 hour at which %% point the duration is recalculated, so that daylight savings time %% adjustments don't affect the precision of when a task is run. -spec until_next_milliseconds(#state{}) -> {ok, {#state{}, erlcron:milliseconds()}} | {error, {#state{}, term()}}. until_next_milliseconds(#state{} = S) -> try Epoch = ecrn_util:epoch_milliseconds(), {Msec, S1} = until_next_time(S#state{last_time=Epoch}), {ok, update_next_run(S1, max(0, Msec))} catch ?EXCEPTION(_, E, ST) -> {error, {S, {E, ?GET_STACK(ST)}}} end. -spec update_next_run(#state{}, erlcron:seconds()) -> {#state{}, erlcron:milliseconds()}. update_next_run(#state{} = State, ?SEC_IN_A_DAY) -> {State, ?MAX_TIMEOUT_MSEC}; update_next_run(#state{last_time=Now} = State, Milliseconds) -> Timeout = round_timeout(Milliseconds), EpochS = current_epoch(Now, State), {State#state{next_run=EpochS+Milliseconds}, Timeout}. round_timeout(Milliseconds) -> trunc(max(0, min(Milliseconds, ?MAX_TIMEOUT_MSEC))). -type normalized_period() :: [{integer(), integer(), integer()}]. -type normalized_sched() :: {once, {relative|absolute, integer()}} | {daily, normalized_period()} | {weekly, [integer()], normalized_period()} | {monthly,integer(), normalized_period()}. -spec normalize(erlcron:run_when(), calendar:datetime()) -> normalized_sched(). normalize({once, I}, _) when is_integer(I) -> {once, {relative, to_milliseconds(I)}}; normalize({once, {H,M,S}=T}, {_, Time}) when is_integer(H), is_integer(M), is_integer(S) , H >= 0, H < 24, M >= 0, M < 59, S >= 0, S < 59 -> T < Time andalso throw({time_given_in_the_past, T}), {once, {absolute, resolve_time(T)}}; normalize({once, Period}, _) -> {once, {absolute, resolve_time(Period)}}; normalize({daily, Period}, _) -> {daily, lists:sort(resolve_period(Period))}; normalize({weekly, DoW, Period}, _) -> {weekly, resolve_dow(DoW), lists:sort(resolve_period(Period))}; normalize({monthly, Day, Period}, TodayDate) when is_integer(Day) -> normalize({monthly, [Day], Period}, TodayDate); normalize({monthly, Days, Period}=T, {{Y,M,_},_}) when is_list(Days) -> case [Day || Day <- Days, not is_integer(Day) orelse Day < -30 orelse Day > 31] of [] -> ok; _ -> throw({invalid_days_in_schedule, T}) end, {PosDays, NegDays} = lists:partition(fun(I) -> I > 0 end, Days), {ThisNextMonthDays, _State} = update_dom(Y,M, {undefined, {0,0, PosDays, NegDays}}, #state{job={T, undefined}}), {monthly, ThisNextMonthDays, lists:sort(resolve_period(Period))}; normalize(Other, _) -> throw({invalid_schedule, Other}). update_dom(Y,M, {_, {Y,M,_,_}}=When, State) -> {When, State}; update_dom(Y,M, {_, {_,_,PosDays,NegDays}}, State = #state{job = {{monthly, _, _Period}, Task}}) -> {_, _, ThisMonthDays} = month_days(Y, M, PosDays, NegDays, true), {NY,NM, NextMonFirstDay} = next_month_days(Y, M, PosDays, NegDays), ThisNextMonthDays = {ThisMonthDays, NY, NM, NextMonFirstDay}, When = {ThisNextMonthDays, {Y,M,PosDays,NegDays}}, {When, State#state{job={{monthly, When}, Task}}}. next_month_days(Y, 12, PosDays, NegDays) -> month_days(Y+1, 1, PosDays, NegDays, false); next_month_days(Y, M, [], NegDays) -> month_days(Y, M+1, [], NegDays, false); next_month_days(Y, M, PosDays, NegDays) -> % When checking next month, and PosDays contains days 29,30,31 % make sure that combining that with {Y,M} gives a valid date D = lists:min(PosDays), M1 = M+1, case calendar:valid_date({Y,M1,D}) of true -> month_days(Y, M1, PosDays, NegDays, false); false -> next_month_days(Y, M1, PosDays, NegDays) end. month_days(Y, M, PosDays, NegDays, false) -> LastDay = calendar:last_day_of_the_month(Y, M), Days = [I+LastDay || I <- NegDays] ++ PosDays, case [I || I <- Days, I =< LastDay, I > 0] of [] -> next_month_days(Y, M, PosDays, NegDays); L -> {Y, M, lists:min(L)} end; month_days(Y, M, PosDays, [], true) -> LastDay = calendar:last_day_of_the_month(Y, M), {Y, M, [I || I <- lists:sort(PosDays), I =< LastDay]}; month_days(Y, M, PosDays, NegDays, true) -> LastDay = calendar:last_day_of_the_month(Y, M), AllDays = PosDays ++ [I+LastDay || I <- NegDays], UniqDays= lists:sort(sets:to_list(sets:from_list(AllDays))), check_days(Y, M, UniqDays), {Y, M, [I || I <- UniqDays, I =< LastDay, I > 0]}. check_days(Y,M,Days) -> lists:foreach(fun(I) -> Date = {Y,M,I}, calendar:valid_date(Date) orelse throw({invalid_date, Date}) end, lists:takewhile(fun(I) -> I > 28 end, lists:reverse(Days))). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_time(erlcron:milliseconds(), erlcron:run_when()) -> erlcron:milliseconds(). until_next_time(NowEpochTime, Sched) when is_integer(NowEpochTime), is_tuple(Sched) -> DateTime = erlang:posixtime_to_universaltime(to_ceiling_seconds(NowEpochTime)), NormSched = normalize(Sched, DateTime), State = set_internal_time(#state{job={NormSched, undefined}}, DateTime, NowEpochTime), {Res, _State1} = until_next_time(State), Res. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. %% @private -spec until_next_time(state()) -> {erlcron:milliseconds(), state()}. until_next_time(State = #state{job={Sched, _Task}}) -> until_next_time2(State, Sched). until_next_time2(State, {once, {relative, Msec}}) when is_integer(Msec) -> {Msec, State}; until_next_time2(State, {once, {absolute, Msec}}) when is_integer(Msec) -> {normalize_to_relative(State, Msec), State}; until_next_time2(State, {daily, Period}) -> {until_next_daytime(State, Period, current_time(State)), State}; until_next_time2(State, {weekly, DoW, Period}) -> {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), Days = find_dow(Today, DoW), NextDays = fun() -> I = Today+1, N = if I>7 -> 1; true -> I end, find_dow(N, DoW) end, {until_next_time_from_now(State, Period, Days, NextDays), State}; until_next_time2(State, {monthly, When, Period}) -> {{ThisYear, ThisMonth, Today}=YMD, _} = current_date(State), {{{ThisMonthDays, NextY, NextM, NextMonthFirstDOM}, _}, State1} = update_dom(ThisYear, ThisMonth, When, State), {YMD1, YMD2} = case lists:dropwhile(fun(I) -> I < Today end, ThisMonthDays) of [DOM1, DOM2 | _] -> {{ThisYear,ThisMonth,DOM1}, {ThisYear,ThisMonth,DOM2}}; [DOM|_] -> {{ThisYear,ThisMonth,DOM}, {NextY,NextM,NextMonthFirstDOM}}; [] -> {{NextY, NextM, NextMonthFirstDOM}, {0,0,0}} end, TodayGreg = to_greg_days(YMD), NextGreg = to_greg_days(YMD1), Days = NextGreg - TodayGreg, NextDays = fun() -> to_greg_days(YMD2) - TodayGreg end, {until_next_time_from_now(State1, Period, Days, NextDays), State1}. until_next_time_from_now(State, Period, 0, NextDays) when is_function(NextDays, 0) -> CurrentTime = current_time(State), F = fun() -> until_days_from_now(State, Period, NextDays()-1) end, case last_time(Period) of T when CurrentTime > T -> F(); _ -> EndTime = last_time(Period), case next_time(Period, CurrentTime) of I when I > EndTime -> F(); I -> I - CurrentTime end end; until_next_time_from_now(State, Period, Days, _NextDays) when Days > 0 -> until_days_from_now(State, Period, Days-1). to_greg_days({Y,M,D}) -> calendar:date_to_gregorian_days(Y,M,D). %% @doc Calculates the time since midnight in milliseconds until the next time this %% period is to occur during the day. -spec until_next_daytime(state(), normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_next_daytime(State, Period, MsecsFromMidnight) -> StartTime = first_time(Period), EndTime = last_time(Period), if MsecsFromMidnight > EndTime -> until_tomorrow(State, StartTime); true -> case next_time(Period, MsecsFromMidnight) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> T - MsecsFromMidnight end end. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow(state(), erlcron:milliseconds()) -> erlcron:milliseconds(). until_tomorrow(State, StartTime) -> StartTime + 24*3600000 - current_time(State). %% @doc Calculates the duration in milliseconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), normalized_period(), integer()) -> erlcron:milliseconds(). until_days_from_now(State, Period, Days) -> MsecsUntilTomorrow = until_tomorrow(State, 0), MsecsUntilTomorrow + Days * 24 * 3600000 + until_next_daytime(State, Period, 0). %% @doc Calculates the first time in a given period. -spec first_time(normalized_period()) -> erlcron:milliseconds(). first_time([]) -> ?SEC_IN_A_DAY; first_time([{FromTime, _ToTime, _RepeatSec}|_]) -> FromTime. %% @doc Calculates the last time in a given period. -spec last_time(normalized_period()) -> erlcron:milliseconds(). last_time([]) -> ?SEC_IN_A_DAY; last_time(Period) when is_list(Period) -> F = fun({FromTime, _ToTime, 0}) -> FromTime; ({FromTime, ToTime, RepeatSec}) -> FromTime + ((ToTime-FromTime) div RepeatSec) * RepeatSec end, lists:max([F(R) || R <- Period]). %% @doc Calculates the first time in the given period after the given time. -spec next_time(normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). next_time([], _Time) -> ?SEC_IN_A_DAY; next_time(Period, Time) when is_list(Period), is_integer(Time) -> F = fun({FromTime, _ToTime, _RepeatSec}) when Time =< FromTime -> FromTime; ({_FromTime, _ToTime, 0}) -> ?SEC_IN_A_DAY; ({FromTime, _ToTime, RepeatSec}) -> A1 = ((Time-FromTime) div RepeatSec) * RepeatSec, A = if A1 < Time -> A1 + RepeatSec; true -> A1 end, FromTime + A end, case [F(R) || R = {_, ToTm, _} <- Period, Time =< ToTm] of [] -> ?SEC_IN_A_DAY; LL -> lists:min(LL) end. %% @doc Returns the current time, in milliseconds past midnight in local time zone. -spec current_time(state()) -> erlcron:milliseconds(). current_time(State = #state{last_time=Now}) -> % Take ceiling of time to the next second Msec = case (Now div 1000) * 1000 of Now -> 0; N -> Now-N end, {_, {H,M,S}} = current_date(State), to_milliseconds(S + M * 60 + H * 3600) + Msec. %% @doc Returns current date in local time current_date(#state{last_time=Now, ref_epoch=E, epoch_at_ref=S}) when is_integer(Now), Now > 0 -> Elapsed = Now - S, to_local_datetime(Elapsed + E). current_epoch(EpochMsec, #state{ref_epoch=RefEpoch, epoch_at_ref=Epoch}) -> Elapsed = EpochMsec - Epoch, Elapsed + RefEpoch. normalize_to_relative(State, Milliseconds) -> NowSec = current_time(State), Milliseconds - NowSec. %% @doc Returns a list of times given a periodic specification. -spec resolve_period([erlcron:period()] | erlcron:period()) -> [{erlcron:milliseconds(), erlcron:milliseconds(), erlcron:milliseconds()}]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration}) -> resolve_period({every, Duration, {between, {0,0,0}, {23,59,59}}}); resolve_period({every, Duration, {between, TimeA, TimeB}} = P) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), StartTime =< EndTime orelse throw({invalid_period, P}), [{StartTime, EndTime, Period}]; resolve_period(Time) -> T = resolve_time(Time), [{T, T, 0}]. %% @doc Returns seconds past midnight for a given time. -spec resolve_time(erlcron:cron_time()) -> erlcron:milliseconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> to_milliseconds(S + M * 60 + H * 3600); resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60 + S); resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + to_milliseconds(M*60); resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> to_milliseconds(H * 3600); resolve_time({12, pm}) -> to_milliseconds(12 * 3600); resolve_time({H, pm}) when H < 12 -> to_milliseconds((H + 12) * 3600); resolve_time(Other) -> throw({invalid_time, Other}). %% @doc Returns seconds for a given duration. -spec resolve_dur(erlcron:duration()) -> erlcron:milliseconds(). resolve_dur({Hour, H}) when H==h; H==hr -> to_milliseconds(Hour * 3600); resolve_dur({Min, M}) when M==m; M==min -> to_milliseconds(Min * 60); resolve_dur({Sec, S}) when S==s; S==sec -> to_milliseconds(Sec); resolve_dur(Other) -> throw({invalid_duration, Other}). %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow(erlcron:dow()) -> [integer()]. resolve_dow(I) when is_atom(I) -> [resolve_dow2(I)]; resolve_dow([I]) -> [resolve_dow2(I)]; resolve_dow(L) when is_list(L) -> lists:sort([resolve_dow2(I) || I <- L]). resolve_dow2(mon) -> 1; resolve_dow2(tue) -> 2; resolve_dow2(wed) -> 3; resolve_dow2(thu) -> 4; resolve_dow2(fri) -> 5; resolve_dow2(sat) -> 6; resolve_dow2(sun) -> 7. -spec find_dow(integer(), [integer()]) -> integer(). find_dow(_TodayDOW, []) -> throw(invalid_dow_period); find_dow(TodayDOW, [FirstDOW|_]=DOWs) -> find_dow(TodayDOW, DOWs, FirstDOW). find_dow(TodayDOW, [TodayDOW|_], _) -> 0; find_dow(TodayDOW, [DOW|_], _FirstDOW) when TodayDOW < DOW -> DOW-TodayDOW; find_dow(TodayDOW, [DOW|T], FirstDOW) when TodayDOW > DOW -> find_dow(TodayDOW, T, FirstDOW); find_dow(TodayDOW, [], FirstDOW) -> FirstDOW+7 - TodayDOW. set_internal_time(State, RefDate, CurEpochMsec) -> EpochS = to_seconds(CurEpochMsec), FloorE = to_milliseconds(EpochS), Msec = to_milliseconds(erlang:universaltime_to_posixtime(RefDate)), State1 = State#state{ref_epoch=Msec, epoch_at_ref=FloorE}, %Now = Msec + CurEpochMsec - FloorE, State1#state{last_time=CurEpochMsec}. %% @doc NewDate is in universal time. fast_forward(#state{ref_epoch=OldRefEpoch, next_run=NextRun}=S, NewRefEpoch, NewDate, Count) -> {Msec, State1} = until_next_time(S#state{last_time=OldRefEpoch, epoch_at_ref=OldRefEpoch}), Span = NewRefEpoch - OldRefEpoch, if Span =< Msec; Msec =:= 0 -> true; true -> RefMsec = OldRefEpoch + Msec, State2 = State1#state{ref_epoch = RefMsec+1, last_run=NextRun, next_run=RefMsec}, do_job_run(State2), case State2#state.job of {{once, _}, _} when Count =:= 1 -> Msec =< 0 andalso ?LOG_WARNING([{info, "One-time job executed immediately due to negative time shift"}, {time_shift_secs, to_seconds(Msec)}, {job_ref, State2#state.alarm_ref}, {job_when, State2#state.orig_when}]), false; _ -> fast_forward(State2, NewRefEpoch, NewDate, Count+1) end end. to_local_datetime(Milliseconds) when is_integer(Milliseconds) -> DT = to_universal_datetime(Milliseconds), erlang:universaltime_to_localtime(DT). to_universal_datetime(Milliseconds) -> erlang:posixtime_to_universaltime(to_seconds(Milliseconds)). to_milliseconds(Secs) -> Secs * 1000. to_seconds(MilliSec) -> MilliSec div 1000. to_ceiling_seconds(Msec) -> S = to_seconds(Msec), case to_milliseconds(S) of Msec -> S; _ -> S+1 end. %%%=================================================================== %%% Tests %%%=================================================================== -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -ifdef(EUNIT). dow_test() -> DOWs = resolve_dow([tue,wed,thu]), ?assertEqual([7], resolve_dow(sun)), ?assertEqual([7], resolve_dow([sun])), ?assertEqual([1,2], resolve_dow([mon,tue])), ?assertEqual([2,3,4], DOWs), ?assertEqual(1, find_dow(1, DOWs)), ?assertEqual(0, find_dow(2, DOWs)), ?assertEqual(0, find_dow(3, DOWs)), ?assertEqual(0, find_dow(4, DOWs)), ?assertEqual(4, find_dow(5, DOWs)), DOWs1 = resolve_dow([thu,sat]), ?assertEqual([4,6], DOWs1), ?assertEqual(3, find_dow(1, DOWs1)), ?assertEqual(2, find_dow(2, DOWs1)), ?assertEqual(1, find_dow(3, DOWs1)), ?assertEqual(0, find_dow(4, DOWs1)), ?assertEqual(1, find_dow(5, DOWs1)), ?assertEqual(0, find_dow(6, DOWs1)), ?assertEqual(4, find_dow(7, DOWs1)), ok. normalize_test() -> Date = {date(), {0,0,0}}, ?assertEqual({once,{relative,1000}}, normalize({once, 1}, Date)), ?assertEqual({once,{absolute,43200000}}, normalize({once, {12,pm}}, Date)), ?assertThrow({time_given_in_the_past,{2,3,4}}, normalize({once, {2,3,4}}, {date(), {2,3,5}})), ?assertEqual({once,{absolute,7384000}}, normalize({once, {2,3,4}}, Date)), ?assertEqual({daily,[{50400000,50400000,0}]}, normalize({daily, {2,pm}}, Date)), ?assertEqual({daily,[{0,86399000,20000}]}, normalize({daily, {every, {20,s}}}, Date)), ?assertEqual({daily,[{3600000,3600000,0},{7200000,7200000,0}]}, normalize({daily, [{2,am},{1,am}]}, Date)), ?assertEqual({daily,[{0,86399000,5000},{0,86399000,20000}]}, normalize({daily, [{every, {5,s}}, {every, {20,s}}]}, Date)), ?assertEqual({daily,[{3600000,7200000,20000}]}, normalize({daily, {every, {20,s}, {between, {1,am}, {2,am}}}}, Date)), ?assertEqual({weekly,[1], [{3600000,3600000,0}]}, normalize({weekly, mon, {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [mon,wed], {1,am}}, Date)), ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [wed,mon], {1,am}}, Date)), diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 8ccb1a6..8191db6 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,146 +1,174 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, datetime/1, + ref_datetime/0, + ref_datetime/1, set_datetime/1, set_datetime/2, reset_datetime/0, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). -record(state, {ref_time :: calendar:datetime(), epoch_at_ref :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). -spec cancel(erlcron:job_ref()) -> boolean(). cancel(AlarmRef) -> ecrn_reg:cancel(AlarmRef). -%% @doc Returns universal time. +%% @doc +%% Returns current datetime with reference adjustment in universal time zone. -spec datetime() -> {calendar:datetime(), erlcron:milliseconds()}. datetime() -> - gen_server:call(?SERVER, get_datetime). + gen_server:call(?SERVER, datetime). +%% @doc +%% Returns current datetime with reference adjustment in universal/local time zone. -spec datetime(local|universal) -> {calendar:datetime(), erlcron:milliseconds()}. datetime(universal) -> datetime(); datetime(local) -> {DT, Epoch} = datetime(), - {calendar:universal_time_to_local_time(DT), Epoch}. + {erlang:universaltime_to_localtime(DT), Epoch}. + +%% @doc Returns reference datetime in universal time zone. +-spec ref_datetime() -> {calendar:datetime(), erlcron:milliseconds()}. +ref_datetime() -> + gen_server:call(?SERVER, ref_datetime). + +%% @doc Returns reference datetime in universal or local time zone. +-spec ref_datetime(local|universal) -> {calendar:datetime(), erlcron:milliseconds()}. +ref_datetime(universal) -> + ref_datetime(); +ref_datetime(local) -> + {DT, Epoch} = ref_datetime(), + {erlang:universaltime_to_localtime(DT), Epoch}. %% @doc sets the date-time for the erlcron -spec set_datetime(calendar:datetime()) -> ok | {error, term()}. set_datetime(DateTime) -> set_datetime(DateTime, local). -spec set_datetime(calendar:datetime(), local|universal) -> ok | {error, term()}. set_datetime(DT={_,_}, local) -> gen_server:call(?SERVER, {set_datetime, erlang:localtime_to_universaltime(DT)}, infinity); set_datetime(DateTime={_,_}, universal) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc Reset reference datetime to current epoch datetime -spec reset_datetime() -> ok | {error, term()}. reset_datetime() -> gen_server:call(?SERVER, reset_datetime, infinity). %% @doc sets the date-time with the erlcron on all nodes -spec multi_set_datetime([node()], calendar:datetime()) -> ok | {error, term()}. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> DateTime = erlang:universaltime(), {ok, #state{ref_time=DateTime, epoch_at_ref=ecrn_util:epoch_milliseconds()}}. %% @private -handle_call(get_datetime, _From, State = #state{ref_time = DateTime, +handle_call(datetime, _From, State = #state{ref_time = DateTime, + epoch_at_ref = Actual}) -> + DT = erlang:universaltime_to_posixtime(DateTime), + Now = ecrn_util:epoch_milliseconds(), + Diff = Now - Actual, + DiffS = to_seconds(Diff), + RefNow = DT + Diff, + Msecs = Diff - DiffS*1000, + NowDT = erlang:posixtime_to_universaltime(RefNow), + {reply, {NowDT, RefNow*1000 + Msecs}, State}; +handle_call(ref_datetime, _From, State = #state{ref_time = DateTime, epoch_at_ref = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{ref_time=DateTime, epoch_at_ref=ecrn_util:epoch_milliseconds()}, {reply, call_all(NewState), NewState}; handle_call(reset_datetime, _From, State) -> Now = ecrn_util:epoch_milliseconds(), DateTime = erlang:posixtime_to_universaltime(to_seconds(Now)), NewState = State#state{ref_time=DateTime, epoch_at_ref=Now}, {reply, call_all(NewState), NewState}. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== %notify_all(#state{ref_time=DateTime, epoch_at_ref=Now}=State) -> % [ecrn_agent:set_datetime(P, DateTime, Now, universal) || P <- ecrn_reg:get_all_pids()], % State. call_all(#state{ref_time=DateTime, epoch_at_ref=Now}) -> Res = lists:foldl(fun(P, A) -> case ecrn_agent:set_datetime(P, DateTime, Now, universal) of ok -> A; {error, Err} -> Ref = try ecrn_reg:get_refs(P) catch _:_ -> [] end, [{Ref, P, Err} | A] end end, [], ecrn_reg:get_all_pids()), case Res of [] -> ok; _ -> {error, {failed_to_set_time, Res}} end. to_seconds(MilliSec) -> MilliSec div 1000. diff --git a/src/erlcron.erl b/src/erlcron.erl index ebc9326..eea0756 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,188 +1,197 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, cron/2, at/2, at/3, daily/2, daily/3, weekly/3, weekly/4, monthly/3,monthly/4, cancel/1, epoch/0, epoch_seconds/0, datetime/0, + ref_datetime/0, set_datetime/1, reset_datetime/0, get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0, milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | h | min | m | sec | s}. -type period() :: cron_time() | {every, duration()} | {every, duration(), constraint()}. -type dom() :: integer(). -type dow_day() :: mon | tue | wed | thu | fri | sat | sun. -type dow() :: dow_day() | [dow_day()]. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | fun(() -> ok) | fun((JobRef::atom()|reference(), calendar:datetime()) -> ok). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom()|[dom()], period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference() | atom(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref(). cron(Job) -> cron(make_ref(), Job). -spec cron(job_ref(), job()) -> job_ref(). cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef)) , is_tuple(Job) -> ecrn_cron_sup:add_job(JobRef, Job). %% @doc %% Run the specified job once after the amount of time specifed. -spec at(cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> at(make_ref(), When, Fun). -spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref(). at(JobRef, When, Fun) -> cron(JobRef, {{once, When}, Fun}). %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. -spec daily(cron_time() | seconds(), function()) -> job_ref(). daily(When, Fun) -> daily(make_ref(), When, Fun). -spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref(). daily(JobRef, When, Fun) -> cron(JobRef, {{daily, When}, Fun}). %% @doc %% Convienience method to specify a job run to run on a weekly basis %% at a specific time. -spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref(). weekly(DOW, When, Fun) -> weekly(make_ref(), DOW, When, Fun). -spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref(). weekly(JobRef, DOW, When, Fun) -> cron(JobRef, {{weekly, DOW, When}, Fun}). %% @doc %% Convienience method to specify a job run to run on a weekly basis %% at a specific time. -spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref(). monthly(DOM, When, Fun) -> monthly(make_ref(), DOM, When, Fun). -spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref(). monthly(JobRef, DOM, When, Fun) -> cron(JobRef, {{monthly, DOM, When}, Fun}). %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc -%% Get the current date time in seconds since epoch. --spec epoch() -> erlcron:milliseconds(). +%% Get the current date time in seconds millisince epoch. +-spec epoch() -> milliseconds(). epoch() -> ecrn_util:epoch_milliseconds(). %% @doc -%% Get the current date time in milliseconds since epoch. --spec epoch_seconds() -> erlcron:seconds(). +%% Get the current date time in seconds since epoch. +-spec epoch_seconds() -> seconds(). epoch_seconds() -> ecrn_util:epoch_seconds(). %% @doc -%% Get the current date time of the running erlcron system. --spec datetime() -> {calendar:datetime(), seconds()}. +%% Get the current date time of the erlcron system adjusted to reference. +%% +-spec datetime() -> {calendar:datetime(), milliseconds()}. datetime() -> ecrn_control:datetime(). %% @doc -%% Set the current date time of the running erlcron system. +%% Get the reference date time of the erlcron system. +%% +-spec ref_datetime() -> {calendar:datetime(), milliseconds()}. +ref_datetime() -> + ecrn_control:ref_datetime(). + +%% @doc +%% Set the current date time of the running erlcron system. -spec set_datetime(calendar:datetime()) -> ok. set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:set_datetime(DateTime). %% @doc %% Reset the reference datetime of erlcron system to current epoch time. -spec reset_datetime() -> ok. reset_datetime() -> ecrn_control:reset_datetime(). %% Get references of all running jobs -spec get_all_jobs() -> [job_ref()]. get_all_jobs() -> ecrn_reg:get_all_refs(). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> ok. multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
469108cbc69146740486edc077522f0d676532e1
Fix several bugs:
diff --git a/.travis.yml b/.travis.yml index 5f9909c..3c80414 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,12 @@ sudo: false language: erlang otp_release: - - R15B03 - - R16B03-1 - - 17.5 - - 18.0 - - 18.1 - - 19.0 + - 20.0 + - 21.0 + - 22.0 before_script: "make get-deps" script: "make test" branches: only: - master diff --git a/README.md b/README.md index 9fd17ad..d864df2 100644 --- a/README.md +++ b/README.md @@ -1,145 +1,169 @@ Erlcron ======= Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The synax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. -Unlike cron's one-minute resolution, erlcron has a 2-second resolution -(actually 1 second, but after running the job, the process waits an -extra second to avoid accidentally running it more than once.) +Unlike cron's one-minute resolution, erlcron has a millisecond resolution. -It does not handle Daylight Savings Time (or other cases when the -system clock is altered) gracefully, and it is recommended that it be -stopped and restarted on such occasions. +It does handle Daylight Savings Time changes (but not the cases when the +system clock is altered by small increments, in which case the next +execution of a scheduled task may be imprecise). Cron Job Description Examples: ```erlang +{{once, {3, 30, pm}, fun() -> io:fwrite("Hello world!~n") end} + +{{once, {3, 30, pm}, fun(JobRef, CurrDateTime) -> io:fwrite("Hello world!~n") end} + {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, fun() -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, {fun() -> io:fwrite("It's 2 Wednesday morning~n") end} +{{weekly, [tue,wed], {2, am}}, + {fun(_, Now) -> io:format("Now is ~p~n", [Now]) end} + {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} +{{monthly, [1, 7, 14], {2, am}}, + {io, fwrite, ["Every 1st, 7th, 14th of the month!~n"]}} + +{{monthly, 0, {2, am}}, + {io, fwrite, ["Last day of the month!~n"]}} + +{{monthly, [0, -1], {2, am}}, + {io, fwrite, ["Last two days of the month!~n"]}} + {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} + +%% Days of month less or equal to zero are subtracted from the end of the month +{{monthly, 0, {2, am}}, + {io, fwrite, ["Last day of the month!~n"]}} ``` Adding a cron to the system: ```erlang Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job). ``` +Cron jobs can be given named atom references: + +```erlang +erlcron:cron(test_job1, {{once, {3,pm}}, {io, fwrite, "It's 3pm"}}). +``` + A simple way to add a daily cron: - erlcron:at({3, 30, pm}, Fun). + erlcron:daily({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. ```erlang -erlcron:once(300, Fun). +erlcron:at(300, Fun). ``` Cancel a running job. ```erlang erlcron:cancel(JobRef). ``` -Get the current date time of the system. +Get the current reference (univeral) date time of the system. ```erlang erlcron:datetime(). ``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:set_datetime(DateTime). ``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(DateTime). ``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(Nodes, DateTime). ``` The application cron can be pre-configured throught environment variables in the config file that all applications can load in the Erlang VM start. The app.config file can be as follow: ```erlang [ {erlcron, [ {crontab, [ {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}}, {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} ]} ]} ]. ``` So, when the app will be started, all configurations will be loaded. Note that the limitation is that in the config file is impossible load an anonymous function (or lambda function) so, you only can use {M,F,A} format. diff --git a/rebar.config b/rebar.config index 9818237..5129c17 100644 --- a/rebar.config +++ b/rebar.config @@ -1,20 +1,18 @@ %% -*- mode: Erlang; fill-column: 80; comment-column: 75; -*- %% Dependencies ================================================================ -{deps, [{rebar_vsn_plugin, ".*", - {git, "https://github.com/erlware/rebar_vsn_plugin.git", - {tag, "master"}}}]}. +{deps, []}. %% Rebar Plugins ============================================================== -{plugins, [rebar_vsn_plugin]}. +{plugins, []}. %% Compiler Options ============================================================ {erl_opts, [debug_info, warnings_as_errors]}. %% EUnit ======================================================================= {eunit_opts, [verbose, {report, {eunit_surefire, [{dir, "."}]}}]}. {cover_enabled, true}. {cover_print_enabled, true}. diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index dde1b76..7343e1b 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,417 +1,755 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). - -behaviour(gen_server). %% API -export([start_link/2, cancel/1, + next_run/1, get_datetime/1, + get_datetime/2, set_datetime/3, + set_datetime/4, recalculate/1, - validate/1]). + validate/1, + until_next_time/2, + normalize/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, - referenced_seconds, - seconds_at_reference, - timeout_type, - fast_forward=false}). - --define(MILLISECONDS, 1000). --define(WAIT_BEFORE_RUN, 2000). + ref_epoch, + epoch_at_ref, + fast_forward=false, + last_time, + next_run, % Time in EPOCH seconds until task's next execution + last_run, % Time in EPOCH seconds when the task was last run + orig_when + }). + +-define(MILLISECONDS, 1000). +-define(WAIT_BEFORE_RUN, 1000). +-define(MAX_TIMEOUT_SEC, 1800). +-define(MAX_TIMEOUT_MSEC, 1800000). +-define(SEC_IN_A_DAY, 86400). + +%% compatibility +-ifdef(OTP_RELEASE). %% this implies 21 or higher +-define(EXCEPTION(Class, Reason, Stacktrace), Class:Reason:Stacktrace). +-define(GET_STACK(Stacktrace), Stacktrace). +-include_lib("kernel/include/logger.hrl"). +-else. +-define(EXCEPTION(Class, Reason, _), Class:Reason). +-define(GET_STACK(_), erlang:get_stacktrace()). +-define(LOG_ERROR(Report), error_logger:error_report(Report)). +-define(LOG_WARNING(Report), error_logger:warning_report(Report)). +-endif. %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref -spec start_link(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. -start_link(JobRef, Job) -> - gen_server:start_link(?MODULE, [JobRef, Job], []). +start_link(JobRef, {When, _Task} = Job) when is_reference(JobRef) -> + {Sched, DateTime, ActualMsec} = normalize_when(When), + gen_server:start_link(?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []); +start_link(JobRef, {When, _Task} = Job) when is_atom(JobRef) -> + {Sched, DateTime, ActualMsec} = normalize_when(When), + gen_server:start_link({local, JobRef}, ?MODULE, [JobRef, Job, Sched, DateTime, ActualMsec], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> + get_datetime(Pid, local). + +-spec get_datetime(pid(), local|universal) -> calendar:datetime(). +get_datetime(Pid, local) -> + erlang:universaltime_to_localtime(get_datetime(Pid, universal)); +get_datetime(Pid, universal) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. -cancel(Pid) -> +cancel(Pid) when is_pid(Pid); is_atom(Pid) -> gen_server:cast(Pid, shutdown). --spec set_datetime(pid(), calendar:datetime(), erlcron:seconds()) -> ok. +-spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> - gen_server:cast(Pid, {set_datetime, DateTime, Actual}). + set_datetime(Pid, DateTime, Actual, local). + +-spec set_datetime(pid(), calendar:datetime(), erlcron:milliseconds(), UTC::local|universal) -> + ok | {error, term()}. +set_datetime(Pid, DateTime, Actual, UTC) -> + DT = case UTC of + local -> erlang:localtime_to_universaltime(DateTime); + universal -> DateTime + end, + Res = gen_server:call(Pid, {set_datetime, DT, Actual}, infinity), + Res. -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). +%% @doc +%% Get job's next execution time +-spec next_run(pid()) -> erlang:timestamp(). +next_run(Pid) -> + gen_server:call(Pid, next_run). + %% @doc %% Validate that a run_when spec specified is correct. --spec validate(erlcron:run_when()) -> valid | invalid. +-spec validate(erlcron:run_when()) -> ok | {error, term()}. validate(Spec) -> - State = #state{job=undefined, - alarm_ref=undefined}, - {DateTime, Actual} = ecrn_control:datetime(), - NewState = set_internal_time(State, DateTime, Actual), + State = #state{job=undefined, alarm_ref=undefined}, + {DateTime, ActualMsec} = ecrn_control:datetime(universal), + NewState = set_internal_time(State, DateTime, ActualMsec), try - until_next_time(NewState, {Spec, undefined}), - valid + NormalSpec = normalize(Spec, DateTime), + {Msec,_} = until_next_time(NewState#state{job={NormalSpec, undefined}}), + Msec > 0 orelse throw({specified_time_past_seconds_ago, to_seconds(Msec)}), + ok catch - _Error:_Reason -> - invalid + _Error:Reason -> + {error, Reason} end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== - %% @private -init([JobRef, Job]) -> - State = #state{job=Job, - alarm_ref=JobRef}, - {DateTime, Actual} = ecrn_control:datetime(), - NewState = set_internal_time(State, DateTime, Actual), - case until_next_milliseconds(NewState, Job) of - {ok, Millis} when is_integer(Millis) -> - ecrn_reg:register(JobRef, self()), - {ok, NewState, Millis}; - {error, _} -> - {stop, normal} +init([JobRef, {When, Task}, Sched, DateTime, ActualMsec]) -> + try + State = set_internal_time(#state{alarm_ref=JobRef, job={Sched, Task}, + last_run=0, next_run=0, orig_when=When}, + DateTime, ActualMsec), + case until_next_milliseconds(State) of + {ok, {NewState, Timeout}} -> + ecrn_reg:register(JobRef, self()), + {ok, NewState, Timeout}; + {error, {_, Reason}} -> + throw(Reason) + end + catch ?EXCEPTION(_, E, ST) -> + ?LOG_ERROR([{error, "Error setting timeout for job"}, + {job_ref, JobRef}, {run_when, When}, + {reason, E}, + {stack, ?GET_STACK(ST)}]), + {stop, normal} end. %% @private -handle_call(_Msg, _From, State) -> - case until_next_milliseconds(State, State#state.job) of - {ok, Millis} -> - {reply, ok, State, Millis}; - {error, _} -> - {stop, normal, ok, State} - end. +handle_call(next_run, _From, #state{next_run=Time} = State) -> + reply_and_wait(Time, State); +handle_call(get_datetime, _From, State) -> + Epoch = ecrn_util:epoch_milliseconds(), + Msec = current_epoch(Epoch, State), + DT = to_universal_datetime(Msec), + reply_and_wait(DT, State#state{last_time=Epoch}); +handle_call({set_datetime, DateTime, CurrEpochMsec}, _From, State) -> + try + NewRefEpoch = to_milliseconds(erlang:universaltime_to_posixtime(DateTime)), + case fast_forward(State#state{fast_forward=true}, NewRefEpoch, DateTime, 1) of + true -> + NewState = set_internal_time(State#state{next_run=0}, DateTime, CurrEpochMsec), + reply_and_wait(ok, NewState); + false -> + {stop, normal, ok, State} + end + catch ?EXCEPTION(_, E, ST) -> + ?LOG_ERROR([{error, "Error setting timeout for job"}, + {job_ref, State#state.alarm_ref}, + {run_when, element(1, State#state.orig_when)}, + {reason, E}, + {stack, ?GET_STACK(ST)}]), + reply_and_wait({error, E}, State) + end; +handle_call(Msg, _From, State) -> + {stop, State, {not_implemented, Msg}}. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; -handle_cast({set_datetime, DateTime, Actual}, State) -> - fast_forward(State#state{fast_forward=true}, DateTime), - NewState = set_internal_time(State, DateTime, Actual), - case until_next_milliseconds(NewState, NewState#state.job) of - {ok, Millis} -> - {noreply, NewState, Millis}; - {error, _} -> - {stop, normal, NewState} - end. +handle_cast(Other, State) -> + {stop, {not_implemented, Other}, State}. %% @private -handle_info(timeout, State = #state{job = {{once, _}, _}}) -> - do_job_run(State, State#state.job), - {stop, normal, State}; -handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> - NewState = State#state{timeout_type=normal}, - case until_next_milliseconds(NewState, NewState#state.job) of - {ok, Millis} -> - {noreply, NewState, Millis}; - {error, _} -> - {stop, normal, NewState} - end; -handle_info(timeout, State = #state{job = Job}) -> - do_job_run(State, Job), - NewState = State#state{timeout_type=wait_before_run}, - {noreply, NewState, ?WAIT_BEFORE_RUN}. +handle_info(timeout, S) -> + process_timeout(S); + +handle_info({'EXIT', _, Reason}, State) -> + {stop, Reason, State}; +handle_info(_Msg, State) -> + {noreply, State, 1000}. %% @private -terminate(_Reason, #state{alarm_ref=Ref}) -> - ecrn_reg:unregister(Ref), +terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== +normalize_when(When) -> + {DateTime, ActualMsec} = ecrn_control:datetime(universal), + Sched = normalize(When, erlang:universaltime_to_localtime(DateTime)), + {Sched, DateTime, ActualMsec}. + +process_timeout(#state{last_time=LastTime, next_run=NextRun, last_run=LastRun}=S) -> + Epoch = ecrn_util:epoch_milliseconds(), + NowMsec = current_epoch(Epoch, S), + {Reply, State} = + if + LastTime < Epoch, NextRun > LastRun, NowMsec >= NextRun -> + {do_job_run(S), S#state{last_run=NextRun, next_run=0}}; + NextRun == LastRun -> + S#state.fast_forward orelse timer:sleep(1), + {noreply, S#state{next_run=0}}; + true -> + {noreply, S#state{last_time=Epoch}} + end, + reply_and_wait(Reply, State). -do_job_run(State, {_, Job}) - when is_record(State, state), is_function(Job) -> - RunFun = fun() -> - Job(State#state.alarm_ref, current_date(State)) - end, - proc_lib:spawn(RunFun); -do_job_run(State, {_, {M, F, A}}) - when is_record(State, state) -> - proc_lib:spawn(M, F, A). +do_job_run(#state{alarm_ref=Ref, next_run=Time, job={When, Job}} = S) -> + execute(Job, Ref, Time), + case When of + {once, _} -> + stop; + _ -> + S#state.fast_forward orelse timer:sleep(1), + noreply + end. -%% @doc Returns the current time, in seconds past midnight. --spec current_time(state()) -> erlcron:seconds(). -current_time(State) -> - {_, {H,M,S}} = current_date(State), - S + M * 60 + H * 3600. +execute(Job, Ref, Time) when is_function(Job, 2) -> + proc_lib:spawn(fun() -> Job(Ref, Time) end); +execute(Job, _, _) when is_function(Job, 0) -> + proc_lib:spawn(Job); +execute({M, F, A}, _, _) when is_atom(M), is_atom(F), is_list(A) -> + proc_lib:spawn(M, F, A). -current_date(State = #state{fast_forward=true}) -> - calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); -current_date(State) -> - Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, - calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + - State#state.referenced_seconds)). +reply_and_wait(stop, State) -> + {stop, normal, State}; +reply_and_wait(Reply, #state{next_run=0} = State) -> + reply_and_wait2(Reply, until_next_milliseconds(State)); +reply_and_wait(Reply, #state{next_run=Next, last_run=Last} = State) when Next-Last =< 0 -> + reply_and_wait2(Reply, {ok, {State, 1000}}); +reply_and_wait(Reply, #state{last_time=Now, next_run=NextMsec} = State) -> + NowTime = current_epoch(Now, State), + Timeout = round_timeout(NextMsec-NowTime), + reply_and_wait2(Reply, {ok, {State, Timeout}}). + +reply_and_wait2(noreply, {ok, {State, Timeout}}) -> {noreply, State, Timeout}; +reply_and_wait2(Reply, {ok, {State, Timeout}}) -> {reply, Reply, State, Timeout}; +reply_and_wait2(noreply, {error, {State, _}}) -> {stop, normal, State}; +reply_and_wait2(Reply, {error, {State, _}}) -> {stop, normal, Reply, State}. %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. --spec until_next_milliseconds(state(), erlcron:job()) -> - {ok, erlcron:seconds()} | {error, invalid_one_exception}. -until_next_milliseconds(State, Job) -> +%% The returned duration is set to the maximum of 1 hour at which +%% point the duration is recalculated, so that daylight savings time +%% adjustments don't affect the precision of when a task is run. +-spec until_next_milliseconds(#state{}) -> + {ok, {#state{}, erlcron:milliseconds()}} | + {error, {#state{}, term()}}. +until_next_milliseconds(#state{} = S) -> try - Millis = until_next_time(State, Job) * ?MILLISECONDS, - {ok, Millis} + Epoch = ecrn_util:epoch_milliseconds(), + {Msec, S1} = until_next_time(S#state{last_time=Epoch}), + {ok, update_next_run(S1, max(0, Msec))} catch - throw:invalid_once_exception -> - {error, invalid_once_exception} + ?EXCEPTION(_, E, ST) -> + {error, {S, {E, ?GET_STACK(ST)}}} end. -%%-ifdef(OTP_VSN_21_AND_ABOVE). --ifdef(OTP_RELEASE). -%% OTP 21 or higher -normalize_seconds(State, Seconds) -> - %% change for R21 - %% get_stacktrace/0 not supported - try - Value = Seconds - current_time(State), - true = (Value >= 0) - catch - _C:_R:StackTrace -> - erlang:display(StackTrace), - throw(invalid_once_exception) - end. --else. -normalize_seconds(State, Seconds) -> - case Seconds - current_time(State) of - Value when Value >= 0 -> - Value; - _ -> - erlang:display(erlang:get_stacktrace()), - throw(invalid_once_exception) +-spec update_next_run(#state{}, erlcron:seconds()) -> {#state{}, erlcron:milliseconds()}. +update_next_run(#state{} = State, ?SEC_IN_A_DAY) -> + {State, ?MAX_TIMEOUT_MSEC}; +update_next_run(#state{last_time=Now} = State, Milliseconds) -> + Timeout = round_timeout(Milliseconds), + EpochS = current_epoch(Now, State), + {State#state{next_run=EpochS+Milliseconds}, Timeout}. + +round_timeout(Milliseconds) -> + trunc(max(0, min(Milliseconds, ?MAX_TIMEOUT_MSEC))). + +-type normalized_period() :: [{integer(), integer(), integer()}]. +-type normalized_sched() :: + {once, {relative|absolute, integer()}} | + {daily, normalized_period()} | + {weekly, [integer()], normalized_period()} | + {monthly,integer(), normalized_period()}. + +-spec normalize(erlcron:run_when(), calendar:datetime()) -> normalized_sched(). +normalize({once, I}, _) when is_integer(I) -> + {once, {relative, to_milliseconds(I)}}; +normalize({once, {H,M,S}=T}, {_, Time}) when is_integer(H), is_integer(M), is_integer(S) + , H >= 0, H < 24, M >= 0, M < 59, S >= 0, S < 59 -> + T < Time andalso throw({time_given_in_the_past, T}), + {once, {absolute, resolve_time(T)}}; +normalize({once, Period}, _) -> + {once, {absolute, resolve_time(Period)}}; +normalize({daily, Period}, _) -> + {daily, lists:sort(resolve_period(Period))}; +normalize({weekly, DoW, Period}, _) -> + {weekly, resolve_dow(DoW), lists:sort(resolve_period(Period))}; +normalize({monthly, Day, Period}, TodayDate) when is_integer(Day) -> + normalize({monthly, [Day], Period}, TodayDate); +normalize({monthly, Days, Period}=T, {{Y,M,_},_}) when is_list(Days) -> + case [Day || Day <- Days, not is_integer(Day) orelse Day < -30 orelse Day > 31] of + [] -> ok; + _ -> throw({invalid_days_in_schedule, T}) + end, + {PosDays, NegDays} = lists:partition(fun(I) -> I > 0 end, Days), + {ThisNextMonthDays, _State} = + update_dom(Y,M, {undefined, {0,0, PosDays, NegDays}}, #state{job={T, undefined}}), + {monthly, ThisNextMonthDays, lists:sort(resolve_period(Period))}; +normalize(Other, _) -> + throw({invalid_schedule, Other}). + +update_dom(Y,M, {_, {Y,M,_,_}}=When, State) -> + {When, State}; +update_dom(Y,M, {_, {_,_,PosDays,NegDays}}, + State = #state{job = {{monthly, _, _Period}, Task}}) -> + {_, _, ThisMonthDays} = month_days(Y, M, PosDays, NegDays, true), + {NY,NM, NextMonFirstDay} = next_month_days(Y, M, PosDays, NegDays), + ThisNextMonthDays = {ThisMonthDays, NY, NM, NextMonFirstDay}, + When = {ThisNextMonthDays, {Y,M,PosDays,NegDays}}, + {When, State#state{job={{monthly, When}, Task}}}. + + +next_month_days(Y, 12, PosDays, NegDays) -> + month_days(Y+1, 1, PosDays, NegDays, false); +next_month_days(Y, M, [], NegDays) -> + month_days(Y, M+1, [], NegDays, false); +next_month_days(Y, M, PosDays, NegDays) -> + % When checking next month, and PosDays contains days 29,30,31 + % make sure that combining that with {Y,M} gives a valid date + D = lists:min(PosDays), + M1 = M+1, + case calendar:valid_date({Y,M1,D}) of + true -> + month_days(Y, M1, PosDays, NegDays, false); + false -> + next_month_days(Y, M1, PosDays, NegDays) end. --endif. -%% @doc Calculates the duration in seconds until the next time +month_days(Y, M, PosDays, NegDays, false) -> + LastDay = calendar:last_day_of_the_month(Y, M), + Days = [I+LastDay || I <- NegDays] ++ PosDays, + case [I || I <- Days, I =< LastDay, I > 0] of + [] -> next_month_days(Y, M, PosDays, NegDays); + L -> {Y, M, lists:min(L)} + end; +month_days(Y, M, PosDays, [], true) -> + LastDay = calendar:last_day_of_the_month(Y, M), + {Y, M, [I || I <- lists:sort(PosDays), I =< LastDay]}; +month_days(Y, M, PosDays, NegDays, true) -> + LastDay = calendar:last_day_of_the_month(Y, M), + AllDays = PosDays ++ [I+LastDay || I <- NegDays], + UniqDays= lists:sort(sets:to_list(sets:from_list(AllDays))), + check_days(Y, M, UniqDays), + {Y, M, [I || I <- UniqDays, I =< LastDay, I > 0]}. + +check_days(Y,M,Days) -> + lists:foreach(fun(I) -> + Date = {Y,M,I}, + calendar:valid_date(Date) orelse throw({invalid_date, Date}) + end, lists:takewhile(fun(I) -> I > 28 end, lists:reverse(Days))). + +%% @doc Calculates the duration in milliseconds until the next time +%% a job is to be run. +-spec until_next_time(erlcron:milliseconds(), erlcron:run_when()) -> erlcron:milliseconds(). +until_next_time(NowEpochTime, Sched) when is_integer(NowEpochTime), is_tuple(Sched) -> + DateTime = erlang:posixtime_to_universaltime(to_ceiling_seconds(NowEpochTime)), + NormSched = normalize(Sched, DateTime), + State = set_internal_time(#state{job={NormSched, undefined}}, + DateTime, NowEpochTime), + {Res, _State1} = until_next_time(State), + Res. + +%% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. --spec until_next_time(state(), {erlcron:run_when(), term()}) -> - erlcron:seconds(). -until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> - Seconds; -until_next_time(State, {{once, {H, M, S}}, _What}) - when is_integer(H), is_integer(M), is_integer(S) -> - normalize_seconds(State, S + (M + (H * 60)) * 60); -until_next_time(State, {{once, Period}, _What}) -> - normalize_seconds(State, resolve_time(Period)); -until_next_time(State, {{daily, Period}, _What}) -> - until_next_daytime(State, Period); -until_next_time(State, {{weekly, DoW, Period}, _What}) -> - OnDay = resolve_dow(DoW), +%% @private +-spec until_next_time(state()) -> {erlcron:milliseconds(), state()}. +until_next_time(State = #state{job={Sched, _Task}}) -> + until_next_time2(State, Sched). + +until_next_time2(State, {once, {relative, Msec}}) when is_integer(Msec) -> + {Msec, State}; +until_next_time2(State, {once, {absolute, Msec}}) when is_integer(Msec) -> + {normalize_to_relative(State, Msec), State}; +until_next_time2(State, {daily, Period}) -> + {until_next_daytime(State, Period, current_time(State)), State}; +until_next_time2(State, {weekly, DoW, Period}) -> {Date, _} = current_date(State), - Today = calendar:day_of_the_week(Date), - case Today of - OnDay -> - until_next_daytime_or_days_from_now(State, Period, 7); - Today when Today < OnDay -> - until_days_from_now(State, Period, OnDay - Today); - Today when Today > OnDay -> - until_days_from_now(State, Period, (OnDay+7) - Today) - end; -until_next_time(State, {{monthly, DoM, Period}, _What}) -> - {{ThisYear, ThisMonth, Today}, _} = current_date(State), - {NextYear, NextMonth} = - case ThisMonth of - 12 -> - {ThisYear + 1, 1}; - _ -> - {ThisYear, ThisMonth + 1} + Today = calendar:day_of_the_week(Date), + Days = find_dow(Today, DoW), + NextDays = fun() -> + I = Today+1, + N = if I>7 -> 1; true -> I end, + find_dow(N, DoW) + end, + {until_next_time_from_now(State, Period, Days, NextDays), State}; +until_next_time2(State, {monthly, When, Period}) -> + {{ThisYear, ThisMonth, Today}=YMD, _} = current_date(State), + {{{ThisMonthDays, NextY, NextM, NextMonthFirstDOM}, _}, State1} = + update_dom(ThisYear, ThisMonth, When, State), + + {YMD1, YMD2} = + case lists:dropwhile(fun(I) -> I < Today end, ThisMonthDays) of + [DOM1, DOM2 | _] -> + {{ThisYear,ThisMonth,DOM1}, {ThisYear,ThisMonth,DOM2}}; + [DOM|_] -> + {{ThisYear,ThisMonth,DOM}, {NextY,NextM,NextMonthFirstDOM}}; + [] -> + {{NextY, NextM, NextMonthFirstDOM}, {0,0,0}} end, - D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), - D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), - Days = D2 - D1, - case Today of - DoM -> - until_next_daytime_or_days_from_now(State, Period, Days); + + TodayGreg = to_greg_days(YMD), + NextGreg = to_greg_days(YMD1), + Days = NextGreg - TodayGreg, + NextDays = fun() -> to_greg_days(YMD2) - TodayGreg end, + {until_next_time_from_now(State1, Period, Days, NextDays), State1}. + +until_next_time_from_now(State, Period, 0, NextDays) when is_function(NextDays, 0) -> + CurrentTime = current_time(State), + F = fun() -> until_days_from_now(State, Period, NextDays()-1) end, + case last_time(Period) of + T when CurrentTime > T -> + F(); _ -> - until_days_from_now(State, Period, Days) - end. + EndTime = last_time(Period), + case next_time(Period, CurrentTime) of + I when I > EndTime -> + F(); + I -> + I - CurrentTime + end + end; +until_next_time_from_now(State, Period, Days, _NextDays) when Days > 0 -> + until_days_from_now(State, Period, Days-1). + +to_greg_days({Y,M,D}) -> + calendar:date_to_gregorian_days(Y,M,D). -%% @doc Calculates the duration in seconds until the next time this +%% @doc Calculates the time since midnight in milliseconds until the next time this %% period is to occur during the day. --spec until_next_daytime(state(), erlcron:period()) -> erlcron:seconds(). -until_next_daytime(State, Period) -> +-spec until_next_daytime(state(), normalized_period(), erlcron:milliseconds()) -> + erlcron:milliseconds(). +until_next_daytime(State, Period, MsecsFromMidnight) -> StartTime = first_time(Period), - EndTime = last_time(Period), - case current_time(State) of - T when T > EndTime -> - until_tomorrow(State, StartTime); - T -> - next_time(Period, T) - T + EndTime = last_time(Period), + if MsecsFromMidnight > EndTime -> + until_tomorrow(State, StartTime); + true -> + case next_time(Period, MsecsFromMidnight) of + T when T > EndTime -> + until_tomorrow(State, StartTime); + T -> + T - MsecsFromMidnight + end end. -%% @doc Calculates the last time in a given period. --spec last_time(erlcron:period()) -> erlcron:seconds(). -last_time(Period) -> - hd(lists:reverse(lists:sort(resolve_period(Period)))). +%% @doc Calculates the duration in seconds until the given time occurs +%% tomorrow. +-spec until_tomorrow(state(), erlcron:milliseconds()) -> erlcron:milliseconds(). +until_tomorrow(State, StartTime) -> + StartTime + 24*3600000 - current_time(State). +%% @doc Calculates the duration in milliseconds until the given period +%% occurs several days from now. +-spec until_days_from_now(state(), normalized_period(), integer()) -> + erlcron:milliseconds(). +until_days_from_now(State, Period, Days) -> + MsecsUntilTomorrow = until_tomorrow(State, 0), + MsecsUntilTomorrow + Days * 24 * 3600000 + until_next_daytime(State, Period, 0). %% @doc Calculates the first time in a given period. --spec first_time(erlcron:period()) -> erlcron:seconds(). -first_time(Period) -> - hd(lists:sort(resolve_period(Period))). +-spec first_time(normalized_period()) -> erlcron:milliseconds(). +first_time([]) -> + ?SEC_IN_A_DAY; +first_time([{FromTime, _ToTime, _RepeatSec}|_]) -> + FromTime. + +%% @doc Calculates the last time in a given period. +-spec last_time(normalized_period()) -> erlcron:milliseconds(). +last_time([]) -> + ?SEC_IN_A_DAY; +last_time(Period) when is_list(Period) -> + F = fun({FromTime, _ToTime, 0}) -> + FromTime; + ({FromTime, ToTime, RepeatSec}) -> + FromTime + ((ToTime-FromTime) div RepeatSec) * RepeatSec + end, + lists:max([F(R) || R <- Period]). %% @doc Calculates the first time in the given period after the given time. --spec next_time(erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). -next_time(Period, Time) -> - R = lists:sort(resolve_period(Period)), - lists:foldl(fun(X, A) -> - case X of - T when T >= Time, T < A -> - T; - _ -> - A - end - end, 24*3600, R). +-spec next_time(normalized_period(), erlcron:milliseconds()) -> erlcron:milliseconds(). +next_time([], _Time) -> + ?SEC_IN_A_DAY; +next_time(Period, Time) when is_list(Period), is_integer(Time) -> + F = fun({FromTime, _ToTime, _RepeatSec}) when Time =< FromTime -> + FromTime; + ({_FromTime, _ToTime, 0}) -> + ?SEC_IN_A_DAY; + ({FromTime, _ToTime, RepeatSec}) -> + A1 = ((Time-FromTime) div RepeatSec) * RepeatSec, + A = if A1 < Time -> A1 + RepeatSec; true -> A1 end, + FromTime + A + end, + case [F(R) || R = {_, ToTm, _} <- Period, Time =< ToTm] of + [] -> ?SEC_IN_A_DAY; + LL -> lists:min(LL) + end. + +%% @doc Returns the current time, in milliseconds past midnight in local time zone. +-spec current_time(state()) -> erlcron:milliseconds(). +current_time(State = #state{last_time=Now}) -> + % Take ceiling of time to the next second + Msec = case (Now div 1000) * 1000 of + Now -> 0; + N -> Now-N + end, + {_, {H,M,S}} = current_date(State), + to_milliseconds(S + M * 60 + H * 3600) + Msec. + +%% @doc Returns current date in local time +current_date(#state{last_time=Now, ref_epoch=E, epoch_at_ref=S}) when is_integer(Now), Now > 0 -> + Elapsed = Now - S, + to_local_datetime(Elapsed + E). + +current_epoch(EpochMsec, #state{ref_epoch=RefEpoch, epoch_at_ref=Epoch}) -> + Elapsed = EpochMsec - Epoch, + Elapsed + RefEpoch. + +normalize_to_relative(State, Milliseconds) -> + NowSec = current_time(State), + Milliseconds - NowSec. %% @doc Returns a list of times given a periodic specification. --spec resolve_period([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. +-spec resolve_period([erlcron:period()] | erlcron:period()) -> + [{erlcron:milliseconds(), erlcron:milliseconds(), erlcron:milliseconds()}]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); -resolve_period({every, Duration, {between, TimeA, TimeB}}) -> - Period = resolve_dur(Duration), +resolve_period({every, Duration}) -> + resolve_period({every, Duration, {between, {0,0,0}, {23,59,59}}}); +resolve_period({every, Duration, {between, TimeA, TimeB}} = P) -> + Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), - EndTime = resolve_time(TimeB), - resolve_period0(Period, StartTime, EndTime, []); + EndTime = resolve_time(TimeB), + StartTime =< EndTime orelse throw({invalid_period, P}), + [{StartTime, EndTime, Period}]; resolve_period(Time) -> - [resolve_time(Time)]. - -resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> - Acc; -resolve_period0(Period, Time, EndTime, Acc) -> - resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). + T = resolve_time(Time), + [{T, T, 0}]. %% @doc Returns seconds past midnight for a given time. --spec resolve_time(erlcron:cron_time()) -> erlcron:seconds(). +-spec resolve_time(erlcron:cron_time()) -> erlcron:milliseconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> - S + M * 60 + H * 3600; + to_milliseconds(S + M * 60 + H * 3600); resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> - resolve_time({H, X}) + M * 60 + S; + resolve_time({H, X}) + to_milliseconds(M*60 + S); resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> - resolve_time({H, X}) + M * 60; + resolve_time({H, X}) + to_milliseconds(M*60); resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> - H * 3600; + to_milliseconds(H * 3600); resolve_time({12, pm}) -> - 12 * 3600; -resolve_time({H, pm}) when H < 12-> - (H + 12) * 3600. + to_milliseconds(12 * 3600); +resolve_time({H, pm}) when H < 12 -> + to_milliseconds((H + 12) * 3600); +resolve_time(Other) -> + throw({invalid_time, Other}). %% @doc Returns seconds for a given duration. --spec resolve_dur(erlcron:duration()) -> erlcron:seconds(). -resolve_dur({Hour, hr}) -> - Hour * 3600; -resolve_dur({Min, min}) -> - Min * 60; -resolve_dur({Sec, sec}) -> - Sec. +-spec resolve_dur(erlcron:duration()) -> erlcron:milliseconds(). +resolve_dur({Hour, H}) when H==h; H==hr -> to_milliseconds(Hour * 3600); +resolve_dur({Min, M}) when M==m; M==min -> to_milliseconds(Min * 60); +resolve_dur({Sec, S}) when S==s; S==sec -> to_milliseconds(Sec); +resolve_dur(Other) -> throw({invalid_duration, Other}). %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. --spec resolve_dow(erlcron:dow()) -> integer(). -resolve_dow(mon) -> - 1; -resolve_dow(tue) -> - 2; -resolve_dow(wed) -> - 3; -resolve_dow(thu) -> - 4; -resolve_dow(fri) -> - 5; -resolve_dow(sat) -> - 6; -resolve_dow(sun) -> - 7. +-spec resolve_dow(erlcron:dow()) -> [integer()]. +resolve_dow(I) when is_atom(I) -> + [resolve_dow2(I)]; +resolve_dow([I]) -> + [resolve_dow2(I)]; +resolve_dow(L) when is_list(L) -> + lists:sort([resolve_dow2(I) || I <- L]). + +resolve_dow2(mon) -> 1; +resolve_dow2(tue) -> 2; +resolve_dow2(wed) -> 3; +resolve_dow2(thu) -> 4; +resolve_dow2(fri) -> 5; +resolve_dow2(sat) -> 6; +resolve_dow2(sun) -> 7. + +-spec find_dow(integer(), [integer()]) -> integer(). +find_dow(_TodayDOW, []) -> + throw(invalid_dow_period); +find_dow(TodayDOW, [FirstDOW|_]=DOWs) -> + find_dow(TodayDOW, DOWs, FirstDOW). + +find_dow(TodayDOW, [TodayDOW|_], _) -> + 0; +find_dow(TodayDOW, [DOW|_], _FirstDOW) when TodayDOW < DOW -> + DOW-TodayDOW; +find_dow(TodayDOW, [DOW|T], FirstDOW) when TodayDOW > DOW -> + find_dow(TodayDOW, T, FirstDOW); +find_dow(TodayDOW, [], FirstDOW) -> + FirstDOW+7 - TodayDOW. + +set_internal_time(State, RefDate, CurEpochMsec) -> + EpochS = to_seconds(CurEpochMsec), + FloorE = to_milliseconds(EpochS), + Msec = to_milliseconds(erlang:universaltime_to_posixtime(RefDate)), + State1 = State#state{ref_epoch=Msec, epoch_at_ref=FloorE}, + %Now = Msec + CurEpochMsec - FloorE, + State1#state{last_time=CurEpochMsec}. + +%% @doc NewDate is in universal time. +fast_forward(#state{ref_epoch=OldRefEpoch, next_run=NextRun}=S, NewRefEpoch, NewDate, Count) -> + {Msec, State1} = until_next_time(S#state{last_time=OldRefEpoch, epoch_at_ref=OldRefEpoch}), + Span = NewRefEpoch - OldRefEpoch, + if Span =< Msec; Msec =:= 0 -> + true; + true -> + RefMsec = OldRefEpoch + Msec, + State2 = State1#state{ref_epoch = RefMsec+1, last_run=NextRun, next_run=RefMsec}, + do_job_run(State2), + case State2#state.job of + {{once, _}, _} when Count =:= 1 -> + Msec =< 0 andalso + ?LOG_WARNING([{info, "One-time job executed immediately due to negative time shift"}, + {time_shift_secs, to_seconds(Msec)}, + {job_ref, State2#state.alarm_ref}, + {job_when, State2#state.orig_when}]), + false; + _ -> + fast_forward(State2, NewRefEpoch, NewDate, Count+1) + end + end. -%% @doc Calculates the duration in seconds until the given time occurs -%% tomorrow. --spec until_tomorrow(state(), erlcron:seconds()) -> erlcron:seconds(). -until_tomorrow(State, StartTime) -> - (StartTime + 24*3600) - current_time(State). +to_local_datetime(Milliseconds) when is_integer(Milliseconds) -> + DT = to_universal_datetime(Milliseconds), + erlang:universaltime_to_localtime(DT). -%% @doc Calculates the duration in seconds until the given period -%% occurs several days from now. --spec until_days_from_now(state(), erlcron:period(), integer()) -> - erlcron:seconds(). -until_days_from_now(State, Period, Days) -> - Days * 24 * 3600 + until_next_daytime(State, Period). +to_universal_datetime(Milliseconds) -> + erlang:posixtime_to_universaltime(to_seconds(Milliseconds)). -%% @doc Calculates the duration in seconds until the given period -%% occurs, which may be today or several days from now. --spec until_next_daytime_or_days_from_now(state(), erlcron:period(), integer()) -> - erlcron:seconds(). -until_next_daytime_or_days_from_now(State, Period, Days) -> - CurrentTime = current_time(State), - case last_time(Period) of - T when T < CurrentTime -> - until_days_from_now(State, Period, Days-1); - _ -> - until_next_daytime(State, Period) - end. +to_milliseconds(Secs) -> + Secs * 1000. -set_internal_time(State, RefDate, CurrentSeconds) -> - NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), - State#state{referenced_seconds=NewSeconds, - seconds_at_reference=CurrentSeconds}. - -ceiling(X) -> - T = erlang:trunc(X), - case (X - T) of - Neg when Neg < 0 -> T; - Pos when Pos > 0 -> T + 1; - _ -> T - end. +to_seconds(MilliSec) -> + MilliSec div 1000. -fast_forward(State, NewDate) -> - try - Seconds = until_next_time(State, State#state.job), - NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), - Span = NewSeconds - State#state.referenced_seconds, - case Span > Seconds of - true -> - RefSecs = State#state.referenced_seconds, - NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, - do_job_run(State, State#state.job), - fast_forward(NewState, NewDate); - false -> - ok - end - catch - throw:invalid_once_exception -> - {error, invalid_once_exception} +to_ceiling_seconds(Msec) -> + S = to_seconds(Msec), + case to_milliseconds(S) of + Msec -> S; + _ -> S+1 end. + +%%%=================================================================== +%%% Tests +%%%=================================================================== + +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). +-endif. + +-ifdef(EUNIT). + +dow_test() -> + DOWs = resolve_dow([tue,wed,thu]), + ?assertEqual([7], resolve_dow(sun)), + ?assertEqual([7], resolve_dow([sun])), + ?assertEqual([1,2], resolve_dow([mon,tue])), + ?assertEqual([2,3,4], DOWs), + ?assertEqual(1, find_dow(1, DOWs)), + ?assertEqual(0, find_dow(2, DOWs)), + ?assertEqual(0, find_dow(3, DOWs)), + ?assertEqual(0, find_dow(4, DOWs)), + ?assertEqual(4, find_dow(5, DOWs)), + DOWs1 = resolve_dow([thu,sat]), + ?assertEqual([4,6], DOWs1), + ?assertEqual(3, find_dow(1, DOWs1)), + ?assertEqual(2, find_dow(2, DOWs1)), + ?assertEqual(1, find_dow(3, DOWs1)), + ?assertEqual(0, find_dow(4, DOWs1)), + ?assertEqual(1, find_dow(5, DOWs1)), + ?assertEqual(0, find_dow(6, DOWs1)), + ?assertEqual(4, find_dow(7, DOWs1)), + ok. + +normalize_test() -> + Date = {date(), {0,0,0}}, + ?assertEqual({once,{relative,1000}}, normalize({once, 1}, Date)), + ?assertEqual({once,{absolute,43200000}}, normalize({once, {12,pm}}, Date)), + ?assertThrow({time_given_in_the_past,{2,3,4}}, normalize({once, {2,3,4}}, {date(), {2,3,5}})), + ?assertEqual({once,{absolute,7384000}}, normalize({once, {2,3,4}}, Date)), + ?assertEqual({daily,[{50400000,50400000,0}]}, normalize({daily, {2,pm}}, Date)), + ?assertEqual({daily,[{0,86399000,20000}]}, normalize({daily, {every, {20,s}}}, Date)), + ?assertEqual({daily,[{3600000,3600000,0},{7200000,7200000,0}]}, + normalize({daily, [{2,am},{1,am}]}, Date)), + ?assertEqual({daily,[{0,86399000,5000},{0,86399000,20000}]}, + normalize({daily, [{every, {5,s}}, {every, {20,s}}]}, Date)), + ?assertEqual({daily,[{3600000,7200000,20000}]}, + normalize({daily, {every, {20,s}, {between, {1,am}, {2,am}}}}, Date)), + ?assertEqual({weekly,[1], [{3600000,3600000,0}]}, normalize({weekly, mon, {1,am}}, Date)), + ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [mon,wed], {1,am}}, Date)), + ?assertEqual({weekly,[1,3],[{3600000,3600000,0}]}, normalize({weekly, [wed,mon], {1,am}}, Date)), + ?assertEqual({monthly,{{[31],2019,2,28},{2019,1, [],[0]}},[{3600000,3600000,0}]}, normalize({monthly, 0, {1,am}}, {{2019,1,1},{0,0,0}})), + ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[],[0]}},[{3600000,3600000,0}]}, normalize({monthly, [0], {1,am}}, {{2019,12,1},{0,0,0}})), + ?assertEqual({monthly,{{[], 2019,3,31},{2019,2,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly,[31], {1,am}}, {{2019,2,1},{0,0,0}})), + ?assertEqual({monthly,{{[1, 31],2020,1,1}, {2019,12,[1],[0]}},[{3600000,3600000,0}]},normalize({monthly,[1,0],{1,am}},{{2019,12,1},{0,0,0}})), + ?assertEqual({monthly,{{[30,31],2020,1,30},{2019,12,[30,31],[]}},[{3600000,3600000,0}]},normalize({monthly,[30,31],{1,am}},{{2019,12,1},{0,0,0}})), + ?assertEqual({monthly,{{[31],2019,3,31},{2019,1,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly, 31, {1,am}}, {{2019,1,1},{0,0,0}})), + ?assertEqual({monthly,{{[29],2024,2,29},{2024,1,[29],[]}},[{3600000,3600000,0}]}, normalize({monthly, 29, {1,am}}, {{2024,1,1},{0,0,0}})), + ?assertEqual({monthly,{{[31],2020,1,31},{2019,12,[31],[]}},[{3600000,3600000,0}]}, normalize({monthly, 31, {1,am}}, {{2019,12,1},{0,0,0}})), + ?assertEqual({monthly,{{[1], 2019,2,1}, {2019,1,[1],[-30]}},[{3600000,3600000,0}]}, normalize({monthly,[1,-30],{1,am}},{{2019,1,1},{0,0,0}})), + ?assertEqual({monthly,{{[1], 2019,3,1}, {2019,1,[],[-30]}}, [{3600000,3600000,0}]}, normalize({monthly,-30,{1,am}}, {{2019,1,1},{0,0,0}})), + ?assertEqual({monthly,{{[30],2019,2,27},{2019,1,[],[-1]}}, [{0,86399000,20000}]}, normalize({monthly, -1, {every, {20,s}}}, {{2019,1,1},{0,0,0}})), + ?assertEqual({monthly,{{[28],2019,2,25},{2019,1,[],[-3]}}, [{0,0,0},{3600000,3600000,0}]}, + normalize({monthly, -3, [{12,am}, {1,am}]}, {{2019,1,1},{0,0,0}})), + ok. + +until_next_time_month_test() -> + T = ecrn_util:localtime_to_epoch({{2019,1,1},{0,0,0}}), + Test = fun(Epoch, Days, When) -> + I = ecrn_agent:until_next_time(Epoch, {monthly, Days, When}), + ecrn_util:epoch_to_datetime_string(Epoch+I) + end, + ?assertEqual("2019-01-31 01:00:00.000", Test(T, [0], {every, {20,s}, {between, {1,am}, {2,am}}})), + ?assertEqual("2019-01-10 01:00:00.000", Test(T, [0,10], {every, {20,s}, {between, {1,am}, {2,am}}})), + ?assertEqual("2019-01-03 00:00:00.000", Test(T, 3, {every, {20,s}})), + ok. + +-endif. diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index b163d6a..f90e7c5 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,61 +1,61 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> - application:start(crypto), + %application:start(crypto), application:start(eunit), - application:start(sasl), + %application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> setup(), {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. setup() -> case application:get_env(erlcron, crontab) of {ok, Crontab} -> lists:foreach(fun(CronJob) -> erlcron:cron(CronJob) end, Crontab); undefined -> ok end. diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 4ebd79e..8ccb1a6 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,116 +1,146 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, + datetime/1, set_datetime/1, + set_datetime/2, + reset_datetime/0, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). --record(state, {reference_datetime :: calendar:datetime(), - datetime_at_reference :: erlcron:seconds()}). +-record(state, {ref_time :: calendar:datetime(), + epoch_at_ref :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). --spec cancel(erlcron:job_ref()) -> ok | undefined. +-spec cancel(erlcron:job_ref()) -> boolean(). cancel(AlarmRef) -> - gen_server:call(?SERVER, {cancel, AlarmRef}). + ecrn_reg:cancel(AlarmRef). --spec datetime() -> {calendar:datetime(), erlcron:seconds()}. +%% @doc Returns universal time. +-spec datetime() -> {calendar:datetime(), erlcron:milliseconds()}. datetime() -> gen_server:call(?SERVER, get_datetime). +-spec datetime(local|universal) -> {calendar:datetime(), erlcron:milliseconds()}. +datetime(universal) -> + datetime(); +datetime(local) -> + {DT, Epoch} = datetime(), + {calendar:universal_time_to_local_time(DT), Epoch}. + %% @doc sets the date-time for the erlcron --spec set_datetime(calendar:datetime()) -> ok. -set_datetime(DateTime={_,_}) -> +-spec set_datetime(calendar:datetime()) -> ok | {error, term()}. +set_datetime(DateTime) -> + set_datetime(DateTime, local). + +-spec set_datetime(calendar:datetime(), local|universal) -> ok | {error, term()}. +set_datetime(DT={_,_}, local) -> + gen_server:call(?SERVER, {set_datetime, erlang:localtime_to_universaltime(DT)}, infinity); +set_datetime(DateTime={_,_}, universal) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). +%% @doc Reset reference datetime to current epoch datetime +-spec reset_datetime() -> ok | {error, term()}. +reset_datetime() -> + gen_server:call(?SERVER, reset_datetime, infinity). + %% @doc sets the date-time with the erlcron on all nodes --spec multi_set_datetime([node()], calendar:datetime()) -> ok. +-spec multi_set_datetime([node()], calendar:datetime()) -> ok | {error, term()}. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> - DateTime = erlang:localtime(), - {ok, #state{reference_datetime=DateTime, - datetime_at_reference=ecrn_util:epoch_seconds()}}. + DateTime = erlang:universaltime(), + {ok, #state{ref_time=DateTime, + epoch_at_ref=ecrn_util:epoch_milliseconds()}}. %% @private -handle_call({cancel, AlarmRef}, _From, State) -> - {reply, internal_cancel(AlarmRef), State}; -handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, - datetime_at_reference = Actual}) -> +handle_call(get_datetime, _From, State = #state{ref_time = DateTime, + epoch_at_ref = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> - NewState = State#state{reference_datetime=DateTime, - datetime_at_reference=ecrn_util:epoch_seconds()}, - case lists:foldl(fun({_, [Pid]}, Acc) -> - - ecrn_agent:set_datetime(Pid, DateTime, - NewState#state.datetime_at_reference), - Acc; - ({Ref, X}, Acc) when is_list(X) -> - [Ref | Acc] - end, - [], - ecrn_reg:get_all()) of - [] -> - {reply, ok, NewState}; - ErrorRefs -> - {reply, {error, ErrorRefs}, NewState} - end. + NewState = State#state{ref_time=DateTime, + epoch_at_ref=ecrn_util:epoch_milliseconds()}, + {reply, call_all(NewState), NewState}; + +handle_call(reset_datetime, _From, State) -> + Now = ecrn_util:epoch_milliseconds(), + DateTime = erlang:posixtime_to_universaltime(to_seconds(Now)), + NewState = State#state{ref_time=DateTime, epoch_at_ref=Now}, + {reply, call_all(NewState), NewState}. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== -internal_cancel(AlarmRef) -> - case ecrn_reg:get(AlarmRef) of - undefined -> - undefined; - {ok, [Pid]} -> - ecrn_agent:cancel(Pid) +%notify_all(#state{ref_time=DateTime, epoch_at_ref=Now}=State) -> +% [ecrn_agent:set_datetime(P, DateTime, Now, universal) || P <- ecrn_reg:get_all_pids()], +% State. + +call_all(#state{ref_time=DateTime, epoch_at_ref=Now}) -> + Res = lists:foldl(fun(P, A) -> + case ecrn_agent:set_datetime(P, DateTime, Now, universal) of + ok -> + A; + {error, Err} -> + Ref = try + ecrn_reg:get_refs(P) + catch _:_ -> + [] + end, + [{Ref, P, Err} | A] + end + end, [], ecrn_reg:get_all_pids()), + case Res of + [] -> ok; + _ -> {error, {failed_to_set_time, Res}} end. + +to_seconds(MilliSec) -> + MilliSec div 1000. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index ba29d29..bab769b 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,56 +1,77 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, - add_job/2]). + add_job/2, + all_jobs/0, + terminate/1]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc -%% Add a chron job to be supervised +%% Add a chron job to be supervised -spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). -add_job(JobRef, Task) -> - {ok, _} = supervisor:start_child(?SERVER, [JobRef, Task]), - JobRef. +add_job(JobRef, Job = {_, Task}) when is_function(Task, 2) + ; is_function(Task, 0) + ; is_tuple(Task), tuple_size(Task)==3 + , is_atom(element(1,Task)) + , is_atom(element(2,Task)) + , is_list(element(3,Task)) -> + case supervisor:start_child(?SERVER, [JobRef, Job]) of + {ok, _} -> JobRef; + {error, {already_started, _}} -> {error, already_started}; + Other -> Other + end. + +%% @doc +%% Get a list of all active jobs +-spec all_jobs() -> [pid()]. +all_jobs() -> + [P || {_,P,_,_} <- supervisor:which_children(?SERVER)]. + +%% @doc +%% Terminate a job +terminate(Pid) when is_pid(Pid) -> + supervisor:terminate_child(?SERVER, Pid). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> - RestartStrategy = simple_one_for_one, - MaxRestarts = 1000, - MaxSecondsBetweenRestarts = 3600, - - SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, - - Restart = transient, - Shutdown = 2000, - Type = worker, + SupFlags = #{ + strategy => simple_one_for_one, + intensity => application:get_env(erlcron, sup_job_intensity, 3), + period => application:get_env(erlcron, sup_job_period, 10) + }, - AChild = {ecrn_agent, {ecrn_agent, start_link, []}, - Restart, Shutdown, Type, [ecrn_agent]}, + AChild = #{id => ecrn_agent, + start => {ecrn_agent, start_link, []}, + restart => transient, + shutdown => brutal_kill, + type => worker, + modules => [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. diff --git a/src/ecrn_reg.erl b/src/ecrn_reg.erl index 299e9d1..3d1739e 100644 --- a/src/ecrn_reg.erl +++ b/src/ecrn_reg.erl @@ -1,168 +1,248 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% This provides simple pid registration for the server. -module(ecrn_reg). -behaviour(gen_server). %% API -export([start_link/0, register/2, unregister/1, get/1, + get_refs/1, + cancel/1, stop/0, - get_all/0]). + get_all/0, + get_all_pids/0, + get_all_refs/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). --include_lib("eunit/include/eunit.hrl"). - -define(SERVER, ?MODULE). --record(state, {registered}). +-record(state, {pid2ref, ref2pid}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link() -> {ok, Pid::pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %% @doc %% Register an arbitrary value with the system, under a set of keys --spec register(term() | [term()], term()) -> ok | {discarded_keys, [term()]}. -register(Keys, Body) when is_list(Keys) -> - gen_server:call(?SERVER, {register, Keys, Body}); -register(Key, Body) -> - gen_server:call(?SERVER, {register, [Key], Body}). +-spec register(erlcron:job_ref(), term()) -> boolean(). +register(Key, Pid) when (is_atom(Key) orelse is_reference(Key)), is_pid(Pid) -> + gen_server:call(?SERVER, {register, Key, Pid}). %% @doc %% Remove the value registered under a que or set of keys --spec unregister(term() | [term()]) -> ok. -unregister(Keys) when is_list(Keys) -> - gen_server:call(?SERVER, {unregister, Keys}); -unregister(Key) -> - gen_server:call(?SERVER, {unregister, [Key]}). +-spec unregister(erlcron:job_ref()) -> ok. +unregister(Key) when is_atom(Key); is_reference(Key) -> + gen_server:cast(?SERVER, {unregister, Key}). %% @doc -%% Get a value buy key. --spec get(term()) -> {ok, term()} | undefined. -get(Key) -> +%% Get a pid by reference key. +-spec get(erlcron:job_ref()) -> pid() | undefined. +get(Key) when is_atom(Key); is_reference(Key) -> gen_server:call(?SERVER, {get, Key}). +%% @doc +%% Get job refs associated with the pid +-spec get_refs(pid()) -> [erlcron:job_ref()]. +get_refs(Pid) when is_pid(Pid) -> + lists:sort(gen_server:call(?SERVER, {get_refs, Pid})). + +%% @doc +%% Cancel all jobs assigned to the given key +-spec cancel(term()) -> boolean(). +cancel(Key) when is_atom(Key); is_reference(Key) -> + gen_server:call(?SERVER, {cancel, Key}). + %% @doc %% Get all the values. -spec get_all() -> [{term(), term()}]. get_all() -> gen_server:call(?SERVER, get_all). +%% @doc +%% Get all registered Pids. +-spec get_all_pids() -> [pid()]. +get_all_pids() -> + gen_server:call(?SERVER, get_all_pids). + +%% @doc +%% Get all registered job references. +-spec get_all_refs() -> [erlcron:job_ref()]. +get_all_refs() -> + gen_server:call(?SERVER, get_all_refs). + %% @doc %% stop this server -spec stop() -> ok. stop() -> gen_server:call(?SERVER, stop). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> - {ok, #state{registered=dict:new()}}. + {ok, #state{pid2ref=#{}, ref2pid=#{}}}. %% @private -handle_call({register, Keys, Body}, _From, #state{registered=Dict}) -> - {Result, Dict2} = add_for_keys(Keys, Body, Dict, ok), - {reply, Result, #state{registered=Dict2}}; -handle_call({unregister, Keys}, _From, #state{registered=Dict}) -> - Dict2 = remove_for_keys(Keys, Dict), - {reply, ok, #state{registered=Dict2}}; -handle_call({get, Key}, _From, State = #state{registered=Dict}) -> - Value = get_for_key(Key, Dict), - {reply, Value, State}; +handle_call({register, Ref, Pid}, _From, #state{pid2ref=M1, ref2pid=M2}=State) -> + Ref1 = monitor(process, Pid), + case maps:find(Pid, M1) of + {ok, Refs} when is_list(Refs) -> + demonitor(Ref1, [flush]), + case lists:member(Ref, Refs) of + true -> + {reply, false, State}; + false -> + {reply, true, State#state{ref2pid=M2#{Ref=>Pid}, pid2ref=M1#{Pid=>[Ref|Refs]}}} + end; + error -> + {reply, true, State#state{ref2pid=M2#{Ref=>Pid}, pid2ref=M1#{Pid=>[Ref]}}} + end; +handle_call({get, Key}, _From, State) -> + case get_for_key(Key, State) of + {ok, V} -> {reply, V, State}; + undefined -> {reply, undefined, State} + end; +handle_call({get_refs, Pid}, _From, State) -> + case get_for_key(Pid, State) of + {ok, V} -> {reply, V, State}; + undefined -> {reply, [], State} + end; +handle_call({cancel, Pid}, _From, State) -> + {Found, State1} = find_and_remove(Pid, State, fun(P) -> ecrn_agent:cancel(P) end), + {reply, Found, State1}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; -handle_call(get_all, _From, State = #state{registered=Dict}) -> - {reply, dict:to_list(Dict), State}. +handle_call(get_all, _From, State = #state{ref2pid=Map}) -> + {reply, maps:to_list(Map), State}; +handle_call(get_all_refs, _From, State = #state{ref2pid=Map}) -> + {reply, maps:keys(Map), State}; +handle_call(get_all_pids, _From, State = #state{pid2ref=Map}) -> + {reply, maps:keys(Map), State}. %% @private +handle_cast({unregister, Key}, State) -> + {_, NewState} = find_and_remove(Key, State, undefined), + {noreply, NewState}; handle_cast(_Msg, State) -> {noreply, State}. %% @private +handle_info({'DOWN', _Ref, process, Pid, _Info}, State) -> + handle_cast({unregister, Pid}, State); handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== -discarded_keys(Key, {discarded_keys, Keys}) -> - {discarded_keys, [Key | Keys]}; -discarded_keys(Key, ok) -> - {discarded_keys, [Key]}. - -add_for_keys([Key | Rest], Body, Dict, Result) -> - case dict:find(Key, Dict) of - error -> - add_for_keys(Rest, Body, dict:append(Key, Body, Dict), Result); - _Value -> - add_for_keys(Rest, Body, dict:append(Key, Body, Dict), - discarded_keys(Key, Result)) +get_for_key(Ref, #state{ref2pid=Map}) when is_reference(Ref); is_atom(Ref) -> + case maps:find(Ref, Map) of + error -> undefined; + OkValue -> OkValue end; -add_for_keys([], _, Dict, Result) -> - {Result, Dict}. +get_for_key(Pid, #state{pid2ref=Map}) when is_pid(Pid) -> + case maps:find(Pid, Map) of + error -> undefined; + OkValue -> OkValue + end. -remove_for_keys([Key | Rest], Dict) -> - remove_for_keys(Rest, dict:erase(Key, Dict)); -remove_for_keys([],Dict) -> - Dict. +-spec find_and_remove(reference()|atom()|pid(), #state{}, undefined|fun((pid())->ok)) -> + {boolean(), #state{}}. +find_and_remove(Ref, S = #state{ref2pid=M1}, Fun) when is_reference(Ref); is_atom(Ref) -> + case maps:find(Ref, M1) of + {ok, Pid} -> + is_function(Fun, 1) andalso Fun(Pid), + {true, find_and_remove2(Pid, Ref, S)}; + error -> + {false, S} + end; +find_and_remove(Pid, State = #state{ref2pid=M1, pid2ref=M2}, Fun) when is_pid(Pid) -> + case maps:find(Pid, M2) of + {ok, Refs} -> + is_function(Fun, 1) andalso Fun(Pid), + NewM1 = lists:foldl(fun(R, M) -> maps:remove(R, M) end, M1, Refs), + {true, State#state{ref2pid=NewM1, pid2ref=maps:remove(Pid,M2)}}; + error -> + {false, State} + end. -get_for_key(Key, Dict) -> - case dict:find(Key, Dict) of +find_and_remove2(Pid, Ref, S = #state{ref2pid=M1, pid2ref=M2}) when is_pid(Pid) -> + case maps:find(Pid, M2) of + {ok, Refs} -> + case lists:delete(Ref, Refs) of + [] -> + S#state{ref2pid=maps:remove(Ref,M1), pid2ref=maps:remove(Pid,M2)}; + L -> + S#state{ref2pid=maps:remove(Ref,M1), pid2ref=M2#{Pid => L}} + end; error -> - undefined; - Value -> - Value + S#state{ref2pid=maps:remove(Ref,M1)} end. %%%=================================================================== %%% Tests %%%=================================================================== +-ifdef(TEST). +-include_lib("eunit/include/eunit.hrl"). +-endif. + +-ifdef(EUNIT). + generate_test_() -> {setup, - fun () -> - ecrn_reg:start_link() - end, - fun (_) -> - ecrn_reg:stop() - end, + fun () -> ecrn_reg:start_link() end, + fun (_) -> ecrn_reg:stop() end, {with, [fun general_tests/1]}}. general_tests(_) -> - ?assertMatch(ok, ecrn_reg:register([a, b], boo)), - ?assertMatch({ok, [boo]}, ecrn_reg:get(a)), - ecrn_reg:unregister([a, b]), - ?assertMatch(undefined, ecrn_reg:get(a)), - ?assertMatch(ok, ecrn_reg:register([a, b], boo)), - ?assertMatch(ok, ecrn_reg:register([c, d], boo2)), - ?assertMatch({ok, [boo2]}, ecrn_reg:get(c)), - ?assertMatch({ok, [boo]}, ecrn_reg:get(b)), - ?assertMatch({discarded_keys, [d, c]}, - ecrn_reg:register([c, d], boo2)). + Self = self(), + ?assertMatch(true, ecrn_reg:register(a, Self)), + ?assertMatch(Self, ecrn_reg:get(a)), + ecrn_reg:unregister(a), + Ref = make_ref(), + ?assertMatch(undefined, ecrn_reg:get(a)), + ?assertMatch(true, ecrn_reg:register(b, Self)), + ?assertMatch(true, ecrn_reg:register(c, Self)), + ?assertMatch(true, ecrn_reg:register(Ref, Self)), + ?assertMatch(Self, ecrn_reg:get(c)), + ?assertMatch(Self, ecrn_reg:get(b)), + ?assertMatch(Self, ecrn_reg:get(Ref)), + ?assertMatch([b,c,Ref], ecrn_reg:get_refs(Self)), + ?assertMatch(false, ecrn_reg:register(b, Self)), + ?assertMatch(false, ecrn_reg:register(c, Self)), + ?assertMatch(false, ecrn_reg:register(Ref, Self)), + ?assertMatch([b,c,Ref], ecrn_reg:get_all_refs()), + ?assertMatch([Self], ecrn_reg:get_all_pids()), + ecrn_reg:unregister(b), + ?assertMatch([c,Ref], ecrn_reg:get_all_refs()), + ?assertMatch([Self], ecrn_reg:get_all_pids()), + ok. + +-endif. diff --git a/src/ecrn_sup.erl b/src/ecrn_sup.erl index 2544f4e..b854849 100644 --- a/src/ecrn_sup.erl +++ b/src/ecrn_sup.erl @@ -1,46 +1,58 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link() -> {ok, Pid::term()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> - RestartStrategy = one_for_one, - MaxRestarts = 3, - MaxSecondsBetweenRestarts = 10, - SupFlags = {RestartStrategy, - MaxRestarts, - MaxSecondsBetweenRestarts}, - - ChildSup = {ecrn_cron_sup, {ecrn_cron_sup, start_link, []}, - permanent, 1000, supervisor, [ecrn_cron_sup]}, - RegistrationServer = {ecrn_reg_server, {ecrn_reg, start_link, []}, - permanent, 1000, worker, [ecrn_reg]}, - BroadcastServer = {ecrn_control, {ecrn_control, start_link, []}, - permanent, 1000, worker, [ecrn_control]}, - - - {ok, {SupFlags, [ChildSup, RegistrationServer, BroadcastServer]}}. + SupFlags = #{ + strategy => one_for_one, + intensity => application:get_env(erlcron, sup_intensity, 3), + period => application:get_env(erlcron, sup_period, 10) + }, + + ChildSup = #{id => ecrn_cron_sup, + start => {ecrn_cron_sup, start_link, []}, + restart => permanent, + shutdown => 1000, + type => supervisor, + modules => [ecrn_cron_sup]}, + + RegServer = #{id => ecrn_reg, + start => {ecrn_reg, start_link, []}, + restart => permanent, + shutdown => 1000, + type => worker, + modules => [ecrn_reg]}, + + CtrlServer = #{id => ecrn_control, + start => {ecrn_control, start_link, []}, + restart => permanent, + shutdown => 1000, + type => worker, + modules => [ecrn_control]}, + + {ok, {SupFlags, [ChildSup, RegServer, CtrlServer]}}. diff --git a/src/ecrn_test.erl b/src/ecrn_test.erl deleted file mode 100644 index 612ab37..0000000 --- a/src/ecrn_test.erl +++ /dev/null @@ -1,166 +0,0 @@ -%%% @copyright Erlware, LLC. All Rights Reserved. -%%% -%%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. --module(ecrn_test). - --include_lib("eunit/include/eunit.hrl"). - -%%%=================================================================== -%%% Types -%%%=================================================================== -cron_test_() -> - {setup, - fun() -> - ecrn_app:manual_start() - end, - fun(_) -> - ecrn_app:manual_stop() - end, - {with, [fun set_alarm_test/1, - fun travel_back_in_time_test/1, - fun cancel_alarm_test/1, - fun big_time_jump_test/1, - fun cron_test/1, - fun validation_test/1]}}. - -set_alarm_test(_) -> - EpochDay = {2000,1,1}, - EpochDateTime = {EpochDay,{8,0,0}}, - erlcron:set_datetime(EpochDateTime), - Alarm1TimeOfDay = {9,0,0}, - Alarm2TimeOfDay = {9,0,1}, - - Self = self(), - - erlcron:at(Alarm1TimeOfDay, fun(_, _) -> - Self ! ack1 - end), - erlcron:at(Alarm2TimeOfDay, fun(_, _) -> - Self ! ack2 - end), - erlcron:set_datetime({EpochDay, {8, 59, 59}}), - - %% The alarm should trigger this nearly immediately. - ?assertMatch(ok, receive - ack1 -> ok - after - 1500 -> timeout - end), - - %% The alarm should trigger this 1 second later. - ?assertMatch(ok, receive - ack2 -> ok - after - 2500 -> timeout - end). - -cancel_alarm_test(_) -> - Day = {2000,1,1}, - erlcron:set_datetime({Day,{8,0,0}}), - AlarmTimeOfDay = {9,0,0}, - - Self = self(), - - Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> - Self ! ack - end), - erlcron:cancel(Ref), - erlcron:set_datetime({Day, AlarmTimeOfDay}), - ?assertMatch(ok, receive - ack -> ack - after - %% There is no event-driven way to - %% ensure we never receive an ack. - 125 -> ok - end). - -%% Time jumps ahead one day so we should see the alarms from both days. -big_time_jump_test(_) -> - Day1 = {2000,1,1}, - Day2 = {2000,1,2}, - EpochDateTime = {Day1,{8,0,0}}, - erlcron:set_datetime(EpochDateTime), - Alarm1TimeOfDay = {9,0,0}, - Alarm2TimeOfDay = {9,0,1}, - - Self = self(), - - erlcron:at(Alarm1TimeOfDay, fun(_, _) -> - Self ! ack1 - end), - erlcron:at(Alarm2TimeOfDay, fun(_, _) -> - Self ! ack2 - end), - erlcron:set_datetime({Day2, {9, 10, 0}}), - ?assertMatch(ok, receive - ack1 -> ok - after - 1500 -> timeout - end), - ?assertMatch(ok, receive - ack2 -> ok - after - 1500 -> timeout - end), - - ?assertMatch(ok, receive - ack1 -> ok - after - 1500 -> timeout - end), - ?assertMatch(ok, receive - ack2 -> ok - after - 2500 -> timeout - end). - -travel_back_in_time_test(_) -> - Seconds = seconds_now(), - Past = {{2000,1,1},{12,0,0}}, - erlcron:set_datetime(Past), - {ExpectedDateTime, _} = erlcron:datetime(), - ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), - ?assertMatch(true, ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), - ?assertMatch(true, ExpectedSeconds < Seconds). - - -%% Time jumps ahead one day so we should see the alarms from both days. -cron_test(_) -> - Day1 = {2000,1,1}, - AlarmTimeOfDay = {15,29,58}, - erlcron:set_datetime({Day1, AlarmTimeOfDay}), - - Self = self(), - - Job = {{daily, {3, 30, pm}}, - fun(_, _) -> - Self ! ack - end}, - - erlcron:cron(Job), - - ?assertMatch(ok, receive - ack -> ok - after - 2500 -> timeout - end). - -validation_test(_) -> - ?assertMatch(valid, ecrn_agent:validate({once, {3, 30, pm}})), - ?assertMatch(valid, ecrn_agent:validate({once, 3600})), - ?assertMatch(valid, ecrn_agent:validate({daily, {every, {23, sec}, - {between, {3, pm}, {3, 30, pm}}}})), - ?assertMatch(valid, ecrn_agent:validate({daily, {3, 30, pm}})), - ?assertMatch(valid, ecrn_agent:validate({weekly, thu, {2, am}})), - ?assertMatch(valid, ecrn_agent:validate({weekly, wed, {2, am}})), - ?assertMatch(valid, ecrn_agent:validate({monthly, 1, {2, am}})), - ?assertMatch(valid, ecrn_agent:validate({monthly, 4, {2, am}})), - ?assertMatch(invalid, ecrn_agent:validate({daily, {55, 22, am}})), - ?assertMatch(invalid, ecrn_agent:validate({monthly, 65, {55, am}})). - -%%%=================================================================== -%%% Internal Functions -%%%=================================================================== -seconds_now() -> - calendar:datetime_to_gregorian_seconds(calendar:universal_time()). diff --git a/src/ecrn_util.erl b/src/ecrn_util.erl index 0fd00fa..5c7bc3e 100644 --- a/src/ecrn_util.erl +++ b/src/ecrn_util.erl @@ -1,18 +1,48 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Utility functions for the erlcron system -module(ecrn_util). --export([epoch_seconds/0]). +-export([epoch_seconds/0, epoch_milliseconds/0]). +-export([epoch_to_time_string/1, epoch_to_datetime_string/1]). +-export([universaltime_to_epoch/1, localtime_to_epoch/1]). %%%=================================================================== %%% API %%%=================================================================== -spec epoch_seconds() -> erlcron:seconds(). epoch_seconds() -> - {Megasecs, Secs, Microsecs} = os:timestamp(), - erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)). + erlang:system_time(seconds). + +-spec epoch_milliseconds() -> erlcron:milliseconds(). +epoch_milliseconds() -> + erlang:system_time(millisecond). + +-spec epoch_to_time_string(erlcron:milliseconds()) -> string(). +epoch_to_time_string(Epoch) when is_integer(Epoch) -> + DT = erlang:posixtime_to_universaltime(Epoch div 1000), + {_, {H,M,S}} = erlang:universaltime_to_localtime(DT), + fmt("~.2.0w:~.2.0w:~.2.0w.~.3.0w", [H,M,S, Epoch rem 1000]). + +-spec epoch_to_datetime_string(erlcron:milliseconds()) -> string(). +epoch_to_datetime_string(Epoch) when is_integer(Epoch) -> + DT = erlang:posixtime_to_universaltime(Epoch div 1000), + {{Y,Mo,D}, {H,M,S}} = erlang:universaltime_to_localtime(DT), + fmt("~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w.~.3.0w", + [Y,Mo,D,H,M,S, Epoch rem 1000]). + +-spec universaltime_to_epoch(calendar:datetime()) -> erlcron:milliseconds(). +universaltime_to_epoch(DT) -> + erlang:universaltime_to_posixtime(DT)*1000. + +-spec localtime_to_epoch(calendar:datetime()) -> erlcron:milliseconds(). +localtime_to_epoch(DT) -> + erlang:universaltime_to_posixtime(erlang:localtime_to_universaltime(DT))*1000. + + +fmt(Fmt, Args) -> + lists:flatten(io_lib:format(Fmt, Args)). diff --git a/src/erlcron.app.src b/src/erlcron.app.src index f227562..f9fc463 100644 --- a/src/erlcron.app.src +++ b/src/erlcron.app.src @@ -1,7 +1,7 @@ {application,erlcron, [{description,"Erlang Implementation of cron"}, - {vsn,"semver"}, + {vsn,"0.1"}, {modules,[]}, {registered,[ecrn_agent]}, {applications,[kernel,stdlib]}, {mod,{ecrn_app,[]}}]}. diff --git a/src/erlcron.erl b/src/erlcron.erl index 7279a64..ebc9326 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,120 +1,188 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, - cron/1, - at/2, - once/2, + cron/1, cron/2, + at/2, at/3, + daily/2, daily/3, + weekly/3, weekly/4, + monthly/3,monthly/4, cancel/1, + epoch/0, + epoch_seconds/0, datetime/0, set_datetime/1, + reset_datetime/0, + get_all_jobs/0, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, - seconds/0]). + seconds/0, + milliseconds/0]). %%%=================================================================== %%% Types %%%=================================================================== --type seconds() :: integer(). +-type seconds() :: integer(). +-type milliseconds():: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. --type duration() :: {integer(), hr | min | sec}. --type period() :: cron_time() | {every, duration(), constraint()}. +-type duration() :: {integer(), hr | h | min | m | sec | s}. +-type period() :: cron_time() | {every, duration()} + | {every, duration(), constraint()}. -type dom() :: integer(). --type dow() :: mon | tue | wed | thu | fri | sat | sun. --type callable() :: {M :: module(), F :: atom(), A :: [term()]} | function(). +-type dow_day() :: mon | tue | wed | thu | fri | sat | sun. +-type dow() :: dow_day() | [dow_day()]. +-type callable() :: {M :: module(), F :: atom(), A :: [term()]} | + fun(() -> ok) | + fun((JobRef::atom()|reference(), calendar:datetime()) -> ok). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} - | {monthly, dom(), period()}. + | {monthly, dom()|[dom()], period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it --type job_ref() :: reference(). +-type job_ref() :: reference() | atom(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid --spec validate(run_when()) -> valid | invalid. +-spec validate(run_when()) -> ok | {error, term()}. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref(). cron(Job) -> - JobRef = make_ref(), + cron(make_ref(), Job). + +-spec cron(job_ref(), job()) -> job_ref(). +cron(JobRef, Job) when (is_atom(JobRef) orelse is_reference(JobRef)) + , is_tuple(Job) -> ecrn_cron_sup:add_job(JobRef, Job). + %% @doc -%% Convienience method to specify a job run to run on a daily basis -%% at a specific time. +%% Run the specified job once after the amount of time specifed. -spec at(cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> - Job = {{daily, When}, Fun}, - cron(Job). + at(make_ref(), When, Fun). + +-spec at(job_ref(), cron_time() | seconds(), function()) -> job_ref(). +at(JobRef, When, Fun) -> + cron(JobRef, {{once, When}, Fun}). %% @doc -%% Run the specified job once after the amount of time specifed. --spec once(cron_time() | seconds(), function()) -> job_ref(). -once(When, Fun) -> - Job = {{once, When}, Fun}, - cron(Job). +%% Convienience method to specify a job run to run on a daily basis +%% at a specific time. +-spec daily(cron_time() | seconds(), function()) -> job_ref(). +daily(When, Fun) -> + daily(make_ref(), When, Fun). + +-spec daily(job_ref(), cron_time() | seconds(), function()) -> job_ref(). +daily(JobRef, When, Fun) -> + cron(JobRef, {{daily, When}, Fun}). + +%% @doc +%% Convienience method to specify a job run to run on a weekly basis +%% at a specific time. +-spec weekly(dow(), cron_time() | seconds(), function()) -> job_ref(). +weekly(DOW, When, Fun) -> + weekly(make_ref(), DOW, When, Fun). + +-spec weekly(job_ref(), dow(), cron_time() | seconds(), function()) -> job_ref(). +weekly(JobRef, DOW, When, Fun) -> + cron(JobRef, {{weekly, DOW, When}, Fun}). + +%% @doc +%% Convienience method to specify a job run to run on a weekly basis +%% at a specific time. +-spec monthly(dom(), cron_time() | seconds(), function()) -> job_ref(). +monthly(DOM, When, Fun) -> + monthly(make_ref(), DOM, When, Fun). + +-spec monthly(job_ref(), dom(), cron_time() | seconds(), function()) -> job_ref(). +monthly(JobRef, DOM, When, Fun) -> + cron(JobRef, {{monthly, DOM, When}, Fun}). %% @doc %% Cancel the job specified by the jobref. --spec cancel(job_ref()) -> ok | undefined. +-spec cancel(job_ref()) -> boolean(). cancel(JobRef) -> ecrn_control:cancel(JobRef). +%% @doc +%% Get the current date time in seconds since epoch. +-spec epoch() -> erlcron:milliseconds(). +epoch() -> + ecrn_util:epoch_milliseconds(). + +%% @doc +%% Get the current date time in milliseconds since epoch. +-spec epoch_seconds() -> erlcron:seconds(). +epoch_seconds() -> + ecrn_util:epoch_seconds(). + %% @doc %% Get the current date time of the running erlcron system. -spec datetime() -> {calendar:datetime(), seconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Set the current date time of the running erlcron system. -spec set_datetime(calendar:datetime()) -> ok. -set_datetime(DateTime) -> +set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:set_datetime(DateTime). %% @doc -%% Set the current date time of the erlcron system running on different nodes. +%% Reset the reference datetime of erlcron system to current epoch time. +-spec reset_datetime() -> ok. +reset_datetime() -> + ecrn_control:reset_datetime(). + +%% Get references of all running jobs +-spec get_all_jobs() -> [job_ref()]. +get_all_jobs() -> + ecrn_reg:get_all_refs(). + +%% @doc +%% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> ok. -multi_set_datetime(DateTime) -> +multi_set_datetime({D,T} = DateTime) when tuple_size(D)==3, tuple_size(T)==3 -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc -%% Set the current date time of the erlcron system running on the -%% specified nodes +%% Set the current date time of the erlcron system running on the +%% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> ok. -multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> +multi_set_datetime(Nodes, DateTime) when is_list(Nodes), tuple_size(DateTime)==2 -> ecrn_control:multi_set_datetime(Nodes, DateTime). diff --git a/test/ecrn_test.erl b/test/ecrn_test.erl new file mode 100644 index 0000000..5b64f63 --- /dev/null +++ b/test/ecrn_test.erl @@ -0,0 +1,157 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. +-module(ecrn_test). +-compile(export_all). +-compile(nowarn_export_all). + +-include_lib("eunit/include/eunit.hrl"). + +-define(FuncTest(A), {atom_to_list(A), fun A/0}). + +%%%=================================================================== +%%% Types +%%%=================================================================== +cron_test_() -> + {setup, + fun() -> + application:load(erlcron), + application:set_env(erlcron, sup_intensity, 0), + application:set_env(erlcron, sup_period, 1), + application:start(erlcron) + end, + fun(_) -> + application:stop(erlcron) + end, + {timeout, 30, [ + ?FuncTest(set_alarm), + ?FuncTest(travel_back_in_time), + ?FuncTest(cancel_alarm), + ?FuncTest(big_time_jump), + ?FuncTest(cron), + ?FuncTest(validation) + ]}}. + +set_alarm() -> + erlcron:set_datetime({{2000,1,1},{8,0,0}}), + + Self = self(), + + erlcron:at(test1, {9,0,0}, fun() -> Self ! ack1 end), + erlcron:at(test2, {9,0,1}, fun() -> Self ! ack2 end), + erlcron:daily(test3, {every, {1,s}, {between, {9,0,2}, {9,0,4}}}, + fun() -> Self ! ack3 end), + + erlcron:set_datetime({{2000,1,1},{8,59,59}}), + + %% The alarm should trigger this nearly immediately. + ?assertMatch(1, collect(ack1, 1500, 1)), + + %% The alarm should trigger this 1 second later. + ?assertMatch(1, collect(ack2, 2500, 1)), + + %% The alarm should trigger this 1 second later. + ?assertMatch(3, collect(ack3, 3000, 3)), + + erlcron:cancel(test3). + +cancel_alarm() -> + Day = {2000,1,1}, + erlcron:set_datetime({Day,{8,0,0}}), + AlarmTimeOfDay = {9,0,0}, + + Self = self(), + + Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> + Self ! ack + end), + erlcron:cancel(Ref), + erlcron:set_datetime({Day, AlarmTimeOfDay}), + ?assertMatch(0, collect(ack, 125, 1)). + +%% Time jumps ahead one day so we should see the alarms from both days. +big_time_jump() -> + Day1 = {2000,1,1}, + Day2 = {2000,1,2}, + EpochDateTime = {Day1,{8,0,0}}, + erlcron:set_datetime(EpochDateTime), + Alarm1TimeOfDay = {9,0,0}, + Alarm2TimeOfDay = {9,0,1}, + + Self = self(), + + erlcron:daily(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), + erlcron:daily(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), + erlcron:set_datetime({Day2, {9, 10, 0}}), + ?assertMatch(1, collect(ack1, 1500, 1)), + ?assertMatch(1, collect(ack2, 1500, 1)), + ?assertMatch(1, collect(ack1, 1500, 1)), + ?assertMatch(1, collect(ack2, 1500, 1)). + +travel_back_in_time() -> + Seconds = seconds_now(), + Past = {{2000,1,1},{12,0,0}}, + erlcron:set_datetime(Past), + {ExpectedDateTime, _} = erlcron:datetime(), + ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), + ?assertMatch(true, ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), + ?assertMatch(true, ExpectedSeconds < Seconds). + + +%% Time jumps ahead one day so we should see the alarms from both days. +cron() -> + Day1 = {2000,1,1}, + AlarmTimeOfDay = {15,29,58}, + erlcron:set_datetime({Day1, AlarmTimeOfDay}), + + Self = self(), + + Job = {{daily, {3, 30, pm}}, + fun(_, _) -> + Self ! ack + end}, + + erlcron:cron(Job), + + ?assertMatch(1, collect(ack, 2500, 1)). + +validation() -> + erlcron:set_datetime({{2000,1,1}, {15,0,0}}), + ?assertMatch(ok, ecrn_agent:validate({once, {3, 30, pm}})), + erlcron:set_datetime({{2000,1,1}, {15,31,0}}), + ?assertMatch({error,{specified_time_past_seconds_ago, -60}}, + ecrn_agent:validate({once, {3, 30, pm}})), + + ?assertMatch(ok, ecrn_agent:validate({once, 3600})), + ?assertMatch(ok, ecrn_agent:validate({daily, {every, {0,s}}})), + ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,s}}})), + ?assertMatch(ok, ecrn_agent:validate({daily, {every, {23,sec}, + {between, {3, pm}, {3, 30, pm}}}})), + ?assertMatch(ok, ecrn_agent:validate({daily, {3, 30, pm}})), + ?assertMatch(ok, ecrn_agent:validate({weekly, thu, {2, am}})), + ?assertMatch(ok, ecrn_agent:validate({weekly, wed, {2, am}})), + ?assertMatch(ok, ecrn_agent:validate({weekly, fri, {every, {5,sec}}})), + ?assertMatch(ok, ecrn_agent:validate({monthly, 1, {2, am}})), + ?assertMatch(ok, ecrn_agent:validate({monthly, 4, {2, am}})), + ?assertMatch({error,{invalid_time,{55,22,am}}}, + ecrn_agent:validate({daily, {55, 22, am}})), + ?assertMatch({error,{invalid_days_in_schedule,{monthly,"A",{55,am}}}}, + ecrn_agent:validate({monthly, 65, {55, am}})). + +%%%=================================================================== +%%% Internal Functions +%%%=================================================================== +seconds_now() -> + calendar:datetime_to_gregorian_seconds(calendar:universal_time()). + +collect(Msg, Timeout, Count) -> + collect(Msg, Timeout, 0, Count). +collect(_Msg, _Timeout, Count, Count) -> + Count; +collect(Msg, Timeout, I, Count) -> + receive + Msg -> collect(Msg, Timeout, I+1, Count) + after + Timeout -> I + end.
erlware/erlcron
d4448b47d531c7b917547d357dffd48008f2444f
use erl-21 new try catch syntax
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 55a14e2..dde1b76 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,401 +1,417 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref -spec start_link(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Validate that a run_when spec specified is correct. -spec validate(erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %% @private handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %% @private handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %% @private terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time(state()) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_milliseconds(state(), erlcron:job()) -> {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. +%%-ifdef(OTP_VSN_21_AND_ABOVE). +-ifdef(OTP_RELEASE). +%% OTP 21 or higher +normalize_seconds(State, Seconds) -> + %% change for R21 + %% get_stacktrace/0 not supported + try + Value = Seconds - current_time(State), + true = (Value >= 0) + catch + _C:_R:StackTrace -> + erlang:display(StackTrace), + throw(invalid_once_exception) + end. +-else. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. +-endif. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. -spec until_next_time(state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. -spec until_next_daytime(state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @doc Calculates the last time in a given period. -spec last_time(erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @doc Calculates the first time in a given period. -spec first_time(erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @doc Calculates the first time in the given period after the given time. -spec next_time(erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @doc Returns a list of times given a periodic specification. -spec resolve_period([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @doc Returns seconds past midnight for a given time. -spec resolve_time(erlcron:cron_time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @doc Returns seconds for a given duration. -spec resolve_dur(erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow(erlcron:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow(state(), erlcron:seconds()) -> erlcron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), erlcron:period(), integer()) -> erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. -spec until_next_daytime_or_days_from_now(state(), erlcron:period(), integer()) -> erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end.
erlware/erlcron
bbdd67ba7af136fe43f667ecf1a77d1beaa10d0f
Fix specs, README
diff --git a/README.md b/README.md index 9fd17ad..1a86902 100644 --- a/README.md +++ b/README.md @@ -1,145 +1,145 @@ Erlcron ======= Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The synax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. Unlike cron's one-minute resolution, erlcron has a 2-second resolution (actually 1 second, but after running the job, the process waits an extra second to avoid accidentally running it more than once.) It does not handle Daylight Savings Time (or other cases when the system clock is altered) gracefully, and it is recommended that it be stopped and restarted on such occasions. Cron Job Description Examples: ```erlang {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, - fun() -> io:fwrite("It's three thirty~n") end} + fun(_JobRef, _DateTime) -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, - {fun() -> io:fwrite("It's 2 Wednesday morning~n") end} + {fun(_JobRef, _DateTime) -> io:fwrite("It's 2 Wednesday morning~n") end} {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} ``` Adding a cron to the system: ```erlang Job = {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}}. erlcron:cron(Job). ``` A simple way to add a daily cron: erlcron:at({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. ```erlang erlcron:once(300, Fun). ``` Cancel a running job. ```erlang erlcron:cancel(JobRef). ``` Get the current date time of the system. ```erlang erlcron:datetime(). ``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:set_datetime(DateTime). ``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(DateTime). ``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. ```erlang erlcron:multi_set_datetime(Nodes, DateTime). ``` The application cron can be pre-configured throught environment variables in the config file that all applications can load in the Erlang VM start. The app.config file can be as follow: ```erlang [ {erlcron, [ {crontab, [ {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}}, {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} ]} ]} ]. ``` So, when the app will be started, all configurations will be loaded. Note that the limitation is that in the config file is impossible load an anonymous function (or lambda function) so, you only can use {M,F,A} format. diff --git a/src/erlcron.erl b/src/erlcron.erl index 7279a64..414b4f7 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,120 +1,121 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | min | sec}. -type period() :: cron_time() | {every, duration(), constraint()}. -type dom() :: integer(). -type dow() :: mon | tue | wed | thu | fri | sat | sun. --type callable() :: {M :: module(), F :: atom(), A :: [term()]} | function(). +-type callable() :: {M :: module(), F :: atom(), A :: [term()]} | + fun((job_ref(), calendar:datetime()) -> term()). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom(), period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate(run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job). %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. --spec at(cron_time() | seconds(), function()) -> job_ref(). +-spec at(cron_time() | seconds(), fun((job_ref(), calendar:datetime()) -> term())) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %% @doc %% Run the specified job once after the amount of time specifed. --spec once(cron_time() | seconds(), function()) -> job_ref(). +-spec once(cron_time() | seconds(), fun((job_ref(), calendar:datetime()) -> term())) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %% @doc %% Cancel the job specified by the jobref. -spec cancel(job_ref()) -> ok | undefined. cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time of the running erlcron system. -spec datetime() -> {calendar:datetime(), seconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Set the current date time of the running erlcron system. -spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime(calendar:datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
194110ac6cfdc69431d1373affa7456269e4d2d0
Fix specs for OTP 19
diff --git a/.travis.yml b/.travis.yml index eff24fa..5f9909c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,14 +1,15 @@ sudo: false language: erlang otp_release: - R15B03 - R16B03-1 - 17.5 - 18.0 - 18.1 + - 19.0 before_script: "make get-deps" script: "make test" branches: only: - master diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index dd93e5b..55a14e2 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,401 +1,401 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% Types %%%=================================================================== -type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref --spec start_link/2 ::(erlcron:job_ref(), erlcron:job()) -> +-spec start_link(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). --spec get_datetime/1 :: (pid()) -> calendar:datetime(). +-spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). --spec cancel/1 :: (pid()) -> ok. +-spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). --spec set_datetime/3 :: (pid(), calendar:datetime(), erlcron:seconds()) -> ok. +-spec set_datetime(pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). --spec recalculate/1 :: (pid()) -> ok. +-spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Validate that a run_when spec specified is correct. --spec validate/1 :: (erlcron:run_when()) -> valid | invalid. +-spec validate(erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %% @private handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %% @private handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %% @private terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. --spec current_time/1 :: (state()) -> erlcron:seconds(). +-spec current_time(state()) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. --spec until_next_milliseconds/2 :: (state(), erlcron:job()) -> +-spec until_next_milliseconds(state(), erlcron:job()) -> {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. --spec until_next_time/2 :: (state(), {erlcron:run_when(), term()}) -> +-spec until_next_time(state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. --spec until_next_daytime/2 :: (state(), erlcron:period()) -> erlcron:seconds(). +-spec until_next_daytime(state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @doc Calculates the last time in a given period. --spec last_time/1 :: (erlcron:period()) -> erlcron:seconds(). +-spec last_time(erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @doc Calculates the first time in a given period. --spec first_time/1 :: (erlcron:period()) -> erlcron:seconds(). +-spec first_time(erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @doc Calculates the first time in the given period after the given time. --spec next_time/2 :: (erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). +-spec next_time(erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @doc Returns a list of times given a periodic specification. --spec resolve_period/1 :: ([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. +-spec resolve_period([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @doc Returns seconds past midnight for a given time. --spec resolve_time/1 :: (erlcron:cron_time()) -> erlcron:seconds(). +-spec resolve_time(erlcron:cron_time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @doc Returns seconds for a given duration. --spec resolve_dur/1 :: (erlcron:duration()) -> erlcron:seconds(). +-spec resolve_dur(erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. --spec resolve_dow/1 :: (erlcron:dow()) -> integer(). +-spec resolve_dow(erlcron:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. --spec until_tomorrow/2 :: (state(), erlcron:seconds()) -> erlcron:seconds(). +-spec until_tomorrow(state(), erlcron:seconds()) -> erlcron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. --spec until_days_from_now/3 :: (state(), erlcron:period(), integer()) -> +-spec until_days_from_now(state(), erlcron:period(), integer()) -> erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. --spec until_next_daytime_or_days_from_now/3 :: (state(), erlcron:period(), integer()) -> +-spec until_next_daytime_or_days_from_now(state(), erlcron:period(), integer()) -> erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index a90d8a8..4ebd79e 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,116 +1,116 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). -record(state, {reference_datetime :: calendar:datetime(), datetime_at_reference :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== --spec start_link/0 :: () -> {ok, pid()} | ignore | {error, Error::term()}. +-spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). --spec cancel/1 :: (erlcron:job_ref()) -> ok | undefined. +-spec cancel(erlcron:job_ref()) -> ok | undefined. cancel(AlarmRef) -> gen_server:call(?SERVER, {cancel, AlarmRef}). --spec datetime/0 :: () -> {calendar:datetime(), erlcron:seconds()}. +-spec datetime() -> {calendar:datetime(), erlcron:seconds()}. datetime() -> gen_server:call(?SERVER, get_datetime). %% @doc sets the date-time for the erlcron --spec set_datetime/1 :: (calendar:datetime()) -> ok. +-spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime={_,_}) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc sets the date-time with the erlcron on all nodes --spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. +-spec multi_set_datetime([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> DateTime = erlang:localtime(), {ok, #state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}}. %% @private handle_call({cancel, AlarmRef}, _From, State) -> {reply, internal_cancel(AlarmRef), State}; handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, datetime_at_reference = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}, case lists:foldl(fun({_, [Pid]}, Acc) -> ecrn_agent:set_datetime(Pid, DateTime, NewState#state.datetime_at_reference), Acc; ({Ref, X}, Acc) when is_list(X) -> [Ref | Acc] end, [], ecrn_reg:get_all()) of [] -> {reply, ok, NewState}; ErrorRefs -> {reply, {error, ErrorRefs}, NewState} end. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== internal_cancel(AlarmRef) -> case ecrn_reg:get(AlarmRef) of undefined -> undefined; {ok, [Pid]} -> ecrn_agent:cancel(Pid) end. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index dfdfde0..ba29d29 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,56 +1,56 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== --spec start_link/0 :: () -> {ok, pid()} | ignore | {error, Error::term()}. +-spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc %% Add a chron job to be supervised --spec add_job/2 :: (erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). +-spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). add_job(JobRef, Task) -> {ok, _} = supervisor:start_child(?SERVER, [JobRef, Task]), JobRef. %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> RestartStrategy = simple_one_for_one, MaxRestarts = 1000, MaxSecondsBetweenRestarts = 3600, SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, Restart = transient, Shutdown = 2000, Type = worker, AChild = {ecrn_agent, {ecrn_agent, start_link, []}, Restart, Shutdown, Type, [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. diff --git a/src/ecrn_reg.erl b/src/ecrn_reg.erl index 7e11d7c..299e9d1 100644 --- a/src/ecrn_reg.erl +++ b/src/ecrn_reg.erl @@ -1,168 +1,168 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% This provides simple pid registration for the server. -module(ecrn_reg). -behaviour(gen_server). %% API -export([start_link/0, register/2, unregister/1, get/1, stop/0, get_all/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include_lib("eunit/include/eunit.hrl"). -define(SERVER, ?MODULE). -record(state, {registered}). %%%=================================================================== %%% API %%%=================================================================== --spec start_link/0 :: () -> {ok, Pid::pid()} | ignore | {error, Error::term()}. +-spec start_link() -> {ok, Pid::pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %% @doc %% Register an arbitrary value with the system, under a set of keys --spec register/2 :: (term() | [term()], term()) -> ok | {discarded_keys, [term()]}. +-spec register(term() | [term()], term()) -> ok | {discarded_keys, [term()]}. register(Keys, Body) when is_list(Keys) -> gen_server:call(?SERVER, {register, Keys, Body}); register(Key, Body) -> gen_server:call(?SERVER, {register, [Key], Body}). %% @doc %% Remove the value registered under a que or set of keys --spec unregister/1 :: (term() | [term()]) -> ok. +-spec unregister(term() | [term()]) -> ok. unregister(Keys) when is_list(Keys) -> gen_server:call(?SERVER, {unregister, Keys}); unregister(Key) -> gen_server:call(?SERVER, {unregister, [Key]}). %% @doc %% Get a value buy key. --spec get/1 :: (term()) -> {ok, term()} | undefined. +-spec get(term()) -> {ok, term()} | undefined. get(Key) -> gen_server:call(?SERVER, {get, Key}). %% @doc %% Get all the values. --spec get_all/0 :: () -> [{term(), term()}]. +-spec get_all() -> [{term(), term()}]. get_all() -> gen_server:call(?SERVER, get_all). %% @doc %% stop this server --spec stop/0 :: () -> ok. +-spec stop() -> ok. stop() -> gen_server:call(?SERVER, stop). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> {ok, #state{registered=dict:new()}}. %% @private handle_call({register, Keys, Body}, _From, #state{registered=Dict}) -> {Result, Dict2} = add_for_keys(Keys, Body, Dict, ok), {reply, Result, #state{registered=Dict2}}; handle_call({unregister, Keys}, _From, #state{registered=Dict}) -> Dict2 = remove_for_keys(Keys, Dict), {reply, ok, #state{registered=Dict2}}; handle_call({get, Key}, _From, State = #state{registered=Dict}) -> Value = get_for_key(Key, Dict), {reply, Value, State}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; handle_call(get_all, _From, State = #state{registered=Dict}) -> {reply, dict:to_list(Dict), State}. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== discarded_keys(Key, {discarded_keys, Keys}) -> {discarded_keys, [Key | Keys]}; discarded_keys(Key, ok) -> {discarded_keys, [Key]}. add_for_keys([Key | Rest], Body, Dict, Result) -> case dict:find(Key, Dict) of error -> add_for_keys(Rest, Body, dict:append(Key, Body, Dict), Result); _Value -> add_for_keys(Rest, Body, dict:append(Key, Body, Dict), discarded_keys(Key, Result)) end; add_for_keys([], _, Dict, Result) -> {Result, Dict}. remove_for_keys([Key | Rest], Dict) -> remove_for_keys(Rest, dict:erase(Key, Dict)); remove_for_keys([],Dict) -> Dict. get_for_key(Key, Dict) -> case dict:find(Key, Dict) of error -> undefined; Value -> Value end. %%%=================================================================== %%% Tests %%%=================================================================== generate_test_() -> {setup, fun () -> ecrn_reg:start_link() end, fun (_) -> ecrn_reg:stop() end, {with, [fun general_tests/1]}}. general_tests(_) -> ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch({ok, [boo]}, ecrn_reg:get(a)), ecrn_reg:unregister([a, b]), ?assertMatch(undefined, ecrn_reg:get(a)), ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch(ok, ecrn_reg:register([c, d], boo2)), ?assertMatch({ok, [boo2]}, ecrn_reg:get(c)), ?assertMatch({ok, [boo]}, ecrn_reg:get(b)), ?assertMatch({discarded_keys, [d, c]}, ecrn_reg:register([c, d], boo2)). diff --git a/src/ecrn_sup.erl b/src/ecrn_sup.erl index 4c56815..2544f4e 100644 --- a/src/ecrn_sup.erl +++ b/src/ecrn_sup.erl @@ -1,46 +1,46 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== --spec start_link/0 :: () -> {ok, Pid::term()} | ignore | {error, Error::term()}. +-spec start_link() -> {ok, Pid::term()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> RestartStrategy = one_for_one, MaxRestarts = 3, MaxSecondsBetweenRestarts = 10, SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, ChildSup = {ecrn_cron_sup, {ecrn_cron_sup, start_link, []}, permanent, 1000, supervisor, [ecrn_cron_sup]}, RegistrationServer = {ecrn_reg_server, {ecrn_reg, start_link, []}, permanent, 1000, worker, [ecrn_reg]}, BroadcastServer = {ecrn_control, {ecrn_control, start_link, []}, permanent, 1000, worker, [ecrn_control]}, {ok, {SupFlags, [ChildSup, RegistrationServer, BroadcastServer]}}. diff --git a/src/ecrn_util.erl b/src/ecrn_util.erl index 15b2a15..0fd00fa 100644 --- a/src/ecrn_util.erl +++ b/src/ecrn_util.erl @@ -1,18 +1,18 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Utility functions for the erlcron system -module(ecrn_util). -export([epoch_seconds/0]). %%%=================================================================== %%% API %%%=================================================================== --spec epoch_seconds/0 :: () -> erlcron:seconds(). +-spec epoch_seconds() -> erlcron:seconds(). epoch_seconds() -> {Megasecs, Secs, Microsecs} = os:timestamp(), erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)). diff --git a/src/erlcron.erl b/src/erlcron.erl index 210e689..7279a64 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,120 +1,120 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | min | sec}. -type period() :: cron_time() | {every, duration(), constraint()}. -type dom() :: integer(). -type dow() :: mon | tue | wed | thu | fri | sat | sun. -type callable() :: {M :: module(), F :: atom(), A :: [term()]} | function(). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom(), period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid --spec validate/1 :: (run_when()) -> valid | invalid. +-spec validate(run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. --spec cron/1 :: (job()) -> job_ref(). +-spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job). %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. --spec at/2 :: (cron_time() | seconds(), function()) -> job_ref(). +-spec at(cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %% @doc %% Run the specified job once after the amount of time specifed. --spec once/2 :: (cron_time() | seconds(), function()) -> job_ref(). +-spec once(cron_time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %% @doc %% Cancel the job specified by the jobref. --spec cancel/1 :: (job_ref()) -> ok | undefined. +-spec cancel(job_ref()) -> ok | undefined. cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time of the running erlcron system. --spec datetime/0 :: () -> {calendar:datetime(), seconds()}. +-spec datetime() -> {calendar:datetime(), seconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Set the current date time of the running erlcron system. --spec set_datetime/1 :: (calendar:datetime()) -> ok. +-spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %% @doc %% Set the current date time of the erlcron system running on different nodes. --spec multi_set_datetime/1 :: (calendar:datetime()) -> ok. +-spec multi_set_datetime(calendar:datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes --spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. +-spec multi_set_datetime([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
8f734afefe748d2d776304cec14e8a33445d1cf4
Make travis-ci test OTP/18.1
diff --git a/.travis.yml b/.travis.yml index a3c473d..eff24fa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,13 +1,14 @@ sudo: false language: erlang otp_release: - R15B03 - R16B03-1 - 17.5 - 18.0 + - 18.1 before_script: "make get-deps" script: "make test" branches: only: - master
erlware/erlcron
7db95992911aaa188c57284afa9ddbacb2464b1b
Stop calling erlang:now/0; use os:timestamp/0 instead
diff --git a/src/ecrn_util.erl b/src/ecrn_util.erl index 67ee86e..15b2a15 100644 --- a/src/ecrn_util.erl +++ b/src/ecrn_util.erl @@ -1,18 +1,18 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Utility functions for the erlcron system -module(ecrn_util). -export([epoch_seconds/0]). %%%=================================================================== %%% API %%%=================================================================== -spec epoch_seconds/0 :: () -> erlcron:seconds(). epoch_seconds() -> - {Megasecs, Secs, Microsecs} = erlang:now(), + {Megasecs, Secs, Microsecs} = os:timestamp(), erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)).
erlware/erlcron
278d2f53b6dc1453bfeb5ed78d8e9a341a433c71
Stop using deprecated syntax for records
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 23e67d3..dd93e5b 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,401 +1,401 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% Types %%%=================================================================== --type state() :: record(state). +-type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref -spec start_link/2 ::(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime/1 :: (pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel/1 :: (pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime/3 :: (pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate/1 :: (pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Validate that a run_when spec specified is correct. -spec validate/1 :: (erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %% @private handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %% @private handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %% @private terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time/1 :: (state()) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_milliseconds/2 :: (state(), erlcron:job()) -> {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. -spec until_next_time/2 :: (state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. -spec until_next_daytime/2 :: (state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @doc Calculates the last time in a given period. -spec last_time/1 :: (erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @doc Calculates the first time in a given period. -spec first_time/1 :: (erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @doc Calculates the first time in the given period after the given time. -spec next_time/2 :: (erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @doc Returns a list of times given a periodic specification. -spec resolve_period/1 :: ([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @doc Returns seconds past midnight for a given time. -spec resolve_time/1 :: (erlcron:cron_time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @doc Returns seconds for a given duration. -spec resolve_dur/1 :: (erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow/1 :: (erlcron:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow/2 :: (state(), erlcron:seconds()) -> erlcron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. -spec until_days_from_now/3 :: (state(), erlcron:period(), integer()) -> erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. -spec until_next_daytime_or_days_from_now/3 :: (state(), erlcron:period(), integer()) -> erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end.
erlware/erlcron
7b33f959353c06e5105ccefcd368622a47bfec51
Support travis-ci for erlcron
diff --git a/.travis.yml b/.travis.yml index 92eb51f..a3c473d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,13 @@ +sudo: false language: erlang otp_release: - - R15B02 - - R15B01 - - R15B -script: "make rebuild" + - R15B03 + - R16B03-1 + - 17.5 + - 18.0 + +before_script: "make get-deps" +script: "make test" branches: only: - master - - next \ No newline at end of file
erlware/erlcron
355fc17a2a4ac8f2d9b6bcadbb5ce7fb5d745355
Revert "MInumum update for R18"
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index dd93e5b..23e67d3 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,401 +1,401 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% Types %%%=================================================================== --type state() :: #state{}. +-type state() :: record(state). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref -spec start_link/2 ::(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime/1 :: (pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel/1 :: (pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime/3 :: (pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate/1 :: (pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Validate that a run_when spec specified is correct. -spec validate/1 :: (erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %% @private handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %% @private handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %% @private terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time/1 :: (state()) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_milliseconds/2 :: (state(), erlcron:job()) -> {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. -spec until_next_time/2 :: (state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. -spec until_next_daytime/2 :: (state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @doc Calculates the last time in a given period. -spec last_time/1 :: (erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @doc Calculates the first time in a given period. -spec first_time/1 :: (erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @doc Calculates the first time in the given period after the given time. -spec next_time/2 :: (erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @doc Returns a list of times given a periodic specification. -spec resolve_period/1 :: ([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @doc Returns seconds past midnight for a given time. -spec resolve_time/1 :: (erlcron:cron_time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @doc Returns seconds for a given duration. -spec resolve_dur/1 :: (erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow/1 :: (erlcron:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow/2 :: (state(), erlcron:seconds()) -> erlcron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. -spec until_days_from_now/3 :: (state(), erlcron:period(), integer()) -> erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. -spec until_next_daytime_or_days_from_now/3 :: (state(), erlcron:period(), integer()) -> erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/ecrn_util.erl b/src/ecrn_util.erl index 469c7ad..67ee86e 100644 --- a/src/ecrn_util.erl +++ b/src/ecrn_util.erl @@ -1,18 +1,18 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Utility functions for the erlcron system -module(ecrn_util). -export([epoch_seconds/0]). %%%=================================================================== %%% API %%%=================================================================== -spec epoch_seconds/0 :: () -> erlcron:seconds(). epoch_seconds() -> - {Megasecs, Secs, Microsecs} = erlang:timestamp(), + {Megasecs, Secs, Microsecs} = erlang:now(), erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)).
erlware/erlcron
474ebd59dc834b2549ea46e176722e446bb8f7ef
MInumum update for R18
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 23e67d3..dd93e5b 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,401 +1,401 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% Types %%%=================================================================== --type state() :: record(state). +-type state() :: #state{}. %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref -spec start_link/2 ::(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime/1 :: (pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel/1 :: (pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime/3 :: (pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate/1 :: (pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Validate that a run_when spec specified is correct. -spec validate/1 :: (erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %% @private handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %% @private handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %% @private terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time/1 :: (state()) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_milliseconds/2 :: (state(), erlcron:job()) -> {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. -spec until_next_time/2 :: (state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. -spec until_next_daytime/2 :: (state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @doc Calculates the last time in a given period. -spec last_time/1 :: (erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @doc Calculates the first time in a given period. -spec first_time/1 :: (erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @doc Calculates the first time in the given period after the given time. -spec next_time/2 :: (erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @doc Returns a list of times given a periodic specification. -spec resolve_period/1 :: ([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @doc Returns seconds past midnight for a given time. -spec resolve_time/1 :: (erlcron:cron_time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @doc Returns seconds for a given duration. -spec resolve_dur/1 :: (erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow/1 :: (erlcron:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow/2 :: (state(), erlcron:seconds()) -> erlcron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. -spec until_days_from_now/3 :: (state(), erlcron:period(), integer()) -> erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. -spec until_next_daytime_or_days_from_now/3 :: (state(), erlcron:period(), integer()) -> erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/ecrn_util.erl b/src/ecrn_util.erl index 67ee86e..469c7ad 100644 --- a/src/ecrn_util.erl +++ b/src/ecrn_util.erl @@ -1,18 +1,18 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Utility functions for the erlcron system -module(ecrn_util). -export([epoch_seconds/0]). %%%=================================================================== %%% API %%%=================================================================== -spec epoch_seconds/0 :: () -> erlcron:seconds(). epoch_seconds() -> - {Megasecs, Secs, Microsecs} = erlang:now(), + {Megasecs, Secs, Microsecs} = erlang:timestamp(), erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)).
erlware/erlcron
5536be3813f1f7b1afc74bf24e3b5dc809c18a42
fix typespec
diff --git a/src/erlcron.erl b/src/erlcron.erl index 5df40dd..210e689 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,120 +1,120 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | min | sec}. -type period() :: cron_time() | {every, duration(), constraint()}. -type dom() :: integer(). -type dow() :: mon | tue | wed | thu | fri | sat | sun. --type callable() :: mfa() | function(). +-type callable() :: {M :: module(), F :: atom(), A :: [term()]} | function(). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom(), period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate/1 :: (run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron/1 :: (job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job). %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. -spec at/2 :: (cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %% @doc %% Run the specified job once after the amount of time specifed. -spec once/2 :: (cron_time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %% @doc %% Cancel the job specified by the jobref. -spec cancel/1 :: (job_ref()) -> ok | undefined. cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time of the running erlcron system. -spec datetime/0 :: () -> {calendar:datetime(), seconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Set the current date time of the running erlcron system. -spec set_datetime/1 :: (calendar:datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime/1 :: (calendar:datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
61eb30d8e7f5f9d91f5af6d7a4ac18da64865dd4
Spec tweaks for erlcron:cancel/1
diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 2b8ce60..a90d8a8 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,116 +1,116 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). -record(state, {reference_datetime :: calendar:datetime(), datetime_at_reference :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link/0 :: () -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). --spec cancel/1 :: (erlcron:job_ref()) -> ok. +-spec cancel/1 :: (erlcron:job_ref()) -> ok | undefined. cancel(AlarmRef) -> gen_server:call(?SERVER, {cancel, AlarmRef}). -spec datetime/0 :: () -> {calendar:datetime(), erlcron:seconds()}. datetime() -> gen_server:call(?SERVER, get_datetime). %% @doc sets the date-time for the erlcron -spec set_datetime/1 :: (calendar:datetime()) -> ok. set_datetime(DateTime={_,_}) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc sets the date-time with the erlcron on all nodes -spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> DateTime = erlang:localtime(), {ok, #state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}}. %% @private handle_call({cancel, AlarmRef}, _From, State) -> {reply, internal_cancel(AlarmRef), State}; handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, datetime_at_reference = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}, case lists:foldl(fun({_, [Pid]}, Acc) -> ecrn_agent:set_datetime(Pid, DateTime, NewState#state.datetime_at_reference), Acc; ({Ref, X}, Acc) when is_list(X) -> [Ref | Acc] end, [], ecrn_reg:get_all()) of [] -> {reply, ok, NewState}; ErrorRefs -> {reply, {error, ErrorRefs}, NewState} end. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== internal_cancel(AlarmRef) -> case ecrn_reg:get(AlarmRef) of undefined -> undefined; {ok, [Pid]} -> ecrn_agent:cancel(Pid) end. diff --git a/src/erlcron.erl b/src/erlcron.erl index 7b8ab51..5df40dd 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,120 +1,120 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | min | sec}. -type period() :: cron_time() | {every, duration(), constraint()}. -type dom() :: integer(). -type dow() :: mon | tue | wed | thu | fri | sat | sun. -type callable() :: mfa() | function(). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom(), period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid -spec validate/1 :: (run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. -spec cron/1 :: (job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job). %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. -spec at/2 :: (cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %% @doc %% Run the specified job once after the amount of time specifed. -spec once/2 :: (cron_time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %% @doc %% Cancel the job specified by the jobref. --spec cancel/1 :: (job_ref()) -> ok. +-spec cancel/1 :: (job_ref()) -> ok | undefined. cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time of the running erlcron system. -spec datetime/0 :: () -> {calendar:datetime(), seconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Set the current date time of the running erlcron system. -spec set_datetime/1 :: (calendar:datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %% @doc %% Set the current date time of the erlcron system running on different nodes. -spec multi_set_datetime/1 :: (calendar:datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
d3735567a7e778a4216b6499693f91af4e158bd6
Internal cancel return type tweak and deletion of unused code
diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index 3d8a948..b163d6a 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,63 +1,61 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> application:start(crypto), application:start(eunit), application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> setup(), {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. setup() -> case application:get_env(erlcron, crontab) of {ok, Crontab} -> lists:foreach(fun(CronJob) -> erlcron:cron(CronJob) end, Crontab); undefined -> - ok; - Reason -> - error_logger:error_msg("Unknown crontab in configfile: ~p~n", [Reason]) + ok end. diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 944428a..2b8ce60 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,116 +1,116 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). -record(state, {reference_datetime :: calendar:datetime(), datetime_at_reference :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link/0 :: () -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). -spec cancel/1 :: (erlcron:job_ref()) -> ok. cancel(AlarmRef) -> gen_server:call(?SERVER, {cancel, AlarmRef}). -spec datetime/0 :: () -> {calendar:datetime(), erlcron:seconds()}. datetime() -> gen_server:call(?SERVER, get_datetime). %% @doc sets the date-time for the erlcron -spec set_datetime/1 :: (calendar:datetime()) -> ok. set_datetime(DateTime={_,_}) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc sets the date-time with the erlcron on all nodes -spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> DateTime = erlang:localtime(), {ok, #state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}}. %% @private handle_call({cancel, AlarmRef}, _From, State) -> {reply, internal_cancel(AlarmRef), State}; handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, datetime_at_reference = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}, case lists:foldl(fun({_, [Pid]}, Acc) -> ecrn_agent:set_datetime(Pid, DateTime, NewState#state.datetime_at_reference), Acc; ({Ref, X}, Acc) when is_list(X) -> [Ref | Acc] end, [], ecrn_reg:get_all()) of [] -> {reply, ok, NewState}; ErrorRefs -> {reply, {error, ErrorRefs}, NewState} end. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== internal_cancel(AlarmRef) -> case ecrn_reg:get(AlarmRef) of undefined -> undefined; {ok, [Pid]} -> - {ok, ecrn_agent:cancel(Pid)} + ecrn_agent:cancel(Pid) end.
erlware/erlcron
ea2aa43fd1d267dc63af397ff24ed22b98da5ecd
add config file support
diff --git a/README.md b/README.md index 898b11b..9fd17ad 100644 --- a/README.md +++ b/README.md @@ -1,107 +1,145 @@ Erlcron ======= Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The synax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. Unlike cron's one-minute resolution, erlcron has a 2-second resolution (actually 1 second, but after running the job, the process waits an extra second to avoid accidentally running it more than once.) It does not handle Daylight Savings Time (or other cases when the system clock is altered) gracefully, and it is recommended that it be stopped and restarted on such occasions. Cron Job Description Examples: - {{once, {3, 30, pm}}, - {io, fwrite, ["Hello, world!~n"]}} +```erlang +{{once, {3, 30, pm}}, + {io, fwrite, ["Hello, world!~n"]}} - {{once, {12, 23, 32}}, - {io, fwrite, ["Hello, world!~n"]}} +{{once, {12, 23, 32}}, + {io, fwrite, ["Hello, world!~n"]}} - {{once, 3600}, - {io, fwrite, ["Hello, world!~n"]}} +{{once, 3600}, + {io, fwrite, ["Hello, world!~n"]}} - {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, - {io, fwrite, ["Hello, world!~n"]}} +{{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, + {io, fwrite, ["Hello, world!~n"]}} - {{daily, {3, 30, pm}}, - fun() -> io:fwrite("It's three thirty~n") end} +{{daily, {3, 30, pm}}, + fun() -> io:fwrite("It's three thirty~n") end} - {{daily, [{1, 10, am}, {1, 07, 30, am}]}, - {io, fwrite, ["Bing~n"]}} +{{daily, [{1, 10, am}, {1, 07, 30, am}]}, + {io, fwrite, ["Bing~n"]}} - {{weekly, thu, {2, am}}, - {io, fwrite, ["It's 2 Thursday morning~n"]}} +{{weekly, thu, {2, am}}, + {io, fwrite, ["It's 2 Thursday morning~n"]}} - {{weekly, wed, {2, am}}, - {fun() -> io:fwrite("It's 2 Wednesday morning~n") end} +{{weekly, wed, {2, am}}, + {fun() -> io:fwrite("It's 2 Wednesday morning~n") end} - {{weekly, fri, {2, am}}, - {io, fwrite, ["It's 2 Friday morning~n"]}} +{{weekly, fri, {2, am}}, + {io, fwrite, ["It's 2 Friday morning~n"]}} - {{monthly, 1, {2, am}}, - {io, fwrite, ["First of the month!~n"]}} - - {{monthly, 4, {2, am}}, - {io, fwrite, ["Fourth of the month!~n"]}} +{{monthly, 1, {2, am}}, + {io, fwrite, ["First of the month!~n"]}} +{{monthly, 4, {2, am}}, + {io, fwrite, ["Fourth of the month!~n"]}} +``` Adding a cron to the system: - Job = {{weekly, thu, {2, am}}, - {io, fwrite, ["It's 2 Thursday morning~n"]}}. +```erlang +Job = {{weekly, thu, {2, am}}, + {io, fwrite, ["It's 2 Thursday morning~n"]}}. - erlcron:cron(Job). +erlcron:cron(Job). +``` A simple way to add a daily cron: erlcron:at({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. - erlcron:once(300, Fun). +```erlang +erlcron:once(300, Fun). +``` Cancel a running job. - erlcron:cancel(JobRef). - +```erlang +erlcron:cancel(JobRef). +``` Get the current date time of the system. - erlcron:datetime(). - +```erlang +erlcron:datetime(). +``` Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. - erlcron:set_datetime(DateTime). +```erlang +erlcron:set_datetime(DateTime). +``` Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. - erlcron:multi_set_datetime(DateTime). +```erlang +erlcron:multi_set_datetime(DateTime). +``` Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. - erlcron:multi_set_datetime(Nodes, DateTime). +```erlang +erlcron:multi_set_datetime(Nodes, DateTime). +``` + +The application cron can be pre-configured throught environment variables +in the config file that all applications can load in the Erlang VM start. +The app.config file can be as follow: + +```erlang +[ + {erlcron, [ + {crontab, [ + {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}}, + + {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}}, + + {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, + {io, fwrite, ["Hello, world!~n"]}} + + ]} + ]} +]. +``` + +So, when the app will be started, all configurations will be loaded. + +Note that the limitation is that in the config file is impossible load an +anonymous function (or lambda function) so, you only can use {M,F,A} format. diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index bf85725..3d8a948 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,50 +1,63 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> application:start(crypto), application:start(eunit), application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> + setup(), {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. + +setup() -> + case application:get_env(erlcron, crontab) of + {ok, Crontab} -> + lists:foreach(fun(CronJob) -> + erlcron:cron(CronJob) + end, Crontab); + undefined -> + ok; + Reason -> + error_logger:error_msg("Unknown crontab in configfile: ~p~n", [Reason]) + end.
erlware/erlcron
4ee8c79816c5a5fe4def94933b10b4ac0f1bee4a
support semver versioning in erlcron
diff --git a/.gitignore b/.gitignore index 13bca88..32c7afb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ ebin/*.beam ebin/*.app -.* \ No newline at end of file +.* +deps/* \ No newline at end of file diff --git a/rebar.config b/rebar.config index 5de288a..9818237 100644 --- a/rebar.config +++ b/rebar.config @@ -1,13 +1,20 @@ -%%% -*- mode: erlang -*- +%% -*- mode: Erlang; fill-column: 80; comment-column: 75; -*- +%% Dependencies ================================================================ +{deps, [{rebar_vsn_plugin, ".*", + {git, "https://github.com/erlware/rebar_vsn_plugin.git", + {tag, "master"}}}]}. + +%% Rebar Plugins ============================================================== +{plugins, [rebar_vsn_plugin]}. %% Compiler Options ============================================================ {erl_opts, [debug_info, warnings_as_errors]}. %% EUnit ======================================================================= {eunit_opts, [verbose, {report, {eunit_surefire, [{dir, "."}]}}]}. {cover_enabled, true}. {cover_print_enabled, true}. diff --git a/src/erlcron.app.src b/src/erlcron.app.src index c417c83..f227562 100644 --- a/src/erlcron.app.src +++ b/src/erlcron.app.src @@ -1,7 +1,7 @@ {application,erlcron, [{description,"Erlang Implementation of cron"}, - {vsn,"0.2"}, + {vsn,"semver"}, {modules,[]}, {registered,[ecrn_agent]}, {applications,[kernel,stdlib]}, {mod,{ecrn_app,[]}}]}.
erlware/erlcron
aecb87330f2cc0673df28f623f97ab574111f5c5
cleanup the license text
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 1d5e551..23e67d3 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,402 +1,401 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. You may obtain a -%%% copy of the License. +%%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% Types %%%=================================================================== -type state() :: record(state). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref -spec start_link/2 ::(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime/1 :: (pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel/1 :: (pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime/3 :: (pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate/1 :: (pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Validate that a run_when spec specified is correct. -spec validate/1 :: (erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %% @private handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %% @private handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %% @private terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time/1 :: (state()) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_milliseconds/2 :: (state(), erlcron:job()) -> {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. -spec until_next_time/2 :: (state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. -spec until_next_daytime/2 :: (state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @doc Calculates the last time in a given period. -spec last_time/1 :: (erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @doc Calculates the first time in a given period. -spec first_time/1 :: (erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @doc Calculates the first time in the given period after the given time. -spec next_time/2 :: (erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @doc Returns a list of times given a periodic specification. -spec resolve_period/1 :: ([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @doc Returns seconds past midnight for a given time. -spec resolve_time/1 :: (erlcron:cron_time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @doc Returns seconds for a given duration. -spec resolve_dur/1 :: (erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. -spec resolve_dow/1 :: (erlcron:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. -spec until_tomorrow/2 :: (state(), erlcron:seconds()) -> erlcron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. -spec until_days_from_now/3 :: (state(), erlcron:period(), integer()) -> erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. -spec until_next_daytime_or_days_from_now/3 :: (state(), erlcron:period(), integer()) -> erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index d55ec41..bf85725 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,51 +1,50 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. You may obtain a -%%% copy of the License. +%%% this file except in compliance with the License. %%%---------------------------------------------------------------- %%% @doc %%% erlcron app system -module(ecrn_app). -behaviour(application). %% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% start up the app and all the dependent apps. manual_start() -> application:start(crypto), application:start(eunit), application:start(sasl), application:start(erlcron). %% @doc %% stop the app manually manual_stop() -> application:stop(erlcron). %%%=================================================================== %%% Application callbacks %%%=================================================================== %% @private start(_StartType, _StartArgs) -> case ecrn_sup:start_link() of {ok, Pid} -> {ok, Pid}; Error -> Error end. %% @private stop(_State) -> ok. diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 4736dd5..944428a 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,117 +1,116 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. You may obtain a -%%% copy of the License. +%%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). -record(state, {reference_datetime :: calendar:datetime(), datetime_at_reference :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link/0 :: () -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). -spec cancel/1 :: (erlcron:job_ref()) -> ok. cancel(AlarmRef) -> gen_server:call(?SERVER, {cancel, AlarmRef}). -spec datetime/0 :: () -> {calendar:datetime(), erlcron:seconds()}. datetime() -> gen_server:call(?SERVER, get_datetime). %% @doc sets the date-time for the erlcron -spec set_datetime/1 :: (calendar:datetime()) -> ok. set_datetime(DateTime={_,_}) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc sets the date-time with the erlcron on all nodes -spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> DateTime = erlang:localtime(), {ok, #state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}}. %% @private handle_call({cancel, AlarmRef}, _From, State) -> {reply, internal_cancel(AlarmRef), State}; handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, datetime_at_reference = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}, case lists:foldl(fun({_, [Pid]}, Acc) -> ecrn_agent:set_datetime(Pid, DateTime, NewState#state.datetime_at_reference), Acc; ({Ref, X}, Acc) when is_list(X) -> [Ref | Acc] end, [], ecrn_reg:get_all()) of [] -> {reply, ok, NewState}; ErrorRefs -> {reply, {error, ErrorRefs}, NewState} end. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== internal_cancel(AlarmRef) -> case ecrn_reg:get(AlarmRef) of undefined -> undefined; {ok, [Pid]} -> {ok, ecrn_agent:cancel(Pid)} end. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index 405fbe1..dfdfde0 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,57 +1,56 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. You may obtain a -%%% copy of the License. +%%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -spec start_link/0 :: () -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc %% Add a chron job to be supervised -spec add_job/2 :: (erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). add_job(JobRef, Task) -> {ok, _} = supervisor:start_child(?SERVER, [JobRef, Task]), JobRef. %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> RestartStrategy = simple_one_for_one, MaxRestarts = 1000, MaxSecondsBetweenRestarts = 3600, SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, Restart = transient, Shutdown = 2000, Type = worker, AChild = {ecrn_agent, {ecrn_agent, start_link, []}, Restart, Shutdown, Type, [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. diff --git a/src/ecrn_reg.erl b/src/ecrn_reg.erl index 6fc541d..7e11d7c 100644 --- a/src/ecrn_reg.erl +++ b/src/ecrn_reg.erl @@ -1,169 +1,168 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. You may obtain a -%%% copy of the License. +%%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% This provides simple pid registration for the server. -module(ecrn_reg). -behaviour(gen_server). %% API -export([start_link/0, register/2, unregister/1, get/1, stop/0, get_all/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include_lib("eunit/include/eunit.hrl"). -define(SERVER, ?MODULE). -record(state, {registered}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link/0 :: () -> {ok, Pid::pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %% @doc %% Register an arbitrary value with the system, under a set of keys -spec register/2 :: (term() | [term()], term()) -> ok | {discarded_keys, [term()]}. register(Keys, Body) when is_list(Keys) -> gen_server:call(?SERVER, {register, Keys, Body}); register(Key, Body) -> gen_server:call(?SERVER, {register, [Key], Body}). %% @doc %% Remove the value registered under a que or set of keys -spec unregister/1 :: (term() | [term()]) -> ok. unregister(Keys) when is_list(Keys) -> gen_server:call(?SERVER, {unregister, Keys}); unregister(Key) -> gen_server:call(?SERVER, {unregister, [Key]}). %% @doc %% Get a value buy key. -spec get/1 :: (term()) -> {ok, term()} | undefined. get(Key) -> gen_server:call(?SERVER, {get, Key}). %% @doc %% Get all the values. -spec get_all/0 :: () -> [{term(), term()}]. get_all() -> gen_server:call(?SERVER, get_all). %% @doc %% stop this server -spec stop/0 :: () -> ok. stop() -> gen_server:call(?SERVER, stop). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> {ok, #state{registered=dict:new()}}. %% @private handle_call({register, Keys, Body}, _From, #state{registered=Dict}) -> {Result, Dict2} = add_for_keys(Keys, Body, Dict, ok), {reply, Result, #state{registered=Dict2}}; handle_call({unregister, Keys}, _From, #state{registered=Dict}) -> Dict2 = remove_for_keys(Keys, Dict), {reply, ok, #state{registered=Dict2}}; handle_call({get, Key}, _From, State = #state{registered=Dict}) -> Value = get_for_key(Key, Dict), {reply, Value, State}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; handle_call(get_all, _From, State = #state{registered=Dict}) -> {reply, dict:to_list(Dict), State}. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== discarded_keys(Key, {discarded_keys, Keys}) -> {discarded_keys, [Key | Keys]}; discarded_keys(Key, ok) -> {discarded_keys, [Key]}. add_for_keys([Key | Rest], Body, Dict, Result) -> case dict:find(Key, Dict) of error -> add_for_keys(Rest, Body, dict:append(Key, Body, Dict), Result); _Value -> add_for_keys(Rest, Body, dict:append(Key, Body, Dict), discarded_keys(Key, Result)) end; add_for_keys([], _, Dict, Result) -> {Result, Dict}. remove_for_keys([Key | Rest], Dict) -> remove_for_keys(Rest, dict:erase(Key, Dict)); remove_for_keys([],Dict) -> Dict. get_for_key(Key, Dict) -> case dict:find(Key, Dict) of error -> undefined; Value -> Value end. %%%=================================================================== %%% Tests %%%=================================================================== generate_test_() -> {setup, fun () -> ecrn_reg:start_link() end, fun (_) -> ecrn_reg:stop() end, {with, [fun general_tests/1]}}. general_tests(_) -> ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch({ok, [boo]}, ecrn_reg:get(a)), ecrn_reg:unregister([a, b]), ?assertMatch(undefined, ecrn_reg:get(a)), ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch(ok, ecrn_reg:register([c, d], boo2)), ?assertMatch({ok, [boo2]}, ecrn_reg:get(c)), ?assertMatch({ok, [boo]}, ecrn_reg:get(b)), ?assertMatch({discarded_keys, [d, c]}, ecrn_reg:register([c, d], boo2)). diff --git a/src/ecrn_test.erl b/src/ecrn_test.erl index 6595aa1..612ab37 100644 --- a/src/ecrn_test.erl +++ b/src/ecrn_test.erl @@ -1,167 +1,166 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. You may obtain a -%%% copy of the License. +%%% this file except in compliance with the License. -module(ecrn_test). -include_lib("eunit/include/eunit.hrl"). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> ecrn_app:manual_start() end, fun(_) -> ecrn_app:manual_stop() end, {with, [fun set_alarm_test/1, fun travel_back_in_time_test/1, fun cancel_alarm_test/1, fun big_time_jump_test/1, fun cron_test/1, fun validation_test/1]}}. set_alarm_test(_) -> EpochDay = {2000,1,1}, EpochDateTime = {EpochDay,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({EpochDay, {8, 59, 59}}), %% The alarm should trigger this nearly immediately. ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), %% The alarm should trigger this 1 second later. ?assertMatch(ok, receive ack2 -> ok after 2500 -> timeout end). cancel_alarm_test(_) -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(ok, receive ack -> ack after %% There is no event-driven way to %% ensure we never receive an ack. 125 -> ok end). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump_test(_) -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack2 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack2 -> ok after 2500 -> timeout end). travel_back_in_time_test(_) -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assertMatch(true, ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), ?assertMatch(true, ExpectedSeconds < Seconds). %% Time jumps ahead one day so we should see the alarms from both days. cron_test(_) -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,58}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Job = {{daily, {3, 30, pm}}, fun(_, _) -> Self ! ack end}, erlcron:cron(Job), ?assertMatch(ok, receive ack -> ok after 2500 -> timeout end). validation_test(_) -> ?assertMatch(valid, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(valid, ecrn_agent:validate({once, 3600})), ?assertMatch(valid, ecrn_agent:validate({daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(valid, ecrn_agent:validate({daily, {3, 30, pm}})), ?assertMatch(valid, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({monthly, 4, {2, am}})), ?assertMatch(invalid, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch(invalid, ecrn_agent:validate({monthly, 65, {55, am}})). %%%=================================================================== %%% Internal Functions %%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). diff --git a/src/ecrn_util.erl b/src/ecrn_util.erl index e06588b..67ee86e 100644 --- a/src/ecrn_util.erl +++ b/src/ecrn_util.erl @@ -1,19 +1,18 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. You may obtain a -%%% copy of the License. +%%% this file except in compliance with the License. %%%------------------------------------------------------------------- %%% @doc %%% Utility functions for the erlcron system -module(ecrn_util). -export([epoch_seconds/0]). %%%=================================================================== %%% API %%%=================================================================== -spec epoch_seconds/0 :: () -> erlcron:seconds(). epoch_seconds() -> {Megasecs, Secs, Microsecs} = erlang:now(), erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)). diff --git a/src/internal.hrl b/src/internal.hrl index 7fd1779..29de9ae 100644 --- a/src/internal.hrl +++ b/src/internal.hrl @@ -1,6 +1,5 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use -%%% this file except in compliance with the License. You may obtain a -%%% copy of the License. +%%% this file except in compliance with the License. -define(ONE_DAY, (24 * 60 * 60)).
erlware/erlcron
5d21270faf2ef2d8d586b1df28f0f6c32001c888
bring cron specs up to the new erlware standard
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index f098d6b..1d5e551 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,403 +1,402 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. You may obtain a %%% copy of the License. %%%------------------------------------------------------------------- %%% @doc %%% Agent for cronish testing -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% Types %%%=================================================================== -type state() :: record(state). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Starts the server with the apropriate job and the appropriate ref --spec start_link(erlcron:job_ref(), erlcron:job()) -> - ignore | {error, Reason::term()} | {ok, pid()}. +-spec start_link/2 ::(erlcron:job_ref(), erlcron:job()) -> + ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). --spec get_datetime(pid()) -> calendar:datetime(). +-spec get_datetime/1 :: (pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). --spec cancel(pid()) -> ok. +-spec cancel/1 :: (pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). --spec set_datetime(pid(), calendar:datetime(), erlcron:seconds()) -> ok. +-spec set_datetime/3 :: (pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). --spec recalculate(pid()) -> ok. +-spec recalculate/1 :: (pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %% @doc %% Validate that a run_when spec specified is correct. --spec validate(erlcron:run_when()) -> valid | invalid. +-spec validate/1 :: (erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %% @private handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %% @private handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %% @private handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %% @private terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. --spec current_time(state()) -> erlcron:seconds(). +-spec current_time/1 :: (state()) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. - current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). - %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. --spec until_next_milliseconds(state(), erlcron:job()) -> - {ok, erlcron:seconds()} | {error, invalid_one_exception}. +-spec until_next_milliseconds/2 :: (state(), erlcron:job()) -> + {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. --spec until_next_time(state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). +-spec until_next_time/2 :: (state(), {erlcron:run_when(), term()}) -> + erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. --spec until_next_daytime(state(), erlcron:period()) -> erlcron:seconds(). +-spec until_next_daytime/2 :: (state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @doc Calculates the last time in a given period. --spec last_time(erlcron:period()) -> erlcron:seconds(). +-spec last_time/1 :: (erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @doc Calculates the first time in a given period. --spec first_time(erlcron:period()) -> erlcron:seconds(). +-spec first_time/1 :: (erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @doc Calculates the first time in the given period after the given time. --spec next_time(erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). +-spec next_time/2 :: (erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @doc Returns a list of times given a periodic specification. --spec resolve_period([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. +-spec resolve_period/1 :: ([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @doc Returns seconds past midnight for a given time. --spec resolve_time(erlcron:cron_time()) -> erlcron:seconds(). +-spec resolve_time/1 :: (erlcron:cron_time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @doc Returns seconds for a given duration. --spec resolve_dur(erlcron:duration()) -> erlcron:seconds(). +-spec resolve_dur/1 :: (erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. --spec resolve_dow(erlcron:dow()) -> integer(). +-spec resolve_dow/1 :: (erlcron:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. --spec until_tomorrow(state(), erlcron:seconds()) -> erlcron:seconds(). +-spec until_tomorrow/2 :: (state(), erlcron:seconds()) -> erlcron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. --spec until_days_from_now(state(), erlcron:period(), integer()) -> - erlcron:seconds(). +-spec until_days_from_now/3 :: (state(), erlcron:period(), integer()) -> + erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. --spec until_next_daytime_or_days_from_now(state(), erlcron:period(), integer()) -> - erlcron:seconds(). +-spec until_next_daytime_or_days_from_now/3 :: (state(), erlcron:period(), integer()) -> + erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 830c123..4736dd5 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,114 +1,117 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. You may obtain a %%% copy of the License. %%%------------------------------------------------------------------- %%% @doc %%% Provides testing/fast forward control for the system -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("internal.hrl"). -record(state, {reference_datetime :: calendar:datetime(), datetime_at_reference :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== --spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. +-spec start_link/0 :: () -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). +-spec cancel/1 :: (erlcron:job_ref()) -> ok. cancel(AlarmRef) -> gen_server:call(?SERVER, {cancel, AlarmRef}). --spec datetime() -> {calendar:datetime(), erlcron:seconds()}. +-spec datetime/0 :: () -> {calendar:datetime(), erlcron:seconds()}. datetime() -> gen_server:call(?SERVER, get_datetime). %% @doc sets the date-time for the erlcron +-spec set_datetime/1 :: (calendar:datetime()) -> ok. set_datetime(DateTime={_,_}) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc sets the date-time with the erlcron on all nodes +-spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> DateTime = erlang:localtime(), {ok, #state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}}. %% @private handle_call({cancel, AlarmRef}, _From, State) -> {reply, internal_cancel(AlarmRef), State}; handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, datetime_at_reference = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{reference_datetime=DateTime, datetime_at_reference=ecrn_util:epoch_seconds()}, case lists:foldl(fun({_, [Pid]}, Acc) -> ecrn_agent:set_datetime(Pid, DateTime, NewState#state.datetime_at_reference), Acc; ({Ref, X}, Acc) when is_list(X) -> [Ref | Acc] end, [], ecrn_reg:get_all()) of [] -> {reply, ok, NewState}; ErrorRefs -> {reply, {error, ErrorRefs}, NewState} end. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== internal_cancel(AlarmRef) -> case ecrn_reg:get(AlarmRef) of undefined -> undefined; {ok, [Pid]} -> {ok, ecrn_agent:cancel(Pid)} end. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index 2936f6e..405fbe1 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,57 +1,57 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. You may obtain a %%% copy of the License. %%%------------------------------------------------------------------- %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, add_job/2]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== --spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. +-spec start_link/0 :: () -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %% @doc %% Add a chron job to be supervised --spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). +-spec add_job/2 :: (erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). add_job(JobRef, Task) -> {ok, _} = supervisor:start_child(?SERVER, [JobRef, Task]), JobRef. %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> RestartStrategy = simple_one_for_one, MaxRestarts = 1000, MaxSecondsBetweenRestarts = 3600, SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, Restart = transient, Shutdown = 2000, Type = worker, AChild = {ecrn_agent, {ecrn_agent, start_link, []}, Restart, Shutdown, Type, [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. diff --git a/src/ecrn_reg.erl b/src/ecrn_reg.erl index 75c0d1d..6fc541d 100644 --- a/src/ecrn_reg.erl +++ b/src/ecrn_reg.erl @@ -1,169 +1,169 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. You may obtain a %%% copy of the License. %%%------------------------------------------------------------------- %%% @doc %%% This provides simple pid registration for the server. -module(ecrn_reg). -behaviour(gen_server). %% API -export([start_link/0, register/2, unregister/1, get/1, stop/0, get_all/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include_lib("eunit/include/eunit.hrl"). -define(SERVER, ?MODULE). -record(state, {registered}). %%%=================================================================== %%% API %%%=================================================================== --spec start_link() -> {ok, Pid::pid()} | ignore | {error, Error::term()}. +-spec start_link/0 :: () -> {ok, Pid::pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %% @doc %% Register an arbitrary value with the system, under a set of keys --spec register(term() | [term()], term()) -> ok | {discarded_keys, [term()]}. +-spec register/2 :: (term() | [term()], term()) -> ok | {discarded_keys, [term()]}. register(Keys, Body) when is_list(Keys) -> gen_server:call(?SERVER, {register, Keys, Body}); register(Key, Body) -> gen_server:call(?SERVER, {register, [Key], Body}). %% @doc %% Remove the value registered under a que or set of keys --spec unregister(term() | [term()]) -> ok. +-spec unregister/1 :: (term() | [term()]) -> ok. unregister(Keys) when is_list(Keys) -> gen_server:call(?SERVER, {unregister, Keys}); unregister(Key) -> gen_server:call(?SERVER, {unregister, [Key]}). %% @doc %% Get a value buy key. --spec get(term()) -> {ok, term()} | undefined. +-spec get/1 :: (term()) -> {ok, term()} | undefined. get(Key) -> gen_server:call(?SERVER, {get, Key}). %% @doc %% Get all the values. --spec get_all() -> [{term(), term()}]. +-spec get_all/0 :: () -> [{term(), term()}]. get_all() -> gen_server:call(?SERVER, get_all). %% @doc %% stop this server --spec stop() -> ok. +-spec stop/0 :: () -> ok. stop() -> gen_server:call(?SERVER, stop). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private init([]) -> {ok, #state{registered=dict:new()}}. %% @private handle_call({register, Keys, Body}, _From, #state{registered=Dict}) -> {Result, Dict2} = add_for_keys(Keys, Body, Dict, ok), {reply, Result, #state{registered=Dict2}}; handle_call({unregister, Keys}, _From, #state{registered=Dict}) -> Dict2 = remove_for_keys(Keys, Dict), {reply, ok, #state{registered=Dict2}}; handle_call({get, Key}, _From, State = #state{registered=Dict}) -> Value = get_for_key(Key, Dict), {reply, Value, State}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; handle_call(get_all, _From, State = #state{registered=Dict}) -> {reply, dict:to_list(Dict), State}. %% @private handle_cast(_Msg, State) -> {noreply, State}. %% @private handle_info(_Info, State) -> {noreply, State}. %% @private terminate(_Reason, _State) -> ok. %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== discarded_keys(Key, {discarded_keys, Keys}) -> {discarded_keys, [Key | Keys]}; discarded_keys(Key, ok) -> {discarded_keys, [Key]}. add_for_keys([Key | Rest], Body, Dict, Result) -> case dict:find(Key, Dict) of error -> add_for_keys(Rest, Body, dict:append(Key, Body, Dict), Result); _Value -> add_for_keys(Rest, Body, dict:append(Key, Body, Dict), discarded_keys(Key, Result)) end; add_for_keys([], _, Dict, Result) -> {Result, Dict}. remove_for_keys([Key | Rest], Dict) -> remove_for_keys(Rest, dict:erase(Key, Dict)); remove_for_keys([],Dict) -> Dict. get_for_key(Key, Dict) -> case dict:find(Key, Dict) of error -> undefined; Value -> Value end. %%%=================================================================== %%% Tests %%%=================================================================== generate_test_() -> {setup, fun () -> ecrn_reg:start_link() end, fun (_) -> ecrn_reg:stop() end, {with, [fun general_tests/1]}}. general_tests(_) -> ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch({ok, [boo]}, ecrn_reg:get(a)), ecrn_reg:unregister([a, b]), ?assertMatch(undefined, ecrn_reg:get(a)), ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch(ok, ecrn_reg:register([c, d], boo2)), ?assertMatch({ok, [boo2]}, ecrn_reg:get(c)), ?assertMatch({ok, [boo]}, ecrn_reg:get(b)), ?assertMatch({discarded_keys, [d, c]}, ecrn_reg:register([c, d], boo2)). diff --git a/src/ecrn_sup.erl b/src/ecrn_sup.erl index 2544f4e..4c56815 100644 --- a/src/ecrn_sup.erl +++ b/src/ecrn_sup.erl @@ -1,46 +1,46 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(ecrn_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== --spec start_link() -> {ok, Pid::term()} | ignore | {error, Error::term()}. +-spec start_link/0 :: () -> {ok, Pid::term()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== %% @private init([]) -> RestartStrategy = one_for_one, MaxRestarts = 3, MaxSecondsBetweenRestarts = 10, SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, ChildSup = {ecrn_cron_sup, {ecrn_cron_sup, start_link, []}, permanent, 1000, supervisor, [ecrn_cron_sup]}, RegistrationServer = {ecrn_reg_server, {ecrn_reg, start_link, []}, permanent, 1000, worker, [ecrn_reg]}, BroadcastServer = {ecrn_control, {ecrn_control, start_link, []}, permanent, 1000, worker, [ecrn_control]}, {ok, {SupFlags, [ChildSup, RegistrationServer, BroadcastServer]}}. diff --git a/src/ecrn_test.erl b/src/ecrn_test.erl index c05cc8a..6595aa1 100644 --- a/src/ecrn_test.erl +++ b/src/ecrn_test.erl @@ -1,169 +1,167 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. You may obtain a %%% copy of the License. -module(ecrn_test). -include_lib("eunit/include/eunit.hrl"). %%%=================================================================== %%% Types %%%=================================================================== cron_test_() -> {setup, fun() -> ecrn_app:manual_start() end, fun(_) -> ecrn_app:manual_stop() end, {with, [fun set_alarm_test/1, fun travel_back_in_time_test/1, fun cancel_alarm_test/1, fun big_time_jump_test/1, fun cron_test/1, fun validation_test/1]}}. set_alarm_test(_) -> EpochDay = {2000,1,1}, EpochDateTime = {EpochDay,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({EpochDay, {8, 59, 59}}), %% The alarm should trigger this nearly immediately. ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), %% The alarm should trigger this 1 second later. ?assertMatch(ok, receive ack2 -> ok after 2500 -> timeout end). cancel_alarm_test(_) -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(ok, receive ack -> ack after %% There is no event-driven way to %% ensure we never receive an ack. 125 -> ok end). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump_test(_) -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack2 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack2 -> ok after 2500 -> timeout end). travel_back_in_time_test(_) -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assertMatch(true, ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), ?assertMatch(true, ExpectedSeconds < Seconds). %% Time jumps ahead one day so we should see the alarms from both days. cron_test(_) -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,58}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Job = {{daily, {3, 30, pm}}, fun(_, _) -> Self ! ack end}, erlcron:cron(Job), ?assertMatch(ok, receive ack -> ok after 2500 -> timeout end). validation_test(_) -> ?assertMatch(valid, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(valid, ecrn_agent:validate({once, 3600})), ?assertMatch(valid, ecrn_agent:validate({daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(valid, ecrn_agent:validate({daily, {3, 30, pm}})), ?assertMatch(valid, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({monthly, 4, {2, am}})), ?assertMatch(invalid, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch(invalid, ecrn_agent:validate({monthly, 65, {55, am}})). - - %%%=================================================================== %%% Internal Functions %%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). diff --git a/src/ecrn_util.erl b/src/ecrn_util.erl index 9e80206..e06588b 100644 --- a/src/ecrn_util.erl +++ b/src/ecrn_util.erl @@ -1,19 +1,19 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. You may obtain a %%% copy of the License. %%%------------------------------------------------------------------- %%% @doc %%% Utility functions for the erlcron system -module(ecrn_util). -export([epoch_seconds/0]). %%%=================================================================== %%% API %%%=================================================================== --spec epoch_seconds() -> erlcron:seconds(). +-spec epoch_seconds/0 :: () -> erlcron:seconds(). epoch_seconds() -> {Megasecs, Secs, Microsecs} = erlang:now(), erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)). diff --git a/src/erlcron.erl b/src/erlcron.erl index 9031fb6..7b8ab51 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,120 +1,120 @@ %%% @copyright Erlware, LLC. All Rights Reserved. %%% %%% This file is provided to you under the BSD License; you may not use %%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | min | sec}. -type period() :: cron_time() | {every, duration(), constraint()}. -type dom() :: integer(). -type dow() :: mon | tue | wed | thu | fri | sat | sun. -type callable() :: mfa() | function(). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom(), period()}. -type job() :: {run_when(), callable()}. %% should be opaque but dialyzer does not allow it -type job_ref() :: reference(). %%%=================================================================== %%% API %%%=================================================================== %% @doc %% Check that the spec specified is valid or invalid --spec validate(run_when()) -> valid | invalid. +-spec validate/1 :: (run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. --spec cron(job()) -> job_ref(). +-spec cron/1 :: (job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job). %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. --spec at(cron_time() | seconds(), function()) -> job_ref(). +-spec at/2 :: (cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %% @doc %% Run the specified job once after the amount of time specifed. --spec once(cron_time() | seconds(), function()) -> job_ref(). +-spec once/2 :: (cron_time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %% @doc %% Cancel the job specified by the jobref. --spec cancel(job_ref()) -> ok. +-spec cancel/1 :: (job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). %% @doc %% Get the current date time of the running erlcron system. --spec datetime() -> {calendar:datetime(), seconds()}. +-spec datetime/0 :: () -> {calendar:datetime(), seconds()}. datetime() -> ecrn_control:datetime(). %% @doc %% Set the current date time of the running erlcron system. --spec set_datetime(calendar:datetime()) -> ok. +-spec set_datetime/1 :: (calendar:datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %% @doc %% Set the current date time of the erlcron system running on different nodes. --spec multi_set_datetime(calendar:datetime()) -> ok. +-spec multi_set_datetime/1 :: (calendar:datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes --spec multi_set_datetime([node()], calendar:datetime()) -> ok. +-spec multi_set_datetime/2 :: ([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
c83f371daaa5ab1429dd11dcc2578f7391251d68
Change .app file loading to use rebar and remove SASL and eunit runtime dependency
diff --git a/ebin/erlcron.app b/ebin/erlcron.app deleted file mode 100644 index 2f154eb..0000000 --- a/ebin/erlcron.app +++ /dev/null @@ -1,8 +0,0 @@ -{application,erlcron, - [{description,"Erlang Implementation of cron"}, - {vsn,"0.2"}, - {modules,[ecrn_agent,ecrn_app,ecrn_control,ecrn_cron_sup, - ecrn_reg,ecrn_sup,ecrn_test,ecrn_util,erlcron]}, - {registered,[ecrn_agent]}, - {applications,[kernel,stdlib,sasl,eunit]}, - {mod,{ecrn_app,[]}}]}. diff --git a/src/erlcron.app.src b/src/erlcron.app.src index 6af2965..c417c83 100644 --- a/src/erlcron.app.src +++ b/src/erlcron.app.src @@ -1,13 +1,7 @@ -%% -*- Erlang -*- - -{application, erlcron, - [{description, "Erlang Implementation of cron"}, - {vsn, "0.2"}, - {modules, []}, - {registered, [ecrn_agent]}, - {applications, [kernel, - stdlib, - sasl, - eunit]}, - {mod, - {ecrn_app, []}}]}. +{application,erlcron, + [{description,"Erlang Implementation of cron"}, + {vsn,"0.2"}, + {modules,[]}, + {registered,[ecrn_agent]}, + {applications,[kernel,stdlib]}, + {mod,{ecrn_app,[]}}]}.
erlware/erlcron
4a886045ecbe9087f05dd0ca6d20a4dd1bad5334
remove invalid comment from app.src file
diff --git a/src/erlcron.app.src b/src/erlcron.app.src index 7ac033c..6af2965 100644 --- a/src/erlcron.app.src +++ b/src/erlcron.app.src @@ -1,14 +1,13 @@ %% -*- Erlang -*- -%% This is the application resource file (.app file) for the ecd_ops application. {application, erlcron, [{description, "Erlang Implementation of cron"}, {vsn, "0.2"}, {modules, []}, {registered, [ecrn_agent]}, {applications, [kernel, stdlib, sasl, eunit]}, {mod, {ecrn_app, []}}]}.
erlware/erlcron
2bd7fd2c5aef1d51e58d1c8e353ddfb341473767
add travis-ci support to the system
diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..92eb51f --- /dev/null +++ b/.travis.yml @@ -0,0 +1,10 @@ +language: erlang +otp_release: + - R15B02 + - R15B01 + - R15B +script: "make rebuild" +branches: + only: + - master + - next \ No newline at end of file
erlware/erlcron
ac9c0f718e1458658745d6ecaae490fb15bbcfe5
refactorings and generalized cleanup to standardize erlcron
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 1f60475..f098d6b 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,480 +1,403 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. You may obtain a +%%% copy of the License. %%%------------------------------------------------------------------- -%%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Agent for cronish testing -%%% @end -%%%------------------------------------------------------------------- -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, - cancel/1, - get_datetime/1, - set_datetime/3, - recalculate/1, - validate/1]). + cancel/1, + get_datetime/1, + set_datetime/3, + recalculate/1, + validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, - terminate/2, code_change/3]). + terminate/2, code_change/3]). --include("erlcron-internal.hrl"). +-include("internal.hrl"). -record(state, {job, - alarm_ref, - referenced_seconds, - seconds_at_reference, - timeout_type, - fast_forward=false}). + alarm_ref, + referenced_seconds, + seconds_at_reference, + timeout_type, + fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% Types %%%=================================================================== -type state() :: record(state). %%%=================================================================== %%% API %%%=================================================================== -%%-------------------------------------------------------------------- %% @doc %% Starts the server with the apropriate job and the appropriate ref -%% @end -%%-------------------------------------------------------------------- -spec start_link(erlcron:job_ref(), erlcron:job()) -> ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). -%%-------------------------------------------------------------------- %% @doc %% Validate that a run_when spec specified is correct. -%% @end -%%-------------------------------------------------------------------- -spec validate(erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, - alarm_ref=undefined}, + alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try - until_next_time(NewState, {Spec, undefined}), - valid + until_next_time(NewState, {Spec, undefined}), + valid catch - _Error:_Reason -> - erlang:display(erlang:get_stacktrace()), - invalid + _Error:_Reason -> + invalid end. - %%%=================================================================== %%% gen_server callbacks %%%=================================================================== -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Initiates the server -%% -%% @spec init(Args) -> {ok, State} | -%% {ok, State, Timeout} | -%% ignore | -%% {stop, Reason} -%% @end -%%-------------------------------------------------------------------- init([JobRef, Job]) -> State = #state{job=Job, - alarm_ref=JobRef}, + alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of - {ok, Millis} when is_integer(Millis) -> - ecrn_reg:register(JobRef, self()), - {ok, NewState, Millis}; - {error, _} -> - {stop, normal} + {ok, Millis} when is_integer(Millis) -> + ecrn_reg:register(JobRef, self()), + {ok, NewState, Millis}; + {error, _} -> + {stop, normal} end. - - -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling call messages -%% -%% @spec handle_call(Request, From, State) -> -%% {reply, Reply, State} | -%% {reply, Reply, State, Timeout} | -%% {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, Reply, State} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of - {ok, Millis} -> - {reply, ok, State, Millis}; - {error, _} -> - {stop, normal, ok, State} + {ok, Millis} -> + {reply, ok, State, Millis}; + {error, _} -> + {stop, normal, ok, State} end. - -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling cast messages -%% -%% @spec handle_cast(Msg, State) -> {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of - {ok, Millis} -> - {noreply, NewState, Millis}; - {error, _} -> - {stop, normal, NewState} + {ok, Millis} -> + {noreply, NewState, Millis}; + {error, _} -> + {stop, normal, NewState} end. - - -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling all non call/cast messages -%% -%% @spec handle_info(Info, State) -> {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of - {ok, Millis} -> - {noreply, NewState, Millis}; - {error, _} -> - {stop, normal, NewState} + {ok, Millis} -> + {noreply, NewState, Millis}; + {error, _} -> + {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. - -%%-------------------------------------------------------------------- %% @private -%% @doc -%% This function is called by a gen_server when it is about to -%% terminate. It should be the opposite of Module:init/1 and do any -%% necessary cleaning up. When it returns, the gen_server terminates -%% with Reason. The return value is ignored. -%% -%% @spec terminate(Reason, State) -> void() -%% @end -%%-------------------------------------------------------------------- terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Convert process state when code is changed -%% -%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} -%% @end -%%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== -do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> + +do_job_run(State, {_, Job}) + when is_record(State, state), is_function(Job) -> RunFun = fun() -> - Job(State#state.alarm_ref, current_date(State)) - end, + Job(State#state.alarm_ref, current_date(State)) + end, proc_lib:spawn(RunFun); -do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> +do_job_run(State, {_, {M, F, A}}) + when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. --spec current_time(record(state)) -> erlcron:seconds(). +-spec current_time(state()) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> - Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, + Elapsed = ecrn_util:epoch_seconds() - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + - State#state.referenced_seconds)). + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_milliseconds(state(), erlcron:job()) -> {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try - Millis = until_next_time(State, Job) * ?MILLISECONDS, - {ok, Millis} + Millis = until_next_time(State, Job) * ?MILLISECONDS, + {ok, Millis} catch - throw:invalid_once_exception -> - {error, invalid_once_exception} + throw:invalid_once_exception -> + {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of - Value when Value >= 0 -> - Value; - _ -> - erlang:display(erlang:get_stacktrace()), - throw(invalid_once_exception) + Value when Value >= 0 -> + Value; + _ -> + erlang:display(erlang:get_stacktrace()), + throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. -spec until_next_time(state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of - OnDay -> - until_next_daytime_or_days_from_now(State, Period, 7); - Today when Today < OnDay -> - until_days_from_now(State, Period, OnDay - Today); - Today when Today > OnDay -> - until_days_from_now(State, Period, (OnDay+7) - Today) + OnDay -> + until_next_daytime_or_days_from_now(State, Period, 7); + Today when Today < OnDay -> + until_days_from_now(State, Period, OnDay - Today); + Today when Today > OnDay -> + until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = - case ThisMonth of - 12 -> - {ThisYear + 1, 1}; - _ -> - {ThisYear, ThisMonth + 1} - end, + case ThisMonth of + 12 -> + {ThisYear + 1, 1}; + _ -> + {ThisYear, ThisMonth + 1} + end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of - DoM -> - until_next_daytime_or_days_from_now(State, Period, Days); - _ -> - until_days_from_now(State, Period, Days) + DoM -> + until_next_daytime_or_days_from_now(State, Period, Days); + _ -> + until_days_from_now(State, Period, Days) end. - - %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. --spec until_next_daytime(erlcron:state(), erlcron:period()) -> erlcron:seconds(). +-spec until_next_daytime(state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of - T when T > EndTime -> - until_tomorrow(State, StartTime); - T -> - next_time(Period, T) - T + T when T > EndTime -> + until_tomorrow(State, StartTime); + T -> + next_time(Period, T) - T end. - %% @doc Calculates the last time in a given period. -spec last_time(erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @doc Calculates the first time in a given period. -spec first_time(erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @doc Calculates the first time in the given period after the given time. -spec next_time(erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> - case X of - T when T >= Time, T < A -> - T; - _ -> - A - end - end, 24*3600, R). - + case X of + T when T >= Time, T < A -> + T; + _ -> + A + end + end, 24*3600, R). %% @doc Returns a list of times given a periodic specification. -spec resolve_period([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @doc Returns seconds past midnight for a given time. --spec resolve_time(duration:time()) -> erlcron:seconds(). +-spec resolve_time(erlcron:cron_time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @doc Returns seconds for a given duration. -spec resolve_dur(erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. --spec resolve_dow(erlang:dow()) -> integer(). +-spec resolve_dow(erlcron:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. --spec until_tomorrow(state(), erlcron:seconds()) -> ercron:seconds(). +-spec until_tomorrow(state(), erlcron:seconds()) -> erlcron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. -spec until_days_from_now(state(), erlcron:period(), integer()) -> erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. -spec until_next_daytime_or_days_from_now(state(), erlcron:period(), integer()) -> erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of - T when T < CurrentTime -> - until_days_from_now(State, Period, Days-1); - _ -> - until_next_daytime(State, Period) + T when T < CurrentTime -> + until_days_from_now(State, Period, Days-1); + _ -> + until_next_daytime(State, Period) end. - - set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, - seconds_at_reference=CurrentSeconds}. + seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try - Seconds = until_next_time(State, State#state.job), - NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), - Span = NewSeconds - State#state.referenced_seconds, - case Span > Seconds of - true -> - RefSecs = State#state.referenced_seconds, - NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, - do_job_run(State, State#state.job), - fast_forward(NewState, NewDate); - false -> - ok - end + Seconds = until_next_time(State, State#state.job), + NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), + Span = NewSeconds - State#state.referenced_seconds, + case Span > Seconds of + true -> + RefSecs = State#state.referenced_seconds, + NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, + do_job_run(State, State#state.job), + fast_forward(NewState, NewDate); + false -> + ok + end catch - throw:invalid_once_exception -> - {error, invalid_once_exception} + throw:invalid_once_exception -> + {error, invalid_once_exception} end. - - - - diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl index 16cd493..d55ec41 100644 --- a/src/ecrn_app.erl +++ b/src/ecrn_app.erl @@ -1,79 +1,51 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. You may obtain a +%%% copy of the License. %%%---------------------------------------------------------------- -%%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @doc %%% erlcron app system -%%% @end -%%%----------------------------------------------------------------, -module(ecrn_app). -behaviour(application). +%% API -export([manual_start/0, manual_stop/0]). %% Application callbacks -export([start/2, stop/1]). %%%=================================================================== -%%% Application callbacks +%%% API %%%=================================================================== -%%-------------------------------------------------------------------- -%% @private -%% @doc -%% This function is called whenever an application is started using -%% application:start/[1,2], and should start the processes of the -%% application. If the application is structured according to the OTP -%% design principles as a supervision tree, this means starting the -%% top supervisor of the tree. -%% -%% @spec start(StartType, StartArgs) -> {ok, Pid} | -%% {ok, Pid, State} | -%% {error, Reason} -%% StartType = normal | {takeover, Node} | {failover, Node} -%% StartArgs = term() -%% @end -%%-------------------------------------------------------------------- - -start(_StartType, _StartArgs) -> - case ecrn_sup:start_link() of - {ok, Pid} -> - {ok, Pid}; - Error -> - Error - end. - -%%-------------------------------------------------------------------- -%% @private -%% @doc -%% This function is called whenever an application has stopped. It -%% is intended to be the opposite of Module:start/2 and should do -%% any necessary cleaning up. The return value is ignored. -%% -%% @spec stop(State) -> void() -%% @end -%%-------------------------------------------------------------------- -stop(_State) -> - ok. - -%% %% @doc %% start up the app and all the dependent apps. -%% @end -%% manual_start() -> application:start(crypto), application:start(eunit), application:start(sasl), application:start(erlcron). -%% %% @doc %% stop the app manually -%% @end -%% manual_stop() -> application:stop(erlcron). %%%=================================================================== -%%% Internal functions +%%% Application callbacks %%%=================================================================== + +%% @private +start(_StartType, _StartArgs) -> + case ecrn_sup:start_link() of + {ok, Pid} -> + {ok, Pid}; + Error -> + Error + end. + +%% @private +stop(_State) -> + ok. diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 7c7e2df..830c123 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,174 +1,114 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. You may obtain a +%%% copy of the License. %%%------------------------------------------------------------------- -%%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Provides testing/fast forward control for the system -%%% @end -%%%------------------------------------------------------------------- -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, - cancel/1, - datetime/0, - set_datetime/1, - multi_set_datetime/2]). + cancel/1, + datetime/0, + set_datetime/1, + multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, - terminate/2, code_change/3]). + terminate/2, code_change/3]). -define(SERVER, ?MODULE). --include("erlcron-internal.hrl"). +-include("internal.hrl"). --record(state, {reference_datetime, datetime_at_reference}). +-record(state, {reference_datetime :: calendar:datetime(), + datetime_at_reference :: erlcron:seconds()}). %%%=================================================================== %%% API %%%=================================================================== -%%-------------------------------------------------------------------- -%% @doc -%% Starts the server -%% -%% @spec start_link() -> {ok, Pid} | ignore | {error, Error} -%% @end -%%-------------------------------------------------------------------- +-spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). cancel(AlarmRef) -> gen_server:call(?SERVER, {cancel, AlarmRef}). -spec datetime() -> {calendar:datetime(), erlcron:seconds()}. datetime() -> gen_server:call(?SERVER, get_datetime). %% @doc sets the date-time for the erlcron set_datetime(DateTime={_,_}) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc sets the date-time with the erlcron on all nodes multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Initiates the server -%% -%% @spec init(Args) -> {ok, State} | -%% {ok, State, Timeout} | -%% ignore | -%% {stop, Reason} -%% @end -%%-------------------------------------------------------------------- init([]) -> DateTime = erlang:localtime(), - {ok, #state{reference_datetime=DateTime, datetime_at_reference=?EPOC_SECONDS}}. + {ok, #state{reference_datetime=DateTime, + datetime_at_reference=ecrn_util:epoch_seconds()}}. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling call messages -%% -%% @spec handle_call(Request, From, State) -> -%% {reply, Reply, State} | -%% {reply, Reply, State, Timeout} | -%% {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, Reply, State} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_call({cancel, AlarmRef}, _From, State) -> {reply, internal_cancel(AlarmRef), State}; handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, - datetime_at_reference = Actual}) -> + datetime_at_reference = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{reference_datetime=DateTime, - datetime_at_reference=?EPOC_SECONDS}, + datetime_at_reference=ecrn_util:epoch_seconds()}, case lists:foldl(fun({_, [Pid]}, Acc) -> - ecrn_agent:set_datetime(Pid, DateTime, - NewState#state.datetime_at_reference), - Acc; - ({Ref, X}, Acc) when is_list(X) -> - [Ref | Acc] - end, - [], - ecrn_reg:get_all()) of - [] -> - {reply, ok, NewState}; - ErrorRefs -> - {reply, {error, ErrorRefs}, NewState} + ecrn_agent:set_datetime(Pid, DateTime, + NewState#state.datetime_at_reference), + Acc; + ({Ref, X}, Acc) when is_list(X) -> + [Ref | Acc] + end, + [], + ecrn_reg:get_all()) of + [] -> + {reply, ok, NewState}; + ErrorRefs -> + {reply, {error, ErrorRefs}, NewState} end. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling cast messages -%% -%% @spec handle_cast(Msg, State) -> {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling all non call/cast messages -%% -%% @spec handle_info(Info, State) -> {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% This function is called by a gen_server when it is about to -%% terminate. It should be the opposite of Module:init/1 and do any -%% necessary cleaning up. When it returns, the gen_server terminates -%% with Reason. The return value is ignored. -%% -%% @spec terminate(Reason, State) -> void() -%% @end -%%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Convert process state when code is changed -%% -%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} -%% @end -%%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== internal_cancel(AlarmRef) -> case ecrn_reg:get(AlarmRef) of - undefined -> - undefined; - {ok, [Pid]} -> - {ok, ecrn_agent:cancel(Pid)} + undefined -> + undefined; + {ok, [Pid]} -> + {ok, ecrn_agent:cancel(Pid)} end. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl index a437d38..2936f6e 100644 --- a/src/ecrn_cron_sup.erl +++ b/src/ecrn_cron_sup.erl @@ -1,80 +1,57 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. You may obtain a +%%% copy of the License. %%%------------------------------------------------------------------- -%%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Simple one for one supervisor for ecd_chron jobs. -%%% @end -%%%------------------------------------------------------------------- -module(ecrn_cron_sup). -behaviour(supervisor). %% API -export([start_link/0, - add_job/2]). + add_job/2]). %% Supervisor callbacks -export([init/1]). -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -%%-------------------------------------------------------------------- -%% @doc -%% Starts the supervisor -%% -%% @spec start_link() -> {ok, Pid} | ignore | {error, Error} -%% @end -%%-------------------------------------------------------------------- +-spec start_link() -> {ok, pid()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). -%%-------------------------------------------------------------------- %% @doc %% Add a chron job to be supervised -%% @end -%%-------------------------------------------------------------------- - -add_job(AlarmRef, Task) -> - supervisor:start_child(?SERVER, [AlarmRef, Task]). - +-spec add_job(erlcron:job_ref(), erlcron:job()) -> erlcron:job_ref(). +add_job(JobRef, Task) -> + {ok, _} = supervisor:start_child(?SERVER, [JobRef, Task]), + JobRef. %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Whenever a supervisor is started using supervisor:start_link/[2,3], -%% this function is called by the new process to find out about -%% restart strategy, maximum restart frequency and child -%% specifications. -%% -%% @spec init(Args) -> {ok, {SupFlags, [ChildSpec]}} | -%% ignore | -%% {error, Reason} -%% @end -%%-------------------------------------------------------------------- init([]) -> RestartStrategy = simple_one_for_one, MaxRestarts = 1000, MaxSecondsBetweenRestarts = 3600, SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, Restart = transient, Shutdown = 2000, Type = worker, AChild = {ecrn_agent, {ecrn_agent, start_link, []}, - Restart, Shutdown, Type, [ecrn_agent]}, + Restart, Shutdown, Type, [ecrn_agent]}, {ok, {SupFlags, [AChild]}}. - -%%%=================================================================== -%%% Internal functions -%%%=================================================================== diff --git a/src/ecrn_reg.erl b/src/ecrn_reg.erl index cbe63e4..75c0d1d 100644 --- a/src/ecrn_reg.erl +++ b/src/ecrn_reg.erl @@ -1,250 +1,169 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. You may obtain a +%%% copy of the License. %%%------------------------------------------------------------------- -%%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% This provides simple pid registration for the server. -%%% @end -%%%------------------------------------------------------------------- -module(ecrn_reg). -behaviour(gen_server). %% API -export([start_link/0, - register/2, - unregister/1, - get/1, - stop/0, - get_all/0]). + register/2, + unregister/1, + get/1, + stop/0, + get_all/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, - terminate/2, code_change/3]). + terminate/2, code_change/3]). -include_lib("eunit/include/eunit.hrl"). -define(SERVER, ?MODULE). -record(state, {registered}). %%%=================================================================== %%% API %%%=================================================================== -spec start_link() -> {ok, Pid::pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). -%%-------------------------------------------------------------------- %% @doc %% Register an arbitrary value with the system, under a set of keys -%% @end -%%-------------------------------------------------------------------- -spec register(term() | [term()], term()) -> ok | {discarded_keys, [term()]}. register(Keys, Body) when is_list(Keys) -> gen_server:call(?SERVER, {register, Keys, Body}); register(Key, Body) -> gen_server:call(?SERVER, {register, [Key], Body}). -%%-------------------------------------------------------------------- %% @doc %% Remove the value registered under a que or set of keys -%% @end -%%-------------------------------------------------------------------- -spec unregister(term() | [term()]) -> ok. unregister(Keys) when is_list(Keys) -> gen_server:call(?SERVER, {unregister, Keys}); unregister(Key) -> gen_server:call(?SERVER, {unregister, [Key]}). -%%-------------------------------------------------------------------- %% @doc %% Get a value buy key. -%% @end -%%-------------------------------------------------------------------- -spec get(term()) -> {ok, term()} | undefined. get(Key) -> gen_server:call(?SERVER, {get, Key}). - -%%-------------------------------------------------------------------- %% @doc %% Get all the values. -%% @end -%%-------------------------------------------------------------------- -spec get_all() -> [{term(), term()}]. get_all() -> gen_server:call(?SERVER, get_all). - -%%-------------------------------------------------------------------- %% @doc %% stop this server -%% @end -%%-------------------------------------------------------------------- -spec stop() -> ok. stop() -> gen_server:call(?SERVER, stop). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Initiates the server -%% -%% @spec init(Args) -> {ok, State} | -%% {ok, State, Timeout} | -%% ignore | -%% {stop, Reason} -%% @end -%%-------------------------------------------------------------------- init([]) -> {ok, #state{registered=dict:new()}}. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling call messages -%% -%% @spec handle_call(Request, From, State) -> -%% < {reply, Reply, State} | -%% {reply, Reply, State, Timeout} | -%% {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, Reply, State} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_call({register, Keys, Body}, _From, #state{registered=Dict}) -> {Result, Dict2} = add_for_keys(Keys, Body, Dict, ok), {reply, Result, #state{registered=Dict2}}; handle_call({unregister, Keys}, _From, #state{registered=Dict}) -> Dict2 = remove_for_keys(Keys, Dict), {reply, ok, #state{registered=Dict2}}; handle_call({get, Key}, _From, State = #state{registered=Dict}) -> Value = get_for_key(Key, Dict), {reply, Value, State}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; handle_call(get_all, _From, State = #state{registered=Dict}) -> {reply, dict:to_list(Dict), State}. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling cast messages -%% -%% @spec handle_cast(Msg, State) -> {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Handling all non call/cast messages -%% -%% @spec handle_info(Info, State) -> {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, State} -%% @end -%%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% This function is called by a gen_server when it is about to -%% terminate. It should be the opposite of Module:init/1 and do any -%% necessary cleaning up. When it returns, the gen_server terminates -%% with Reason. The return value is ignored. -%% -%% @spec terminate(Reason, State) -> void() -%% @end -%%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Convert process state when code is changed -%% -%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} -%% @end -%%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== discarded_keys(Key, {discarded_keys, Keys}) -> {discarded_keys, [Key | Keys]}; discarded_keys(Key, ok) -> {discarded_keys, [Key]}. add_for_keys([Key | Rest], Body, Dict, Result) -> case dict:find(Key, Dict) of - error -> - add_for_keys(Rest, Body, dict:append(Key, Body, Dict), Result); - _Value -> - add_for_keys(Rest, Body, dict:append(Key, Body, Dict), - discarded_keys(Key, Result)) + error -> + add_for_keys(Rest, Body, dict:append(Key, Body, Dict), Result); + _Value -> + add_for_keys(Rest, Body, dict:append(Key, Body, Dict), + discarded_keys(Key, Result)) end; add_for_keys([], _, Dict, Result) -> {Result, Dict}. remove_for_keys([Key | Rest], Dict) -> remove_for_keys(Rest, dict:erase(Key, Dict)); remove_for_keys([],Dict) -> Dict. get_for_key(Key, Dict) -> case dict:find(Key, Dict) of - error -> - undefined; - Value -> - Value + error -> + undefined; + Value -> + Value end. %%%=================================================================== %%% Tests %%%=================================================================== generate_test_() -> {setup, fun () -> - ecrn_reg:start_link() + ecrn_reg:start_link() end, fun (_) -> - ecrn_reg:stop() + ecrn_reg:stop() end, {with, [fun general_tests/1]}}. general_tests(_) -> ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch({ok, [boo]}, ecrn_reg:get(a)), ecrn_reg:unregister([a, b]), ?assertMatch(undefined, ecrn_reg:get(a)), ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch(ok, ecrn_reg:register([c, d], boo2)), ?assertMatch({ok, [boo2]}, ecrn_reg:get(c)), ?assertMatch({ok, [boo]}, ecrn_reg:get(b)), ?assertMatch({discarded_keys, [d, c]}, - ecrn_reg:register([c, d], boo2)). - - - - - - - - + ecrn_reg:register([c, d], boo2)). diff --git a/src/ecrn_sup.erl b/src/ecrn_sup.erl index 4e1496d..2544f4e 100644 --- a/src/ecrn_sup.erl +++ b/src/ecrn_sup.erl @@ -1,74 +1,46 @@ -%%%---------------------------------------------------------------- -%%% @author Eric Newhuis <enewhuis@ecdmarket.com> -%%% @doc -%%% @end -%%% @copyright 2009 eCD Market -%%%---------------------------------------------------------------- +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. -module(ecrn_sup). -behaviour(supervisor). %% API -export([start_link/0]). %% Supervisor callbacks -export([init/1]). --include("erlcron-internal.hrl"). - -define(SERVER, ?MODULE). %%%=================================================================== %%% API functions %%%=================================================================== -%%-------------------------------------------------------------------- -%% @doc -%% Starts the supervisor -%% -%% @spec start_link() -> {ok, Pid} | ignore | {error, Error} -%% @end -%%-------------------------------------------------------------------- - +-spec start_link() -> {ok, Pid::term()} | ignore | {error, Error::term()}. start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%%=================================================================== %%% Supervisor callbacks %%%=================================================================== -%%-------------------------------------------------------------------- %% @private -%% @doc -%% Whenever a supervisor is started using supervisor:start_link/[2,3], -%% this function is called by the new process to find out about -%% restart strategy, maximum restart frequency and child -%% specifications. -%% -%% @spec init(Args) -> {ok, {SupFlags, [ChildSpec]}} | -%% ignore | -%% {error, Reason} -%% @end -%%-------------------------------------------------------------------- - init([]) -> RestartStrategy = one_for_one, MaxRestarts = 3, MaxSecondsBetweenRestarts = 10, SupFlags = {RestartStrategy, - MaxRestarts, - MaxSecondsBetweenRestarts}, + MaxRestarts, + MaxSecondsBetweenRestarts}, ChildSup = {ecrn_cron_sup, {ecrn_cron_sup, start_link, []}, - permanent, 1000, supervisor, [ecrn_cron_sup]}, + permanent, 1000, supervisor, [ecrn_cron_sup]}, RegistrationServer = {ecrn_reg_server, {ecrn_reg, start_link, []}, - permanent, 1000, worker, [ecrn_reg]}, + permanent, 1000, worker, [ecrn_reg]}, BroadcastServer = {ecrn_control, {ecrn_control, start_link, []}, - permanent, 1000, worker, [ecrn_control]}, + permanent, 1000, worker, [ecrn_control]}, {ok, {SupFlags, [ChildSup, RegistrationServer, BroadcastServer]}}. - -%%%=================================================================== -%%% Internal functions -%%%=================================================================== diff --git a/src/ecrn_test.erl b/src/ecrn_test.erl index f037efd..c05cc8a 100644 --- a/src/ecrn_test.erl +++ b/src/ecrn_test.erl @@ -1,171 +1,169 @@ -%%%------------------------------------------------------------------- -%%% @author Eric Merritt <emerritt@ecdmarket.com> -%%%------------------------------------------------------------------- +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. You may obtain a +%%% copy of the License. -module(ecrn_test). --compile(export_all). - -include_lib("eunit/include/eunit.hrl"). -%% -- tests --------------------------------------------------------------------- +%%%=================================================================== +%%% Types +%%%=================================================================== cron_test_() -> {setup, fun() -> - ecrn_app:manual_start() + ecrn_app:manual_start() end, fun(_) -> - ecrn_app:manual_stop() + ecrn_app:manual_stop() end, {with, [fun set_alarm_test/1, - fun travel_back_in_time_test/1, - fun cancel_alarm_test/1, - fun big_time_jump_test/1, - fun cron_test/1, - fun validation_test/1]}}. - - + fun travel_back_in_time_test/1, + fun cancel_alarm_test/1, + fun big_time_jump_test/1, + fun cron_test/1, + fun validation_test/1]}}. set_alarm_test(_) -> EpochDay = {2000,1,1}, EpochDateTime = {EpochDay,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> - Self ! ack1 - end), + Self ! ack1 + end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> - Self ! ack2 - end), + Self ! ack2 + end), erlcron:set_datetime({EpochDay, {8, 59, 59}}), -%% -%% The alarm should trigger this nearly immediately. -%% + + %% The alarm should trigger this nearly immediately. ?assertMatch(ok, receive - ack1 -> ok - after - 1500 -> timeout - end), -%% -%% The alarm should trigger this 1 second later. -%% + ack1 -> ok + after + 1500 -> timeout + end), + + %% The alarm should trigger this 1 second later. ?assertMatch(ok, receive - ack2 -> ok - after - 2500 -> timeout - end). + ack2 -> ok + after + 2500 -> timeout + end). cancel_alarm_test(_) -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> - Self ! ack - end), + Self ! ack + end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(ok, receive - ack -> ack - after -%% There is no event-driven way to -%% ensure we never receive an ack. - 125 -> ok - end). + ack -> ack + after + %% There is no event-driven way to + %% ensure we never receive an ack. + 125 -> ok + end). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump_test(_) -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> - Self ! ack1 - end), + Self ! ack1 + end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> - Self ! ack2 - end), + Self ! ack2 + end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(ok, receive - ack1 -> ok - after - 1500 -> timeout - end), + ack1 -> ok + after + 1500 -> timeout + end), ?assertMatch(ok, receive - ack2 -> ok - after - 1500 -> timeout - end), + ack2 -> ok + after + 1500 -> timeout + end), ?assertMatch(ok, receive - ack1 -> ok - after - 1500 -> timeout - end), + ack1 -> ok + after + 1500 -> timeout + end), ?assertMatch(ok, receive - ack2 -> ok - after - 2500 -> timeout - end). + ack2 -> ok + after + 2500 -> timeout + end). travel_back_in_time_test(_) -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), - ?assert(ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), - ?assert(ExpectedSeconds < Seconds). + ?assertMatch(true, ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), + ?assertMatch(true, ExpectedSeconds < Seconds). %% Time jumps ahead one day so we should see the alarms from both days. cron_test(_) -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,58}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Job = {{daily, {3, 30, pm}}, - fun(_, _) -> - Self ! ack - end}, + fun(_, _) -> + Self ! ack + end}, erlcron:cron(Job), ?assertMatch(ok, receive - ack -> ok - after - 2500 -> timeout - end). + ack -> ok + after + 2500 -> timeout + end). validation_test(_) -> ?assertMatch(valid, ecrn_agent:validate({once, {3, 30, pm}})), ?assertMatch(valid, ecrn_agent:validate({once, 3600})), - ?assertMatch(valid, ecrn_agent:validate({daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}})), + ?assertMatch(valid, ecrn_agent:validate({daily, {every, {23, sec}, + {between, {3, pm}, {3, 30, pm}}}})), ?assertMatch(valid, ecrn_agent:validate({daily, {3, 30, pm}})), - ?assertMatch(valid, ecrn_agent:validate({daily, [{1, 10, am}, {1, 07, 30, am}]})), ?assertMatch(valid, ecrn_agent:validate({weekly, thu, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({weekly, wed, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({monthly, 1, {2, am}})), ?assertMatch(valid, ecrn_agent:validate({monthly, 4, {2, am}})), - ?assertMatch(invalid, ecrn_agent:validate({once, fubar})), ?assertMatch(invalid, ecrn_agent:validate({daily, {55, 22, am}})), ?assertMatch(invalid, ecrn_agent:validate({monthly, 65, {55, am}})). -%% -- helpers ------------------------------------------------------------------- - +%%%=================================================================== +%%% Internal Functions +%%%=================================================================== seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). diff --git a/src/ecrn_util.erl b/src/ecrn_util.erl new file mode 100644 index 0000000..9e80206 --- /dev/null +++ b/src/ecrn_util.erl @@ -0,0 +1,19 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. You may obtain a +%%% copy of the License. +%%%------------------------------------------------------------------- +%%% @doc +%%% Utility functions for the erlcron system +-module(ecrn_util). + +-export([epoch_seconds/0]). + +%%%=================================================================== +%%% API +%%%=================================================================== +-spec epoch_seconds() -> erlcron:seconds(). +epoch_seconds() -> + {Megasecs, Secs, Microsecs} = erlang:now(), + erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)). diff --git a/src/erlcron.erl b/src/erlcron.erl index 81a3100..9031fb6 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,148 +1,120 @@ -%%%---------------------------------------------------------------- -%%% @author Eric Newhuis <enewhuis@ecdmarket.com> -%%% @copyright 2009-2010 eCD Market -%%%----------------------------------------------------------------, +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. -module(erlcron). -export([validate/1, cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/1, multi_set_datetime/2]). -export_type([job/0, job_ref/0, run_when/0, callable/0, dow/0, dom/0, period/0, duration/0, constraint/0, cron_time/0, seconds/0]). %%%=================================================================== %%% Types %%%=================================================================== -type seconds() :: integer(). -type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm} | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | min | sec}. -type period() :: cron_time() | {every, duration(), constraint()}. -type dom() :: integer(). -type dow() :: mon | tue | wed | thu | fri | sat | sun. -type callable() :: mfa() | function(). -type run_when() :: {once, cron_time()} | {once, seconds()} | {daily, period()} | {weekly, dow(), period()} | {monthly, dom(), period()}. -type job() :: {run_when(), callable()}. --opaque job_ref() :: reference(). + +%% should be opaque but dialyzer does not allow it +-type job_ref() :: reference(). %%%=================================================================== %%% API %%%=================================================================== -%%-------------------------------------------------------------------- %% @doc %% Check that the spec specified is valid or invalid -%% @end -%%-------------------------------------------------------------------- -spec validate(run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). -%%-------------------------------------------------------------------- %% @doc %% Adds a new job to the cron system. Jobs are described in the job() -%% spec. It returns the JobRef that can be used to manipulate the job -%% after it is created. -%% @end -%%-------------------------------------------------------------------- +%% spec. It returns the JobRef that can be used to manipulate the job +%% after it is created. + -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), - ecrn_cron_sup:add_job(JobRef, Job), - JobRef. - -%%-------------------------------------------------------------------- + ecrn_cron_sup:add_job(JobRef, Job). %% @doc -%% Convienience method to specify a job run to run on a daily basis -%% at a specific time. -%% @end -%%-------------------------------------------------------------------- +%% Convienience method to specify a job run to run on a daily basis +%% at a specific time. -spec at(cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). -%%-------------------------------------------------------------------- %% @doc %% Run the specified job once after the amount of time specifed. -%% @end -%%-------------------------------------------------------------------- -spec once(cron_time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). -%%-------------------------------------------------------------------- %% @doc %% Cancel the job specified by the jobref. -%% @end -%%-------------------------------------------------------------------- -spec cancel(job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). -%%-------------------------------------------------------------------- %% @doc %% Get the current date time of the running erlcron system. -%% @end -%%-------------------------------------------------------------------- -spec datetime() -> {calendar:datetime(), seconds()}. datetime() -> ecrn_control:datetime(). -%%-------------------------------------------------------------------- %% @doc %% Set the current date time of the running erlcron system. -%% @end -%%-------------------------------------------------------------------- -spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). - -%%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on different nodes. -%% @end -%%-------------------------------------------------------------------- -spec multi_set_datetime(calendar:datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). - -%%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes -%% @end -%%-------------------------------------------------------------------- -spec multi_set_datetime([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
4ea3bfba773a9775ea455ab2a4694c6d28ebaf64
move erlcron to an app.src instead of raw metadata
diff --git a/ebin/erlcron.app b/ebin/erlcron.app index a79c2a1..2f154eb 100644 --- a/ebin/erlcron.app +++ b/ebin/erlcron.app @@ -1,31 +1,8 @@ -%% -*- Erlang -*- -%% This is the application resource file (.app file) for the ecd_ops application. - -{application, erlcron, - [{description, - "Erlang Implementation of cron"}, - - {vsn, "0.2"}, - - {modules, - [erlcron, - ecrn_app, - ecrn_sup, - ecrn_agent, - ecrn_test, - ecrn_control, - ecrn_cron_sup, - ecrn_reg]}, - - {registered, - [ecrn_agent]}, - - {applications, - [kernel, - stdlib, - sasl, - eunit]}, - - {mod, - {ecrn_app, []}} - ]}. +{application,erlcron, + [{description,"Erlang Implementation of cron"}, + {vsn,"0.2"}, + {modules,[ecrn_agent,ecrn_app,ecrn_control,ecrn_cron_sup, + ecrn_reg,ecrn_sup,ecrn_test,ecrn_util,erlcron]}, + {registered,[ecrn_agent]}, + {applications,[kernel,stdlib,sasl,eunit]}, + {mod,{ecrn_app,[]}}]}. diff --git a/src/erlcron.app.src b/src/erlcron.app.src new file mode 100644 index 0000000..7ac033c --- /dev/null +++ b/src/erlcron.app.src @@ -0,0 +1,14 @@ +%% -*- Erlang -*- +%% This is the application resource file (.app file) for the ecd_ops application. + +{application, erlcron, + [{description, "Erlang Implementation of cron"}, + {vsn, "0.2"}, + {modules, []}, + {registered, [ecrn_agent]}, + {applications, [kernel, + stdlib, + sasl, + eunit]}, + {mod, + {ecrn_app, []}}]}.
erlware/erlcron
f8c126f6d35bb209745443ca46ee3196444a253d
rename erlcron-internal to internal.hrl
diff --git a/src/erlcron-internal.hrl b/src/erlcron-internal.hrl deleted file mode 100644 index 087d26a..0000000 --- a/src/erlcron-internal.hrl +++ /dev/null @@ -1,11 +0,0 @@ -%%%---------------------------------------------------------------- -%%% @author Eric Merritt <emerritt@ecdmarket.com> -%%% @copyright 2009 eCD Market -%%%---------------------------------------------------------------- --define(ONE_DAY,(24 * 60 * 60) ). - --define(EPOC_SECONDS, - (fun() -> - {Megasecs, Secs, Microsecs} = erlang:now(), - erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)) - end)()). diff --git a/src/internal.hrl b/src/internal.hrl new file mode 100644 index 0000000..7fd1779 --- /dev/null +++ b/src/internal.hrl @@ -0,0 +1,6 @@ +%%% @copyright Erlware, LLC. All Rights Reserved. +%%% +%%% This file is provided to you under the BSD License; you may not use +%%% this file except in compliance with the License. You may obtain a +%%% copy of the License. +-define(ONE_DAY, (24 * 60 * 60)).
erlware/erlcron
8e339a33ec81cef7b83b1e94c8eeb5f127df8c4b
fix spec problems that dialyzer found
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index cfde845..1f60475 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,479 +1,480 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Agent for cronish testing %%% @end %%%------------------------------------------------------------------- -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include("erlcron-internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). +%%%=================================================================== +%%% Types +%%%=================================================================== + +-type state() :: record(state). + %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server with the apropriate job and the appropriate ref %% @end %%-------------------------------------------------------------------- --spec start_link(erlcron:job_ref(), erlcron:job()) -> ok. +-spec start_link(erlcron:job_ref(), erlcron:job()) -> + ignore | {error, Reason::term()} | {ok, pid()}. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). --spec get_datetime(pid()) -> erlcron:datetime(). +-spec get_datetime(pid()) -> calendar:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). --spec set_datetime(pid(), erlcron:datetime(), erlcron:datetime()) -> ok. +-spec set_datetime(pid(), calendar:datetime(), erlcron:seconds()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %%-------------------------------------------------------------------- %% @doc %% Validate that a run_when spec specified is correct. %% @end %%-------------------------------------------------------------------- -spec validate(erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> erlang:display(erlang:get_stacktrace()), invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time(record(state)) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. --spec until_next_milliseconds(record(state), erlcron:job()) -> erlcron:seconds(). +-spec until_next_milliseconds(state(), erlcron:job()) -> + {ok, erlcron:seconds()} | {error, invalid_one_exception}. until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. --spec until_next_time(record(state), erlcron:job()) -> erlcron:seconds(). +-spec until_next_time(state(), {erlcron:run_when(), term()}) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. -%% @spec until_next_daytime(period()) -> seconds() +-spec until_next_daytime(erlcron:state(), erlcron:period()) -> erlcron:seconds(). until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. -%% @spec last_time(period()) -> seconds() %% @doc Calculates the last time in a given period. - +-spec last_time(erlcron:period()) -> erlcron:seconds(). last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). -%% @spec first_time(period()) -> seconds() -%% @doc Calculates the first time in a given period. +%% @doc Calculates the first time in a given period. +-spec first_time(erlcron:period()) -> erlcron:seconds(). first_time(Period) -> hd(lists:sort(resolve_period(Period))). -%% @spec next_time(period(), seconds()) -> seconds() %% @doc Calculates the first time in the given period after the given time. - +-spec next_time(erlcron:period(), erlcron:seconds()) -> erlcron:seconds(). next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). -%% @spec resolve_period(period()) -> [seconds()] -%% @doc Returns a list of times given a periodic specification. +%% @doc Returns a list of times given a periodic specification. +-spec resolve_period([erlcron:period()] | erlcron:period()) -> [erlcron:seconds()]. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). -%% @spec resolve_time(time()) -> seconds() %% @doc Returns seconds past midnight for a given time. - +-spec resolve_time(duration:time()) -> erlcron:seconds(). resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. -%% @spec resolve_dur(duration()) -> seconds() %% @doc Returns seconds for a given duration. - +-spec resolve_dur(erlcron:duration()) -> erlcron:seconds(). resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. -%% @spec resolve_dow(dow()) -> integer() %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. - +-spec resolve_dow(erlang:dow()) -> integer(). resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. -%% @spec until_tomorrow(seconds()) -> seconds() %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. - +-spec until_tomorrow(state(), erlcron:seconds()) -> ercron:seconds(). until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). -%% @spec until_days_from_now(period(), integer()) -> seconds() - %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. - +-spec until_days_from_now(state(), erlcron:period(), integer()) -> + erlcron:seconds(). until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). -%% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. - +-spec until_next_daytime_or_days_from_now(state(), erlcron:period(), integer()) -> + erlcron:seconds(). until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl index 2c0070a..7c7e2df 100644 --- a/src/ecrn_control.erl +++ b/src/ecrn_control.erl @@ -1,173 +1,174 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Provides testing/fast forward control for the system %%% @end %%%------------------------------------------------------------------- -module(ecrn_control). -behaviour(gen_server). %% API -export([start_link/0, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/2]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). -include("erlcron-internal.hrl"). -record(state, {reference_datetime, datetime_at_reference}). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server %% %% @spec start_link() -> {ok, Pid} | ignore | {error, Error} %% @end %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). cancel(AlarmRef) -> gen_server:call(?SERVER, {cancel, AlarmRef}). +-spec datetime() -> {calendar:datetime(), erlcron:seconds()}. datetime() -> gen_server:call(?SERVER, get_datetime). %% @doc sets the date-time for the erlcron set_datetime(DateTime={_,_}) -> gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). %% @doc sets the date-time with the erlcron on all nodes multi_set_datetime(Nodes, DateTime={_,_}) -> gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> DateTime = erlang:localtime(), {ok, #state{reference_datetime=DateTime, datetime_at_reference=?EPOC_SECONDS}}. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call({cancel, AlarmRef}, _From, State) -> {reply, internal_cancel(AlarmRef), State}; handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, datetime_at_reference = Actual}) -> {reply, {DateTime, Actual}, State}; handle_call({set_datetime, DateTime}, _From, State) -> NewState = State#state{reference_datetime=DateTime, datetime_at_reference=?EPOC_SECONDS}, case lists:foldl(fun({_, [Pid]}, Acc) -> ecrn_agent:set_datetime(Pid, DateTime, NewState#state.datetime_at_reference), Acc; ({Ref, X}, Acc) when is_list(X) -> [Ref | Acc] end, [], ecrn_reg:get_all()) of [] -> {reply, ok, NewState}; ErrorRefs -> {reply, {error, ErrorRefs}, NewState} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== internal_cancel(AlarmRef) -> case ecrn_reg:get(AlarmRef) of undefined -> undefined; {ok, [Pid]} -> {ok, ecrn_agent:cancel(Pid)} end. diff --git a/src/ecrn_reg.erl b/src/ecrn_reg.erl index f7fe934..cbe63e4 100644 --- a/src/ecrn_reg.erl +++ b/src/ecrn_reg.erl @@ -1,256 +1,250 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% This provides simple pid registration for the server. %%% @end %%%------------------------------------------------------------------- -module(ecrn_reg). -behaviour(gen_server). %% API -export([start_link/0, register/2, unregister/1, get/1, stop/0, get_all/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include_lib("eunit/include/eunit.hrl"). -define(SERVER, ?MODULE). -record(state, {registered}). %%%=================================================================== %%% API %%%=================================================================== -%%-------------------------------------------------------------------- -%% @doc -%% Starts the server -%% -%% @spec start_link() -> {ok, Pid} | ignore | {error, Error} -%% @end -%%-------------------------------------------------------------------- +-spec start_link() -> {ok, Pid::pid()} | ignore | {error, Error::term()}. start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %%-------------------------------------------------------------------- %% @doc %% Register an arbitrary value with the system, under a set of keys %% @end %%-------------------------------------------------------------------- --spec register(term() | [term()], term()) -> ok. +-spec register(term() | [term()], term()) -> ok | {discarded_keys, [term()]}. register(Keys, Body) when is_list(Keys) -> gen_server:call(?SERVER, {register, Keys, Body}); register(Key, Body) -> gen_server:call(?SERVER, {register, [Key], Body}). %%-------------------------------------------------------------------- %% @doc %% Remove the value registered under a que or set of keys %% @end %%-------------------------------------------------------------------- -spec unregister(term() | [term()]) -> ok. unregister(Keys) when is_list(Keys) -> gen_server:call(?SERVER, {unregister, Keys}); unregister(Key) -> gen_server:call(?SERVER, {unregister, [Key]}). %%-------------------------------------------------------------------- %% @doc %% Get a value buy key. %% @end %%-------------------------------------------------------------------- -spec get(term()) -> {ok, term()} | undefined. get(Key) -> gen_server:call(?SERVER, {get, Key}). %%-------------------------------------------------------------------- %% @doc %% Get all the values. %% @end %%-------------------------------------------------------------------- -spec get_all() -> [{term(), term()}]. get_all() -> gen_server:call(?SERVER, get_all). %%-------------------------------------------------------------------- %% @doc %% stop this server %% @end %%-------------------------------------------------------------------- -spec stop() -> ok. stop() -> gen_server:call(?SERVER, stop). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> {ok, #state{registered=dict:new()}}. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% < {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call({register, Keys, Body}, _From, #state{registered=Dict}) -> {Result, Dict2} = add_for_keys(Keys, Body, Dict, ok), {reply, Result, #state{registered=Dict2}}; handle_call({unregister, Keys}, _From, #state{registered=Dict}) -> Dict2 = remove_for_keys(Keys, Dict), {reply, ok, #state{registered=Dict2}}; handle_call({get, Key}, _From, State = #state{registered=Dict}) -> Value = get_for_key(Key, Dict), {reply, Value, State}; handle_call(stop, _From, State) -> {stop, normal, ok, State}; handle_call(get_all, _From, State = #state{registered=Dict}) -> {reply, dict:to_list(Dict), State}. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== discarded_keys(Key, {discarded_keys, Keys}) -> {discarded_keys, [Key | Keys]}; discarded_keys(Key, ok) -> {discarded_keys, [Key]}. add_for_keys([Key | Rest], Body, Dict, Result) -> case dict:find(Key, Dict) of error -> add_for_keys(Rest, Body, dict:append(Key, Body, Dict), Result); _Value -> add_for_keys(Rest, Body, dict:append(Key, Body, Dict), discarded_keys(Key, Result)) end; add_for_keys([], _, Dict, Result) -> {Result, Dict}. remove_for_keys([Key | Rest], Dict) -> remove_for_keys(Rest, dict:erase(Key, Dict)); remove_for_keys([],Dict) -> Dict. get_for_key(Key, Dict) -> case dict:find(Key, Dict) of error -> undefined; Value -> Value end. %%%=================================================================== %%% Tests %%%=================================================================== generate_test_() -> {setup, fun () -> ecrn_reg:start_link() end, fun (_) -> ecrn_reg:stop() end, {with, [fun general_tests/1]}}. general_tests(_) -> ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch({ok, [boo]}, ecrn_reg:get(a)), ecrn_reg:unregister([a, b]), ?assertMatch(undefined, ecrn_reg:get(a)), ?assertMatch(ok, ecrn_reg:register([a, b], boo)), ?assertMatch(ok, ecrn_reg:register([c, d], boo2)), ?assertMatch({ok, [boo2]}, ecrn_reg:get(c)), ?assertMatch({ok, [boo]}, ecrn_reg:get(b)), ?assertMatch({discarded_keys, [d, c]}, ecrn_reg:register([c, d], boo2)). diff --git a/src/erlcron-internal.hrl b/src/erlcron-internal.hrl index d8a8e3d..087d26a 100644 --- a/src/erlcron-internal.hrl +++ b/src/erlcron-internal.hrl @@ -1,11 +1,11 @@ %%%---------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @copyright 2009 eCD Market %%%---------------------------------------------------------------- -define(ONE_DAY,(24 * 60 * 60) ). -define(EPOC_SECONDS, - fun() -> - {Megasecs, Secs, Microsecs} = erlang:now(), - (Megasecs * 1000000) + Secs + (Microsecs / 1000000) - end()). + (fun() -> + {Megasecs, Secs, Microsecs} = erlang:now(), + erlang:trunc((Megasecs * 1000000) + Secs + (Microsecs / 1000000)) + end)()). diff --git a/src/erlcron.erl b/src/erlcron.erl index a776ba8..81a3100 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,147 +1,148 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). -export([validate/1, - cron/1, - at/2, - once/2, - cancel/1, - datetime/0, - set_datetime/1, - multi_set_datetime/1, - multi_set_datetime/2]). + cron/1, + at/2, + once/2, + cancel/1, + datetime/0, + set_datetime/1, + multi_set_datetime/1, + multi_set_datetime/2]). -export_type([job/0, - job_ref/0, - run_when/0, - callable/0, - dow/0, - dom/0, - period/0, - duration/0, - constraint/0, - cron_time/0, - datetime/0, - time/0, - date/0, - seconds/0]). + job_ref/0, + run_when/0, + callable/0, + dow/0, + dom/0, + period/0, + duration/0, + constraint/0, + cron_time/0, + seconds/0]). + + +%%%=================================================================== +%%% Types +%%%=================================================================== -type seconds() :: integer(). --type date() :: {integer(), integer(), integer()}. --type time() :: {integer(), integer(), integer()}. --type datetime() :: {date(), time()}. --type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm}. +-type cron_time() :: {integer(), am | pm} + | {integer(), integer(), am | pm} + | calendar:time(). -type constraint() :: {between, cron_time(), cron_time()}. -type duration() :: {integer(), hr | min | sec}. --type period() :: cron_time() | [cron_time()] | {every, duration(), constraint()}. +-type period() :: cron_time() | {every, duration(), constraint()}. -type dom() :: integer(). -type dow() :: mon | tue | wed | thu | fri | sat | sun. -type callable() :: mfa() | function(). --type run_when() :: {once, seconds()} - | {daily, period()} - | {weekly, dow(), period()} - | {monthly, dom(), period()}. +-type run_when() :: {once, cron_time()} + | {once, seconds()} + | {daily, period()} + | {weekly, dow(), period()} + | {monthly, dom(), period()}. -type job() :: {run_when(), callable()}. --opaque job_ref() :: {integer(), reference()}. +-opaque job_ref() :: reference(). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Check that the spec specified is valid or invalid %% @end %%-------------------------------------------------------------------- -spec validate(run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). %%-------------------------------------------------------------------- %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. %% @end %%-------------------------------------------------------------------- -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job), JobRef. %%-------------------------------------------------------------------- %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. %% @end %%-------------------------------------------------------------------- --spec at(time() | seconds(), function()) -> job_ref(). +-spec at(cron_time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Run the specified job once after the amount of time specifed. %% @end %%-------------------------------------------------------------------- --spec once(time() | seconds(), function()) -> job_ref(). +-spec once(cron_time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Cancel the job specified by the jobref. %% @end %%-------------------------------------------------------------------- -spec cancel(job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). %%-------------------------------------------------------------------- %% @doc %% Get the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- --spec datetime() -> datetime(). +-spec datetime() -> {calendar:datetime(), seconds()}. datetime() -> ecrn_control:datetime(). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- --spec set_datetime(datetime()) -> ok. +-spec set_datetime(calendar:datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on different nodes. %% @end %%-------------------------------------------------------------------- --spec multi_set_datetime(datetime()) -> ok. +-spec multi_set_datetime(calendar:datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes %% @end %%-------------------------------------------------------------------- --spec multi_set_datetime([node()], datetime()) -> ok. +-spec multi_set_datetime([node()], calendar:datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime). -
erlware/erlcron
e9c7bd7a1c10e1f2abc30ee5aa25ab0617e407a3
cleanup and format the rebar config
diff --git a/README.md b/README.md index 1187944..898b11b 100644 --- a/README.md +++ b/README.md @@ -1,113 +1,107 @@ -Erlcron provides testable cronish like functionality for Erlang +Erlcron +======= + +Erlcron provides testable cron like functionality for Erlang systems, with the ability to arbitrarily set the time and place along with fastforwarding through tests. See erlcron.erl for more documentation. The synax of a job description is quite different from crontab. It is (in this author's opinion) easier to read and is much more in keeping with the Erlang tradition. It is not quite as expressive as cron but this can be compensated for by adding multiple jobs. No output is logged or mailed to anyone. If you want output to be -logged or mailed, you must explicitly specify that as part of the -job. +logged or mailed, you must explicitly specify that as part of the job. This does not poll the system on a minute-by-minute basis like cron does. Each job is assigned to a single (Erlang) process. The time until it is to run next is calculated, and the process sleeps for exactly that long. -Unlike cron's one-minute resolution, crone -has a 2-second resolution (actually 1 second, but after running the -job, the process waits an extra second to avoid accidentally running it -more than once.) - -Because it does not wake up every minute, and because it does not -have a fixed configuration file, crone must be stopped and -restarted if the user wishes to change the scheduled jobs. +Unlike cron's one-minute resolution, erlcron has a 2-second resolution +(actually 1 second, but after running the job, the process waits an +extra second to avoid accidentally running it more than once.) -It does not handle Daylight Savings Time (or other -cases when the system clock is altered) gracefully, and it is recommended -that it be stopped and restarted on such occasions. +It does not handle Daylight Savings Time (or other cases when the +system clock is altered) gracefully, and it is recommended that it be +stopped and restarted on such occasions. Cron Job Description Examples: {{once, {3, 30, pm}}, {io, fwrite, ["Hello, world!~n"]}} {{once, {12, 23, 32}}, {io, fwrite, ["Hello, world!~n"]}} {{once, 3600}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, {io, fwrite, ["Hello, world!~n"]}} {{daily, {3, 30, pm}}, fun() -> io:fwrite("It's three thirty~n") end} {{daily, [{1, 10, am}, {1, 07, 30, am}]}, {io, fwrite, ["Bing~n"]}} {{weekly, thu, {2, am}}, {io, fwrite, ["It's 2 Thursday morning~n"]}} {{weekly, wed, {2, am}}, - {fuxbn() -> io:fwrite("It's 2 Wednesday morning~n") end} + {fun() -> io:fwrite("It's 2 Wednesday morning~n") end} {{weekly, fri, {2, am}}, {io, fwrite, ["It's 2 Friday morning~n"]}} {{monthly, 1, {2, am}}, {io, fwrite, ["First of the month!~n"]}} {{monthly, 4, {2, am}}, {io, fwrite, ["Fourth of the month!~n"]}} Adding a cron to the system: -Job = {{weekly, thu, {2, am}}, - {io, fwrite, ["It's 2 Thursday morning~n"]}}. + Job = {{weekly, thu, {2, am}}, + {io, fwrite, ["It's 2 Thursday morning~n"]}}. -erlcron:cron(Job). + erlcron:cron(Job). A simple way to add a daily cron: -erlcron:at({3, 30, pm}, Fun). + erlcron:at({3, 30, pm}, Fun). A simple way to add a job that will be run once in the future. Where 'once' is the number of seconds until it runs. -erlcron:once(300, Fun). - + erlcron:once(300, Fun). Cancel a running job. -erlcron:cancel(JobRef). + erlcron:cancel(JobRef). Get the current date time of the system. -erlcron:datetime(). + erlcron:datetime(). Set the current date time of the system. Any tests that need to be run in the interim will be run as the time rolls forward. -erlcron:set_datetime(DateTime). - + erlcron:set_datetime(DateTime). Set the current date time of the system on all nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. -erlcron:multi_set_datetime(DateTime). + erlcron:multi_set_datetime(DateTime). Set the current date time of the system on a specific set of nodes in the cluster. Any tests that need to be run in the interim will be run as the time rolls forward. -erlcron:multi_set_datetime(Nodes, DateTime). - + erlcron:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
f9d31866f703c3e999a2f308007dee1ccd23d1a1
add a complete makefile to the system to help drive rebar
diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a08f383 --- /dev/null +++ b/Makefile @@ -0,0 +1,92 @@ +# Copyright Erlware, LLC. All Rights Reserved. +# +# This file is provided to you under the BSD License; you may not use +# this file except in compliance with the License. You may obtain a +# copy of the License. + +ERLFLAGS= -pa $(CURDIR)/.eunit -pa $(CURDIR)/ebin -pa $(CURDIR)/deps/*/ebin + +DEPS_PLT=$(CURDIR)/.deps_plt + +# ============================================================================= +# Verify that the programs we need to run are installed on this system +# ============================================================================= +ERL = $(shell which erl) + +ifeq ($(ERL),) +$(error "Erlang not available on this system") +endif + +REBAR=$(shell which rebar) + +ifeq ($(REBAR),) +$(error "Rebar not available on this system") +endif + +.PHONY: all compile doc clean test dialyzer typer shell distclean pdf \ + get-deps escript clean-common-test-data rebuild + +all: compile dialyzer test + +# ============================================================================= +# Rules to build the system +# ============================================================================= + +get-deps: + $(REBAR) get-deps + $(REBAR) compile + +compile: + $(REBAR) skip_deps=true compile + +doc: + $(REBAR) skip_deps=true doc + +eunit: compile clean-common-test-data + $(REBAR) skip_deps=true eunit + +ct: compile clean-common-test-data + $(REBAR) skip_deps=true ct + +test: compile eunit ct + +$(DEPS_PLT): + @echo Building local plt at $(DEPS_PLT) + @echo + dialyzer --output_plt $(DEPS_PLT) --build_plt \ + --apps erts kernel stdlib + +dialyzer: $(DEPS_PLT) + dialyzer --plt $(DEPS_PLT) --fullpath \ + -pa $(CURDIR)/ebin --src src + +typer: + typer --plt $(DEPS_PLT) -r ./src + +shell: get-deps compile +# You often want *rebuilt* rebar tests to be available to the +# shell you have to call eunit (to get the tests +# rebuilt). However, eunit runs the tests, which probably +# fails (thats probably why You want them in the shell). This +# runs eunit but tells make to ignore the result. + - @$(REBAR) skip_deps=true eunit + @$(ERL) $(ERLFLAGS) + +pdf: + pandoc README.md -o README.pdf + +clean-common-test-data: +# We have to do this because of the unique way we generate test +# data. Without this rebar eunit gets very confused + - rm -rf $(CURDIR)/test/*_SUITE_data + +clean: clean-common-test-data + - rm -rf $(CURDIR)/test/*.beam + - rm -rf $(CURDIR)/logs + $(REBAR) skip_deps=true clean + +distclean: clean + - rm -rf $(DEPS_PLT) + - rm -rvf $(CURDIR)/deps/* + +rebuild: distclean get-deps compile dialyzer test
erlware/erlcron
3dedec11103472711e5fdb8255944b936aacdc8d
format the rebar config and make it a bit more reader friendly
diff --git a/rebar.config b/rebar.config index f1c51f5..5de288a 100644 --- a/rebar.config +++ b/rebar.config @@ -1,3 +1,13 @@ +%%% -*- mode: erlang -*- + +%% Compiler Options ============================================================ {erl_opts, [debug_info, warnings_as_errors]}. + +%% EUnit ======================================================================= +{eunit_opts, [verbose, + {report, {eunit_surefire, [{dir, "."}]}}]}. + +{cover_enabled, true}. +{cover_print_enabled, true}.
erlware/erlcron
9199fcd935b589c10a9b1e512d454fad140560b5
add warnings_as_errors to the rebar config
diff --git a/rebar.config b/rebar.config index 0f5d40e..f1c51f5 100644 --- a/rebar.config +++ b/rebar.config @@ -1 +1,3 @@ -{erl_opts, [debug_info]}. +{erl_opts, + [debug_info, + warnings_as_errors]}.
erlware/erlcron
94311eba72d1c40cba7fd8d5e79671dbf2ee00a1
Basic rebarization
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7d3bff3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +ebin/*.beam +ebin/*.app diff --git a/rebar b/rebar new file mode 100755 index 0000000..672a9f8 Binary files /dev/null and b/rebar differ diff --git a/rebar.config b/rebar.config new file mode 100644 index 0000000..0f5d40e --- /dev/null +++ b/rebar.config @@ -0,0 +1 @@ +{erl_opts, [debug_info]}.
erlware/erlcron
4c771ba32d2d01d0bbb5236521adefbfc4620033
migrate to explicit exported types
diff --git a/ebin/erlcron.app b/ebin/erlcron.app index fabd875..a79c2a1 100644 --- a/ebin/erlcron.app +++ b/ebin/erlcron.app @@ -1,31 +1,31 @@ %% -*- Erlang -*- %% This is the application resource file (.app file) for the ecd_ops application. {application, erlcron, [{description, "Erlang Implementation of cron"}, - {vsn, "0.1"}, + {vsn, "0.2"}, {modules, [erlcron, ecrn_app, ecrn_sup, ecrn_agent, ecrn_test, ecrn_control, ecrn_cron_sup, ecrn_reg]}, {registered, [ecrn_agent]}, {applications, [kernel, stdlib, sasl, eunit]}, {mod, {ecrn_app, []}} ]}. diff --git a/include/erlcron.hrl b/include/erlcron.hrl deleted file mode 100644 index 203a984..0000000 --- a/include/erlcron.hrl +++ /dev/null @@ -1,19 +0,0 @@ - --type seconds() :: integer(). --type date() :: {integer(), integer(), integer()}. --type time() :: {integer(), integer(), integer()}. --type datetime() :: {date(), time()}. - --type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm}. --type constraint() :: {between, cron_time(), cron_time()}. --type duration() :: {integer(), hr | min | sec}. --type period() :: cron_time() | [cron_time()] | {every, duration(), constraint()}. --type dom() :: integer(). --type dow() :: mon | tue | wed | thu | fri | sat | sun. --type callable() :: mfa() | function(). --type run_when() :: {daily, period()} - | {weekly, dow(), period()} - | {monthly, dom(), period()}. - --type job() :: {run_when(), callable()}. --opaque job_ref() :: {integer(), reference()}. diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 63c7646..cfde845 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,480 +1,479 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Agent for cronish testing %%% @end %%%------------------------------------------------------------------- -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). --include_lib("erlcron/include/erlcron.hrl"). -include("erlcron-internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server with the apropriate job and the appropriate ref %% @end %%-------------------------------------------------------------------- --spec start_link(job_ref(), job()) -> ok. +-spec start_link(erlcron:job_ref(), erlcron:job()) -> ok. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). --spec get_datetime(pid()) -> datetime(). +-spec get_datetime(pid()) -> erlcron:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). --spec set_datetime(pid(), datetime(), datetime()) -> ok. +-spec set_datetime(pid(), erlcron:datetime(), erlcron:datetime()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %%-------------------------------------------------------------------- %% @doc %% Validate that a run_when spec specified is correct. %% @end %%-------------------------------------------------------------------- --spec validate(run_when()) -> valid | invalid. +-spec validate(erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> erlang:display(erlang:get_stacktrace()), invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. --spec current_time(record(state)) -> seconds(). +-spec current_time(record(state)) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. --spec until_next_milliseconds(record(state), job()) -> seconds(). +-spec until_next_milliseconds(record(state), erlcron:job()) -> erlcron:seconds(). until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. --spec until_next_time(record(state), job()) -> seconds(). +-spec until_next_time(record(state), erlcron:job()) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. %% @spec until_next_daytime(period()) -> seconds() until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @spec last_time(period()) -> seconds() %% @doc Calculates the last time in a given period. last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @spec first_time(period()) -> seconds() %% @doc Calculates the first time in a given period. first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @spec next_time(period(), seconds()) -> seconds() %% @doc Calculates the first time in the given period after the given time. next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @spec resolve_period(period()) -> [seconds()] %% @doc Returns a list of times given a periodic specification. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @spec resolve_time(time()) -> seconds() %% @doc Returns seconds past midnight for a given time. resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @spec resolve_dur(duration()) -> seconds() %% @doc Returns seconds for a given duration. resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @spec resolve_dow(dow()) -> integer() %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @spec until_tomorrow(seconds()) -> seconds() %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @spec until_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/erlcron.erl b/src/erlcron.erl index 2d1e1c9..a776ba8 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,113 +1,147 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). -export([validate/1, cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/1, multi_set_datetime/2]). --include_lib("erlcron/include/erlcron.hrl"). +-export_type([job/0, + job_ref/0, + run_when/0, + callable/0, + dow/0, + dom/0, + period/0, + duration/0, + constraint/0, + cron_time/0, + datetime/0, + time/0, + date/0, + seconds/0]). + +-type seconds() :: integer(). +-type date() :: {integer(), integer(), integer()}. +-type time() :: {integer(), integer(), integer()}. +-type datetime() :: {date(), time()}. + +-type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm}. +-type constraint() :: {between, cron_time(), cron_time()}. +-type duration() :: {integer(), hr | min | sec}. +-type period() :: cron_time() | [cron_time()] | {every, duration(), constraint()}. +-type dom() :: integer(). +-type dow() :: mon | tue | wed | thu | fri | sat | sun. +-type callable() :: mfa() | function(). +-type run_when() :: {once, seconds()} + | {daily, period()} + | {weekly, dow(), period()} + | {monthly, dom(), period()}. + +-type job() :: {run_when(), callable()}. +-opaque job_ref() :: {integer(), reference()}. + %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Check that the spec specified is valid or invalid %% @end %%-------------------------------------------------------------------- -spec validate(run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). %%-------------------------------------------------------------------- %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. %% @end %%-------------------------------------------------------------------- -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job), JobRef. %%-------------------------------------------------------------------- %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. %% @end %%-------------------------------------------------------------------- -spec at(time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Run the specified job once after the amount of time specifed. %% @end %%-------------------------------------------------------------------- -spec once(time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Cancel the job specified by the jobref. %% @end %%-------------------------------------------------------------------- -spec cancel(job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). %%-------------------------------------------------------------------- %% @doc %% Get the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- -spec datetime() -> datetime(). datetime() -> ecrn_control:datetime(). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- -spec set_datetime(datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on different nodes. %% @end %%-------------------------------------------------------------------- -spec multi_set_datetime(datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes %% @end %%-------------------------------------------------------------------- -spec multi_set_datetime([node()], datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
b413c256eafd153d96a53ad98f5f83aa4430f081
add spec validation to the api
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 1a3cfc4..63c7646 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,475 +1,480 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Agent for cronish testing %%% @end %%%------------------------------------------------------------------- -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, - recalculate/1]). + recalculate/1, + validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include_lib("erlcron/include/erlcron.hrl"). -include("erlcron-internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server with the apropriate job and the appropriate ref %% @end %%-------------------------------------------------------------------- -spec start_link(job_ref(), job()) -> ok. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime(pid()) -> datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), datetime(), datetime()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %%-------------------------------------------------------------------- %% @doc %% Validate that a run_when spec specified is correct. %% @end %%-------------------------------------------------------------------- -spec validate(run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), - case until_next_milliseconds(NewState, {Spec, undefined}) of - {ok, Millis} when is_integer(Millis) -> - valid; - {error, _} -> + try + until_next_time(NewState, {Spec, undefined}), + valid + catch + _Error:_Reason -> + erlang:display(erlang:get_stacktrace()), invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time(record(state)) -> seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_milliseconds(record(state), job()) -> seconds(). until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> + erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. --spec until_next_seconds(record(state), job()) -> seconds(). +-spec until_next_time(record(state), job()) -> seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), - Today = calendar:day_of_the_week(current_date(State)), + {Date, _} = current_date(State), + Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> - {ThisYear, ThisMonth, Today} = current_date(State), + {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. %% @spec until_next_daytime(period()) -> seconds() until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @spec last_time(period()) -> seconds() %% @doc Calculates the last time in a given period. last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @spec first_time(period()) -> seconds() %% @doc Calculates the first time in a given period. first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @spec next_time(period(), seconds()) -> seconds() %% @doc Calculates the first time in the given period after the given time. next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @spec resolve_period(period()) -> [seconds()] %% @doc Returns a list of times given a periodic specification. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @spec resolve_time(time()) -> seconds() %% @doc Returns seconds past midnight for a given time. -resolve_time({H, M, S}) when is_integer(S) -> +resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; -resolve_time({H, M, S, X}) when is_atom(X) -> +resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; -resolve_time({H, M, X}) when is_atom(X) -> +resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; -resolve_time({H, am}) -> +resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; -resolve_time({H, pm}) -> +resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @spec resolve_dur(duration()) -> seconds() %% @doc Returns seconds for a given duration. resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @spec resolve_dow(dow()) -> integer() %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @spec until_tomorrow(seconds()) -> seconds() %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @spec until_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/ecrn_test.erl b/src/ecrn_test.erl index 2d60a61..f037efd 100644 --- a/src/ecrn_test.erl +++ b/src/ecrn_test.erl @@ -1,152 +1,171 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%%------------------------------------------------------------------- -module(ecrn_test). +-compile(export_all). + -include_lib("eunit/include/eunit.hrl"). %% -- tests --------------------------------------------------------------------- cron_test_() -> {setup, fun() -> ecrn_app:manual_start() end, fun(_) -> ecrn_app:manual_stop() end, {with, [fun set_alarm_test/1, fun travel_back_in_time_test/1, fun cancel_alarm_test/1, fun big_time_jump_test/1, - fun cron_test/1]}}. + fun cron_test/1, + fun validation_test/1]}}. set_alarm_test(_) -> EpochDay = {2000,1,1}, EpochDateTime = {EpochDay,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({EpochDay, {8, 59, 59}}), %% %% The alarm should trigger this nearly immediately. %% ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), %% %% The alarm should trigger this 1 second later. %% ?assertMatch(ok, receive ack2 -> ok after 2500 -> timeout end). cancel_alarm_test(_) -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(ok, receive ack -> ack after %% There is no event-driven way to %% ensure we never receive an ack. 125 -> ok end). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump_test(_) -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack2 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack2 -> ok after 2500 -> timeout end). travel_back_in_time_test(_) -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assert(ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), ?assert(ExpectedSeconds < Seconds). %% Time jumps ahead one day so we should see the alarms from both days. cron_test(_) -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,58}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Job = {{daily, {3, 30, pm}}, fun(_, _) -> Self ! ack end}, erlcron:cron(Job), ?assertMatch(ok, receive ack -> ok after 2500 -> timeout end). +validation_test(_) -> + ?assertMatch(valid, ecrn_agent:validate({once, {3, 30, pm}})), + ?assertMatch(valid, ecrn_agent:validate({once, 3600})), + ?assertMatch(valid, ecrn_agent:validate({daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}})), + ?assertMatch(valid, ecrn_agent:validate({daily, {3, 30, pm}})), + ?assertMatch(valid, ecrn_agent:validate({daily, [{1, 10, am}, {1, 07, 30, am}]})), + ?assertMatch(valid, ecrn_agent:validate({weekly, thu, {2, am}})), + ?assertMatch(valid, ecrn_agent:validate({weekly, wed, {2, am}})), + ?assertMatch(valid, ecrn_agent:validate({monthly, 1, {2, am}})), + ?assertMatch(valid, ecrn_agent:validate({monthly, 4, {2, am}})), + ?assertMatch(invalid, ecrn_agent:validate({once, fubar})), + ?assertMatch(invalid, ecrn_agent:validate({daily, {55, 22, am}})), + ?assertMatch(invalid, ecrn_agent:validate({monthly, 65, {55, am}})). + + + %% -- helpers ------------------------------------------------------------------- seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). diff --git a/src/erlcron.erl b/src/erlcron.erl index e319315..2d1e1c9 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,105 +1,113 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). --export([cron/1, +-export([validate/1, + cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, - set_datetime/2, multi_set_datetime/1, - multi_set_datetime/2, - multi_set_datetime/3]). + multi_set_datetime/2]). -include_lib("erlcron/include/erlcron.hrl"). %%%=================================================================== %%% API %%%=================================================================== +%%-------------------------------------------------------------------- +%% @doc +%% Check that the spec specified is valid or invalid +%% @end +%%-------------------------------------------------------------------- +-spec validate(run_when()) -> valid | invalid. +validate(Spec) -> + ecrn_agent:validate(Spec). + %%-------------------------------------------------------------------- %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. %% @end %%-------------------------------------------------------------------- -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job), JobRef. %%-------------------------------------------------------------------- %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. %% @end %%-------------------------------------------------------------------- -spec at(time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Run the specified job once after the amount of time specifed. %% @end %%-------------------------------------------------------------------- -spec once(time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Cancel the job specified by the jobref. %% @end %%-------------------------------------------------------------------- -spec cancel(job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). %%-------------------------------------------------------------------- %% @doc %% Get the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- -spec datetime() -> datetime(). datetime() -> ecrn_control:datetime(). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- -spec set_datetime(datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on different nodes. %% @end %%-------------------------------------------------------------------- -spec multi_set_datetime(datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes %% @end %%-------------------------------------------------------------------- -spec multi_set_datetime([node()], datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
e9fdd31e693b2a0deeefff6cf36c83ec1730579a
add validation for spec to ecrn_agent
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index be9a4b5..1a3cfc4 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,453 +1,475 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Agent for cronish testing %%% @end %%%------------------------------------------------------------------- -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include_lib("erlcron/include/erlcron.hrl"). -include("erlcron-internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server with the apropriate job and the appropriate ref %% @end %%-------------------------------------------------------------------- -spec start_link(job_ref(), job()) -> ok. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime(pid()) -> datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), datetime(), datetime()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). +%%-------------------------------------------------------------------- +%% @doc +%% Validate that a run_when spec specified is correct. +%% @end +%%-------------------------------------------------------------------- +-spec validate(run_when()) -> valid | invalid. +validate(Spec) -> + State = #state{job=undefined, + alarm_ref=undefined}, + {DateTime, Actual} = ecrn_control:datetime(), + NewState = set_internal_time(State, DateTime, Actual), + case until_next_milliseconds(NewState, {Spec, undefined}) of + {ok, Millis} when is_integer(Millis) -> + valid; + {error, _} -> + invalid + end. + + %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time(record(state)) -> seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). +%% @doc Calculates the duration in milliseconds until the next time +%% a job is to be run. +-spec until_next_milliseconds(record(state), job()) -> seconds(). until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> throw(invalid_once_exception) end. -%% @spec until_next_seconds(job()) -> seconds() %% @doc Calculates the duration in seconds until the next time %% a job is to be run. +-spec until_next_seconds(record(state), job()) -> seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), Today = calendar:day_of_the_week(current_date(State)), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {ThisYear, ThisMonth, Today} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. %% @spec until_next_daytime(period()) -> seconds() until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @spec last_time(period()) -> seconds() %% @doc Calculates the last time in a given period. last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @spec first_time(period()) -> seconds() %% @doc Calculates the first time in a given period. first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @spec next_time(period(), seconds()) -> seconds() %% @doc Calculates the first time in the given period after the given time. next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @spec resolve_period(period()) -> [seconds()] %% @doc Returns a list of times given a periodic specification. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @spec resolve_time(time()) -> seconds() %% @doc Returns seconds past midnight for a given time. resolve_time({H, M, S}) when is_integer(S) -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) -> (H + 12) * 3600. %% @spec resolve_dur(duration()) -> seconds() %% @doc Returns seconds for a given duration. resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @spec resolve_dow(dow()) -> integer() %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @spec until_tomorrow(seconds()) -> seconds() %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @spec until_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end.
erlware/erlcron
68cebfc196283bcccd30fdcba20f38f487e9fa7d
Add more documentation, fix specs in erlcron
diff --git a/src/erlcron.erl b/src/erlcron.erl index d94fbd9..e319315 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,57 +1,105 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). -export([cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, set_datetime/2, multi_set_datetime/1, multi_set_datetime/2, multi_set_datetime/3]). -include_lib("erlcron/include/erlcron.hrl"). +%%%=================================================================== +%%% API +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @doc +%% Adds a new job to the cron system. Jobs are described in the job() +%% spec. It returns the JobRef that can be used to manipulate the job +%% after it is created. +%% @end +%%-------------------------------------------------------------------- -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job), JobRef. +%%-------------------------------------------------------------------- +%% @doc +%% Convienience method to specify a job run to run on a daily basis +%% at a specific time. +%% @end +%%-------------------------------------------------------------------- -spec at(time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). +%%-------------------------------------------------------------------- +%% @doc +%% Run the specified job once after the amount of time specifed. +%% @end +%%-------------------------------------------------------------------- -spec once(time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). +%%-------------------------------------------------------------------- +%% @doc +%% Cancel the job specified by the jobref. +%% @end +%%-------------------------------------------------------------------- -spec cancel(job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). - +%%-------------------------------------------------------------------- +%% @doc +%% Get the current date time of the running erlcron system. +%% @end +%%-------------------------------------------------------------------- -spec datetime() -> datetime(). datetime() -> ecrn_control:datetime(). +%%-------------------------------------------------------------------- +%% @doc +%% Set the current date time of the running erlcron system. +%% @end +%%-------------------------------------------------------------------- -spec set_datetime(datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). +%%-------------------------------------------------------------------- +%% @doc +%% Set the current date time of the erlcron system running on different nodes. +%% @end +%%-------------------------------------------------------------------- -spec multi_set_datetime(datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). + +%%-------------------------------------------------------------------- +%% @doc +%% Set the current date time of the erlcron system running on the +%% specified nodes +%% @end +%%-------------------------------------------------------------------- -spec multi_set_datetime([node()], datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
1ccc1f7b4ebf606ba6f70a0488037cde0869619b
Remove invalide functions, uneccesary documentation
diff --git a/src/erlcron.erl b/src/erlcron.erl index 3f8f190..d94fbd9 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,135 +1,57 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). -export([cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, set_datetime/2, multi_set_datetime/1, multi_set_datetime/2, multi_set_datetime/3]). -include_lib("erlcron/include/erlcron.hrl"). -%% @doc Simple job scheduler for Erlang/OTP -%% -%% This is a simple utility which schedules jobs to be -%% run at a given time or periodically -%% -%% The synax of a job description is quite different from -%% <code>crontab</code>. It is (in this author's opinion) easier to read -%% and is much more in keeping with the Erlang tradition. It is not -%% quite as expressive as <code>cron</code> but this can be compensated -%% for by adding multiple jobs. -%% -%% No output is logged or mailed to anyone. If you want output to -%% be logged or mailed, you must explicitly specify that as part of the -%% job. -%% -%% This does not poll the system on a minute-by-minute -%% basis like <code>cron</code> does. Each job is assigned to a single -%% (Erlang) process. The time until it is to run next is calculated, -%% and the process sleeps for exactly that long. -%% -%% Unlike <code>cron</code>'s one-minute resolution, <code>crone</code> -%% has a 2-second resolution (actually 1 second, but after running the -%% job, the process waits an extra second to avoid accidentally running it -%% more than once.) -%% -%% Because it does not wake up every minute, and because it does not -%% have a fixed configuration file, <code>crone</code> must be stopped and -%% restarted if the user wishes to change the scheduled jobs. -%% -%% It does not handle Daylight Savings Time (or other -%% cases when the system clock is altered) gracefully, and it is recommended -%% that it be stopped and restarted on such occasions. -%% -%% Cron Job Examples -%% -%% <code> -%% -%% {{once, {3, 30, pm}}, -%% {io, fwrite, ["Hello, world!~n"]}} -%% -%% {{once, {12, 23, 32}}, -%% {io, fwrite, ["Hello, world!~n"]}} -%% -%% {{once, 3600}, -%% {io, fwrite, ["Hello, world!~n"]}} -%% -%% {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, -%% {io, fwrite, ["Hello, world!~n"]}} -%% -%% {{daily, {3, 30, pm}}, -%% fun() -> io:fwrite("It's three thirty~n") end} -%% -%% {{daily, [{1, 10, am}, {1, 07, 30, am}]}, -%% {io, fwrite, ["Bing~n"]}} -%% -%% {{weekly, thu, {2, am}}, -%% {io, fwrite, ["It's 2 Thursday morning~n"]}} -%% -%% {{weekly, wed, {2, am}}, -%% {fuxbn() -> io:fwrite("It's 2 Wednesday morning~n") end} -%% -%% {{weekly, fri, {2, am}}, -%% {io, fwrite, ["It's 2 Friday morning~n"]}} -%% -%% {{monthly, 1, {2, am}}, -%% {io, fwrite, ["First of the month!~n"]}} -%% -%% {{monthly, 4, {2, am}}, -%% {io, fwrite, ["Fourth of the month!~n"]}} -%% </code> -%% -%% @end - --spec cron(job()) -> ok. +-spec cron(job()) -> job_ref(). cron(Job) -> - AlarmRef = make_ref(), - ecrn_cron_sup:add_job(AlarmRef, Job), - AlarmRef. + JobRef = make_ref(), + ecrn_cron_sup:add_job(JobRef, Job), + JobRef. --spec at(time() | seconds(), function()) -> ok. +-spec at(time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). --spec once(time() | seconds(), function()) -> ok. +-spec once(time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). -spec cancel(job_ref()) -> ok. -cancel(AlarmRef) -> - ecrn_control:cancel(AlarmRef). +cancel(JobRef) -> + ecrn_control:cancel(JobRef). -spec datetime() -> datetime(). datetime() -> ecrn_control:datetime(). -spec set_datetime(datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). --spec set_datetime(datetime(), testing | production) -> ok. -set_datetime(DateTime, Atom) when is_atom(Atom) -> - ecrn_control:set_datetime(DateTime, Atom). -spec multi_set_datetime(datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). -spec multi_set_datetime([node()], datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime). -multi_set_datetime(Nodes, DateTime, testing) when is_list(Nodes) -> - ecrn_control:multi_set_datetime(Nodes, DateTime, testing).
erlware/erlcron
993944e3ade60b33368f6dca9e2feaec4b1383b4
Enhance project README
diff --git a/README b/README index b67959a..1187944 100644 --- a/README +++ b/README @@ -1,3 +1,113 @@ -This provides testable cronish like functionality for Erlang systems, -with the ability to arbitrarily set the time and place along with -fastforwarding through tests. See erlcron.erl for more documentation. \ No newline at end of file +Erlcron provides testable cronish like functionality for Erlang +systems, with the ability to arbitrarily set the time and place along +with fastforwarding through tests. See erlcron.erl for more +documentation. + +The synax of a job description is quite different from crontab. It is +(in this author's opinion) easier to read and is much more in keeping +with the Erlang tradition. It is not quite as expressive as cron but +this can be compensated for by adding multiple jobs. + +No output is logged or mailed to anyone. If you want output to be +logged or mailed, you must explicitly specify that as part of the +job. + +This does not poll the system on a minute-by-minute basis like cron +does. Each job is assigned to a single (Erlang) process. The time +until it is to run next is calculated, and the process sleeps for +exactly that long. + +Unlike cron's one-minute resolution, crone +has a 2-second resolution (actually 1 second, but after running the +job, the process waits an extra second to avoid accidentally running it +more than once.) + +Because it does not wake up every minute, and because it does not +have a fixed configuration file, crone must be stopped and +restarted if the user wishes to change the scheduled jobs. + +It does not handle Daylight Savings Time (or other +cases when the system clock is altered) gracefully, and it is recommended +that it be stopped and restarted on such occasions. + +Cron Job Description Examples: + + {{once, {3, 30, pm}}, + {io, fwrite, ["Hello, world!~n"]}} + + {{once, {12, 23, 32}}, + {io, fwrite, ["Hello, world!~n"]}} + + {{once, 3600}, + {io, fwrite, ["Hello, world!~n"]}} + + {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, + {io, fwrite, ["Hello, world!~n"]}} + + {{daily, {3, 30, pm}}, + fun() -> io:fwrite("It's three thirty~n") end} + + {{daily, [{1, 10, am}, {1, 07, 30, am}]}, + {io, fwrite, ["Bing~n"]}} + + {{weekly, thu, {2, am}}, + {io, fwrite, ["It's 2 Thursday morning~n"]}} + + {{weekly, wed, {2, am}}, + {fuxbn() -> io:fwrite("It's 2 Wednesday morning~n") end} + + {{weekly, fri, {2, am}}, + {io, fwrite, ["It's 2 Friday morning~n"]}} + + {{monthly, 1, {2, am}}, + {io, fwrite, ["First of the month!~n"]}} + + {{monthly, 4, {2, am}}, + {io, fwrite, ["Fourth of the month!~n"]}} + + +Adding a cron to the system: + +Job = {{weekly, thu, {2, am}}, + {io, fwrite, ["It's 2 Thursday morning~n"]}}. + +erlcron:cron(Job). + +A simple way to add a daily cron: + +erlcron:at({3, 30, pm}, Fun). + +A simple way to add a job that will be run once in the future. Where +'once' is the number of seconds until it runs. + +erlcron:once(300, Fun). + + +Cancel a running job. + +erlcron:cancel(JobRef). + + +Get the current date time of the system. + +erlcron:datetime(). + + +Set the current date time of the system. Any tests that need to be run +in the interim will be run as the time rolls forward. + +erlcron:set_datetime(DateTime). + + +Set the current date time of the system on all nodes in the +cluster. Any tests that need to be run in the interim will be run as +the time rolls forward. + +erlcron:multi_set_datetime(DateTime). + +Set the current date time of the system on a specific set of nodes in +the cluster. Any tests that need to be run in the interim will be run +as the time rolls forward. + +erlcron:multi_set_datetime(Nodes, DateTime). +
erlware/erlcron
8e6a359f6d0befae5263f663460d9728ed879990
migrate to explicit exported types
diff --git a/ebin/erlcron.app b/ebin/erlcron.app index fabd875..a79c2a1 100644 --- a/ebin/erlcron.app +++ b/ebin/erlcron.app @@ -1,31 +1,31 @@ %% -*- Erlang -*- %% This is the application resource file (.app file) for the ecd_ops application. {application, erlcron, [{description, "Erlang Implementation of cron"}, - {vsn, "0.1"}, + {vsn, "0.2"}, {modules, [erlcron, ecrn_app, ecrn_sup, ecrn_agent, ecrn_test, ecrn_control, ecrn_cron_sup, ecrn_reg]}, {registered, [ecrn_agent]}, {applications, [kernel, stdlib, sasl, eunit]}, {mod, {ecrn_app, []}} ]}. diff --git a/include/erlcron.hrl b/include/erlcron.hrl deleted file mode 100644 index 203a984..0000000 --- a/include/erlcron.hrl +++ /dev/null @@ -1,19 +0,0 @@ - --type seconds() :: integer(). --type date() :: {integer(), integer(), integer()}. --type time() :: {integer(), integer(), integer()}. --type datetime() :: {date(), time()}. - --type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm}. --type constraint() :: {between, cron_time(), cron_time()}. --type duration() :: {integer(), hr | min | sec}. --type period() :: cron_time() | [cron_time()] | {every, duration(), constraint()}. --type dom() :: integer(). --type dow() :: mon | tue | wed | thu | fri | sat | sun. --type callable() :: mfa() | function(). --type run_when() :: {daily, period()} - | {weekly, dow(), period()} - | {monthly, dom(), period()}. - --type job() :: {run_when(), callable()}. --opaque job_ref() :: {integer(), reference()}. diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 63c7646..cfde845 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,480 +1,479 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Agent for cronish testing %%% @end %%%------------------------------------------------------------------- -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1, validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). --include_lib("erlcron/include/erlcron.hrl"). -include("erlcron-internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server with the apropriate job and the appropriate ref %% @end %%-------------------------------------------------------------------- --spec start_link(job_ref(), job()) -> ok. +-spec start_link(erlcron:job_ref(), erlcron:job()) -> ok. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). --spec get_datetime(pid()) -> datetime(). +-spec get_datetime(pid()) -> erlcron:datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). --spec set_datetime(pid(), datetime(), datetime()) -> ok. +-spec set_datetime(pid(), erlcron:datetime(), erlcron:datetime()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %%-------------------------------------------------------------------- %% @doc %% Validate that a run_when spec specified is correct. %% @end %%-------------------------------------------------------------------- --spec validate(run_when()) -> valid | invalid. +-spec validate(erlcron:run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), try until_next_time(NewState, {Spec, undefined}), valid catch _Error:_Reason -> erlang:display(erlang:get_stacktrace()), invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. --spec current_time(record(state)) -> seconds(). +-spec current_time(record(state)) -> erlcron:seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. --spec until_next_milliseconds(record(state), job()) -> seconds(). +-spec until_next_milliseconds(record(state), erlcron:job()) -> erlcron:seconds(). until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. --spec until_next_time(record(state), job()) -> seconds(). +-spec until_next_time(record(state), erlcron:job()) -> erlcron:seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), {Date, _} = current_date(State), Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. %% @spec until_next_daytime(period()) -> seconds() until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @spec last_time(period()) -> seconds() %% @doc Calculates the last time in a given period. last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @spec first_time(period()) -> seconds() %% @doc Calculates the first time in a given period. first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @spec next_time(period(), seconds()) -> seconds() %% @doc Calculates the first time in the given period after the given time. next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @spec resolve_period(period()) -> [seconds()] %% @doc Returns a list of times given a periodic specification. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @spec resolve_time(time()) -> seconds() %% @doc Returns seconds past midnight for a given time. resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @spec resolve_dur(duration()) -> seconds() %% @doc Returns seconds for a given duration. resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @spec resolve_dow(dow()) -> integer() %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @spec until_tomorrow(seconds()) -> seconds() %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @spec until_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/erlcron.erl b/src/erlcron.erl index 2d1e1c9..a776ba8 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,113 +1,147 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). -export([validate/1, cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, multi_set_datetime/1, multi_set_datetime/2]). --include_lib("erlcron/include/erlcron.hrl"). +-export_type([job/0, + job_ref/0, + run_when/0, + callable/0, + dow/0, + dom/0, + period/0, + duration/0, + constraint/0, + cron_time/0, + datetime/0, + time/0, + date/0, + seconds/0]). + +-type seconds() :: integer(). +-type date() :: {integer(), integer(), integer()}. +-type time() :: {integer(), integer(), integer()}. +-type datetime() :: {date(), time()}. + +-type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm}. +-type constraint() :: {between, cron_time(), cron_time()}. +-type duration() :: {integer(), hr | min | sec}. +-type period() :: cron_time() | [cron_time()] | {every, duration(), constraint()}. +-type dom() :: integer(). +-type dow() :: mon | tue | wed | thu | fri | sat | sun. +-type callable() :: mfa() | function(). +-type run_when() :: {once, seconds()} + | {daily, period()} + | {weekly, dow(), period()} + | {monthly, dom(), period()}. + +-type job() :: {run_when(), callable()}. +-opaque job_ref() :: {integer(), reference()}. + %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Check that the spec specified is valid or invalid %% @end %%-------------------------------------------------------------------- -spec validate(run_when()) -> valid | invalid. validate(Spec) -> ecrn_agent:validate(Spec). %%-------------------------------------------------------------------- %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. %% @end %%-------------------------------------------------------------------- -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job), JobRef. %%-------------------------------------------------------------------- %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. %% @end %%-------------------------------------------------------------------- -spec at(time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Run the specified job once after the amount of time specifed. %% @end %%-------------------------------------------------------------------- -spec once(time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Cancel the job specified by the jobref. %% @end %%-------------------------------------------------------------------- -spec cancel(job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). %%-------------------------------------------------------------------- %% @doc %% Get the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- -spec datetime() -> datetime(). datetime() -> ecrn_control:datetime(). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- -spec set_datetime(datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on different nodes. %% @end %%-------------------------------------------------------------------- -spec multi_set_datetime(datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes %% @end %%-------------------------------------------------------------------- -spec multi_set_datetime([node()], datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
7b66bbf98fc6120c1ed6f6fe54269b94b0bdf47f
add spec validation to the api
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index 1a3cfc4..63c7646 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,475 +1,480 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Agent for cronish testing %%% @end %%%------------------------------------------------------------------- -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, - recalculate/1]). + recalculate/1, + validate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include_lib("erlcron/include/erlcron.hrl"). -include("erlcron-internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server with the apropriate job and the appropriate ref %% @end %%-------------------------------------------------------------------- -spec start_link(job_ref(), job()) -> ok. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime(pid()) -> datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), datetime(), datetime()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). %%-------------------------------------------------------------------- %% @doc %% Validate that a run_when spec specified is correct. %% @end %%-------------------------------------------------------------------- -spec validate(run_when()) -> valid | invalid. validate(Spec) -> State = #state{job=undefined, alarm_ref=undefined}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), - case until_next_milliseconds(NewState, {Spec, undefined}) of - {ok, Millis} when is_integer(Millis) -> - valid; - {error, _} -> + try + until_next_time(NewState, {Spec, undefined}), + valid + catch + _Error:_Reason -> + erlang:display(erlang:get_stacktrace()), invalid end. %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time(record(state)) -> seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). %% @doc Calculates the duration in milliseconds until the next time %% a job is to be run. -spec until_next_milliseconds(record(state), job()) -> seconds(). until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> + erlang:display(erlang:get_stacktrace()), throw(invalid_once_exception) end. %% @doc Calculates the duration in seconds until the next time %% a job is to be run. --spec until_next_seconds(record(state), job()) -> seconds(). +-spec until_next_time(record(state), job()) -> seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), - Today = calendar:day_of_the_week(current_date(State)), + {Date, _} = current_date(State), + Today = calendar:day_of_the_week(Date), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> - {ThisYear, ThisMonth, Today} = current_date(State), + {{ThisYear, ThisMonth, Today}, _} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. %% @spec until_next_daytime(period()) -> seconds() until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @spec last_time(period()) -> seconds() %% @doc Calculates the last time in a given period. last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @spec first_time(period()) -> seconds() %% @doc Calculates the first time in a given period. first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @spec next_time(period(), seconds()) -> seconds() %% @doc Calculates the first time in the given period after the given time. next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @spec resolve_period(period()) -> [seconds()] %% @doc Returns a list of times given a periodic specification. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @spec resolve_time(time()) -> seconds() %% @doc Returns seconds past midnight for a given time. -resolve_time({H, M, S}) when is_integer(S) -> +resolve_time({H, M, S}) when H < 24, M < 60, S < 60 -> S + M * 60 + H * 3600; -resolve_time({H, M, S, X}) when is_atom(X) -> +resolve_time({H, M, S, X}) when H < 24, M < 60, S < 60, is_atom(X) -> resolve_time({H, X}) + M * 60 + S; -resolve_time({H, M, X}) when is_atom(X) -> +resolve_time({H, M, X}) when H < 24, M < 60, is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; -resolve_time({H, am}) -> +resolve_time({H, am}) when H < 12 -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; -resolve_time({H, pm}) -> +resolve_time({H, pm}) when H < 12-> (H + 12) * 3600. %% @spec resolve_dur(duration()) -> seconds() %% @doc Returns seconds for a given duration. resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @spec resolve_dow(dow()) -> integer() %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @spec until_tomorrow(seconds()) -> seconds() %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @spec until_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end. diff --git a/src/ecrn_test.erl b/src/ecrn_test.erl index 2d60a61..f037efd 100644 --- a/src/ecrn_test.erl +++ b/src/ecrn_test.erl @@ -1,152 +1,171 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%%------------------------------------------------------------------- -module(ecrn_test). +-compile(export_all). + -include_lib("eunit/include/eunit.hrl"). %% -- tests --------------------------------------------------------------------- cron_test_() -> {setup, fun() -> ecrn_app:manual_start() end, fun(_) -> ecrn_app:manual_stop() end, {with, [fun set_alarm_test/1, fun travel_back_in_time_test/1, fun cancel_alarm_test/1, fun big_time_jump_test/1, - fun cron_test/1]}}. + fun cron_test/1, + fun validation_test/1]}}. set_alarm_test(_) -> EpochDay = {2000,1,1}, EpochDateTime = {EpochDay,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({EpochDay, {8, 59, 59}}), %% %% The alarm should trigger this nearly immediately. %% ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), %% %% The alarm should trigger this 1 second later. %% ?assertMatch(ok, receive ack2 -> ok after 2500 -> timeout end). cancel_alarm_test(_) -> Day = {2000,1,1}, erlcron:set_datetime({Day,{8,0,0}}), AlarmTimeOfDay = {9,0,0}, Self = self(), Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> Self ! ack end), erlcron:cancel(Ref), erlcron:set_datetime({Day, AlarmTimeOfDay}), ?assertMatch(ok, receive ack -> ack after %% There is no event-driven way to %% ensure we never receive an ack. 125 -> ok end). %% Time jumps ahead one day so we should see the alarms from both days. big_time_jump_test(_) -> Day1 = {2000,1,1}, Day2 = {2000,1,2}, EpochDateTime = {Day1,{8,0,0}}, erlcron:set_datetime(EpochDateTime), Alarm1TimeOfDay = {9,0,0}, Alarm2TimeOfDay = {9,0,1}, Self = self(), erlcron:at(Alarm1TimeOfDay, fun(_, _) -> Self ! ack1 end), erlcron:at(Alarm2TimeOfDay, fun(_, _) -> Self ! ack2 end), erlcron:set_datetime({Day2, {9, 10, 0}}), ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack2 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack1 -> ok after 1500 -> timeout end), ?assertMatch(ok, receive ack2 -> ok after 2500 -> timeout end). travel_back_in_time_test(_) -> Seconds = seconds_now(), Past = {{2000,1,1},{12,0,0}}, erlcron:set_datetime(Past), {ExpectedDateTime, _} = erlcron:datetime(), ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), ?assert(ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), ?assert(ExpectedSeconds < Seconds). %% Time jumps ahead one day so we should see the alarms from both days. cron_test(_) -> Day1 = {2000,1,1}, AlarmTimeOfDay = {15,29,58}, erlcron:set_datetime({Day1, AlarmTimeOfDay}), Self = self(), Job = {{daily, {3, 30, pm}}, fun(_, _) -> Self ! ack end}, erlcron:cron(Job), ?assertMatch(ok, receive ack -> ok after 2500 -> timeout end). +validation_test(_) -> + ?assertMatch(valid, ecrn_agent:validate({once, {3, 30, pm}})), + ?assertMatch(valid, ecrn_agent:validate({once, 3600})), + ?assertMatch(valid, ecrn_agent:validate({daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}})), + ?assertMatch(valid, ecrn_agent:validate({daily, {3, 30, pm}})), + ?assertMatch(valid, ecrn_agent:validate({daily, [{1, 10, am}, {1, 07, 30, am}]})), + ?assertMatch(valid, ecrn_agent:validate({weekly, thu, {2, am}})), + ?assertMatch(valid, ecrn_agent:validate({weekly, wed, {2, am}})), + ?assertMatch(valid, ecrn_agent:validate({monthly, 1, {2, am}})), + ?assertMatch(valid, ecrn_agent:validate({monthly, 4, {2, am}})), + ?assertMatch(invalid, ecrn_agent:validate({once, fubar})), + ?assertMatch(invalid, ecrn_agent:validate({daily, {55, 22, am}})), + ?assertMatch(invalid, ecrn_agent:validate({monthly, 65, {55, am}})). + + + %% -- helpers ------------------------------------------------------------------- seconds_now() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). diff --git a/src/erlcron.erl b/src/erlcron.erl index e319315..2d1e1c9 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,105 +1,113 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). --export([cron/1, +-export([validate/1, + cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, - set_datetime/2, multi_set_datetime/1, - multi_set_datetime/2, - multi_set_datetime/3]). + multi_set_datetime/2]). -include_lib("erlcron/include/erlcron.hrl"). %%%=================================================================== %%% API %%%=================================================================== +%%-------------------------------------------------------------------- +%% @doc +%% Check that the spec specified is valid or invalid +%% @end +%%-------------------------------------------------------------------- +-spec validate(run_when()) -> valid | invalid. +validate(Spec) -> + ecrn_agent:validate(Spec). + %%-------------------------------------------------------------------- %% @doc %% Adds a new job to the cron system. Jobs are described in the job() %% spec. It returns the JobRef that can be used to manipulate the job %% after it is created. %% @end %%-------------------------------------------------------------------- -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job), JobRef. %%-------------------------------------------------------------------- %% @doc %% Convienience method to specify a job run to run on a daily basis %% at a specific time. %% @end %%-------------------------------------------------------------------- -spec at(time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Run the specified job once after the amount of time specifed. %% @end %%-------------------------------------------------------------------- -spec once(time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). %%-------------------------------------------------------------------- %% @doc %% Cancel the job specified by the jobref. %% @end %%-------------------------------------------------------------------- -spec cancel(job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). %%-------------------------------------------------------------------- %% @doc %% Get the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- -spec datetime() -> datetime(). datetime() -> ecrn_control:datetime(). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the running erlcron system. %% @end %%-------------------------------------------------------------------- -spec set_datetime(datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on different nodes. %% @end %%-------------------------------------------------------------------- -spec multi_set_datetime(datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). %%-------------------------------------------------------------------- %% @doc %% Set the current date time of the erlcron system running on the %% specified nodes %% @end %%-------------------------------------------------------------------- -spec multi_set_datetime([node()], datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
2e01e46af8001bcc5c4546ea8bd1e632abd662bc
add validation for spec to ecrn_agent
diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl index be9a4b5..1a3cfc4 100644 --- a/src/ecrn_agent.erl +++ b/src/ecrn_agent.erl @@ -1,453 +1,475 @@ %%%------------------------------------------------------------------- %%% @author Eric Merritt <emerritt@ecdmarket.com> %%% @doc %%% Agent for cronish testing %%% @end %%%------------------------------------------------------------------- -module(ecrn_agent). -behaviour(gen_server). %% API -export([start_link/2, cancel/1, get_datetime/1, set_datetime/3, recalculate/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -include_lib("erlcron/include/erlcron.hrl"). -include("erlcron-internal.hrl"). -record(state, {job, alarm_ref, referenced_seconds, seconds_at_reference, timeout_type, fast_forward=false}). -define(MILLISECONDS, 1000). -define(WAIT_BEFORE_RUN, 2000). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server with the apropriate job and the appropriate ref %% @end %%-------------------------------------------------------------------- -spec start_link(job_ref(), job()) -> ok. start_link(JobRef, Job) -> gen_server:start_link(?MODULE, [JobRef, Job], []). -spec get_datetime(pid()) -> datetime(). get_datetime(Pid) -> gen_server:call(Pid, get_datetime). -spec cancel(pid()) -> ok. cancel(Pid) -> gen_server:cast(Pid, shutdown). -spec set_datetime(pid(), datetime(), datetime()) -> ok. set_datetime(Pid, DateTime, Actual) -> gen_server:cast(Pid, {set_datetime, DateTime, Actual}). -spec recalculate(pid()) -> ok. recalculate(Pid) -> gen_server:cast(Pid, recalculate). +%%-------------------------------------------------------------------- +%% @doc +%% Validate that a run_when spec specified is correct. +%% @end +%%-------------------------------------------------------------------- +-spec validate(run_when()) -> valid | invalid. +validate(Spec) -> + State = #state{job=undefined, + alarm_ref=undefined}, + {DateTime, Actual} = ecrn_control:datetime(), + NewState = set_internal_time(State, DateTime, Actual), + case until_next_milliseconds(NewState, {Spec, undefined}) of + {ok, Millis} when is_integer(Millis) -> + valid; + {error, _} -> + invalid + end. + + %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @private %% @doc %% Initiates the server %% %% @spec init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([JobRef, Job]) -> State = #state{job=Job, alarm_ref=JobRef}, {DateTime, Actual} = ecrn_control:datetime(), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, Job) of {ok, Millis} when is_integer(Millis) -> ecrn_reg:register(JobRef, self()), {ok, NewState, Millis}; {error, _} -> {stop, normal} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling call messages %% %% @spec handle_call(Request, From, State) -> %% {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_call(_Msg, _From, State) -> case until_next_milliseconds(State, State#state.job) of {ok, Millis} -> {reply, ok, State, Millis}; {error, _} -> {stop, normal, ok, State} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling cast messages %% %% @spec handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_cast(shutdown, State) -> {stop, normal, State}; handle_cast({set_datetime, DateTime, Actual}, State) -> fast_forward(State#state{fast_forward=true}, DateTime), NewState = set_internal_time(State, DateTime, Actual), case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end. %%-------------------------------------------------------------------- %% @private %% @doc %% Handling all non call/cast messages %% %% @spec handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% @end %%-------------------------------------------------------------------- handle_info(timeout, State = #state{job = {{once, _}, _}}) -> do_job_run(State, State#state.job), {stop, normal, State}; handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> NewState = State#state{timeout_type=normal}, case until_next_milliseconds(NewState, NewState#state.job) of {ok, Millis} -> {noreply, NewState, Millis}; {error, _} -> {stop, normal, NewState} end; handle_info(timeout, State = #state{job = Job}) -> do_job_run(State, Job), NewState = State#state{timeout_type=wait_before_run}, {noreply, NewState, ?WAIT_BEFORE_RUN}. %%-------------------------------------------------------------------- %% @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. %% %% @spec terminate(Reason, State) -> void() %% @end %%-------------------------------------------------------------------- terminate(_Reason, #state{alarm_ref=Ref}) -> ecrn_reg:unregister(Ref), ok. %%-------------------------------------------------------------------- %% @private %% @doc %% Convert process state when code is changed %% %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} %% @end %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> RunFun = fun() -> Job(State#state.alarm_ref, current_date(State)) end, proc_lib:spawn(RunFun); do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> proc_lib:spawn(M, F, A). %% @doc Returns the current time, in seconds past midnight. -spec current_time(record(state)) -> seconds(). current_time(State) -> {_, {H,M,S}} = current_date(State), S + M * 60 + H * 3600. current_date(State = #state{fast_forward=true}) -> calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); current_date(State) -> Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + State#state.referenced_seconds)). +%% @doc Calculates the duration in milliseconds until the next time +%% a job is to be run. +-spec until_next_milliseconds(record(state), job()) -> seconds(). until_next_milliseconds(State, Job) -> try Millis = until_next_time(State, Job) * ?MILLISECONDS, {ok, Millis} catch throw:invalid_once_exception -> {error, invalid_once_exception} end. normalize_seconds(State, Seconds) -> case Seconds - current_time(State) of Value when Value >= 0 -> Value; _ -> throw(invalid_once_exception) end. -%% @spec until_next_seconds(job()) -> seconds() %% @doc Calculates the duration in seconds until the next time %% a job is to be run. +-spec until_next_seconds(record(state), job()) -> seconds(). until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> Seconds; until_next_time(State, {{once, {H, M, S}}, _What}) when is_integer(H), is_integer(M), is_integer(S) -> normalize_seconds(State, S + (M + (H * 60)) * 60); until_next_time(State, {{once, Period}, _What}) -> normalize_seconds(State, resolve_time(Period)); until_next_time(State, {{daily, Period}, _What}) -> until_next_daytime(State, Period); until_next_time(State, {{weekly, DoW, Period}, _What}) -> OnDay = resolve_dow(DoW), Today = calendar:day_of_the_week(current_date(State)), case Today of OnDay -> until_next_daytime_or_days_from_now(State, Period, 7); Today when Today < OnDay -> until_days_from_now(State, Period, OnDay - Today); Today when Today > OnDay -> until_days_from_now(State, Period, (OnDay+7) - Today) end; until_next_time(State, {{monthly, DoM, Period}, _What}) -> {ThisYear, ThisMonth, Today} = current_date(State), {NextYear, NextMonth} = case ThisMonth of 12 -> {ThisYear + 1, 1}; _ -> {ThisYear, ThisMonth + 1} end, D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), Days = D2 - D1, case Today of DoM -> until_next_daytime_or_days_from_now(State, Period, Days); _ -> until_days_from_now(State, Period, Days) end. %% @doc Calculates the duration in seconds until the next time this %% period is to occur during the day. %% @spec until_next_daytime(period()) -> seconds() until_next_daytime(State, Period) -> StartTime = first_time(Period), EndTime = last_time(Period), case current_time(State) of T when T > EndTime -> until_tomorrow(State, StartTime); T -> next_time(Period, T) - T end. %% @spec last_time(period()) -> seconds() %% @doc Calculates the last time in a given period. last_time(Period) -> hd(lists:reverse(lists:sort(resolve_period(Period)))). %% @spec first_time(period()) -> seconds() %% @doc Calculates the first time in a given period. first_time(Period) -> hd(lists:sort(resolve_period(Period))). %% @spec next_time(period(), seconds()) -> seconds() %% @doc Calculates the first time in the given period after the given time. next_time(Period, Time) -> R = lists:sort(resolve_period(Period)), lists:foldl(fun(X, A) -> case X of T when T >= Time, T < A -> T; _ -> A end end, 24*3600, R). %% @spec resolve_period(period()) -> [seconds()] %% @doc Returns a list of times given a periodic specification. resolve_period([]) -> []; resolve_period([H | T]) -> resolve_period(H) ++ resolve_period(T); resolve_period({every, Duration, {between, TimeA, TimeB}}) -> Period = resolve_dur(Duration), StartTime = resolve_time(TimeA), EndTime = resolve_time(TimeB), resolve_period0(Period, StartTime, EndTime, []); resolve_period(Time) -> [resolve_time(Time)]. resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> Acc; resolve_period0(Period, Time, EndTime, Acc) -> resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). %% @spec resolve_time(time()) -> seconds() %% @doc Returns seconds past midnight for a given time. resolve_time({H, M, S}) when is_integer(S) -> S + M * 60 + H * 3600; resolve_time({H, M, S, X}) when is_atom(X) -> resolve_time({H, X}) + M * 60 + S; resolve_time({H, M, X}) when is_atom(X) -> resolve_time({H, X}) + M * 60; resolve_time({12, am}) -> 0; resolve_time({H, am}) -> H * 3600; resolve_time({12, pm}) -> 12 * 3600; resolve_time({H, pm}) -> (H + 12) * 3600. %% @spec resolve_dur(duration()) -> seconds() %% @doc Returns seconds for a given duration. resolve_dur({Hour, hr}) -> Hour * 3600; resolve_dur({Min, min}) -> Min * 60; resolve_dur({Sec, sec}) -> Sec. %% @spec resolve_dow(dow()) -> integer() %% @doc Returns the number of the given day of the week. See the calendar %% module for day numbers. resolve_dow(mon) -> 1; resolve_dow(tue) -> 2; resolve_dow(wed) -> 3; resolve_dow(thu) -> 4; resolve_dow(fri) -> 5; resolve_dow(sat) -> 6; resolve_dow(sun) -> 7. %% @spec until_tomorrow(seconds()) -> seconds() %% @doc Calculates the duration in seconds until the given time occurs %% tomorrow. until_tomorrow(State, StartTime) -> (StartTime + 24*3600) - current_time(State). %% @spec until_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs several days from now. until_days_from_now(State, Period, Days) -> Days * 24 * 3600 + until_next_daytime(State, Period). %% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds() %% @doc Calculates the duration in seconds until the given period %% occurs, which may be today or several days from now. until_next_daytime_or_days_from_now(State, Period, Days) -> CurrentTime = current_time(State), case last_time(Period) of T when T < CurrentTime -> until_days_from_now(State, Period, Days-1); _ -> until_next_daytime(State, Period) end. set_internal_time(State, RefDate, CurrentSeconds) -> NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), State#state{referenced_seconds=NewSeconds, seconds_at_reference=CurrentSeconds}. ceiling(X) -> T = erlang:trunc(X), case (X - T) of Neg when Neg < 0 -> T; Pos when Pos > 0 -> T + 1; _ -> T end. fast_forward(State, NewDate) -> try Seconds = until_next_time(State, State#state.job), NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), Span = NewSeconds - State#state.referenced_seconds, case Span > Seconds of true -> RefSecs = State#state.referenced_seconds, NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, do_job_run(State, State#state.job), fast_forward(NewState, NewDate); false -> ok end catch throw:invalid_once_exception -> {error, invalid_once_exception} end.
erlware/erlcron
aa1c5e937b7853caf49eb28ed07a60dd78122d4d
Add more documentation, fix specs in erlcron
diff --git a/src/erlcron.erl b/src/erlcron.erl index d94fbd9..e319315 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,57 +1,105 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). -export([cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, set_datetime/2, multi_set_datetime/1, multi_set_datetime/2, multi_set_datetime/3]). -include_lib("erlcron/include/erlcron.hrl"). +%%%=================================================================== +%%% API +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @doc +%% Adds a new job to the cron system. Jobs are described in the job() +%% spec. It returns the JobRef that can be used to manipulate the job +%% after it is created. +%% @end +%%-------------------------------------------------------------------- -spec cron(job()) -> job_ref(). cron(Job) -> JobRef = make_ref(), ecrn_cron_sup:add_job(JobRef, Job), JobRef. +%%-------------------------------------------------------------------- +%% @doc +%% Convienience method to specify a job run to run on a daily basis +%% at a specific time. +%% @end +%%-------------------------------------------------------------------- -spec at(time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). +%%-------------------------------------------------------------------- +%% @doc +%% Run the specified job once after the amount of time specifed. +%% @end +%%-------------------------------------------------------------------- -spec once(time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). +%%-------------------------------------------------------------------- +%% @doc +%% Cancel the job specified by the jobref. +%% @end +%%-------------------------------------------------------------------- -spec cancel(job_ref()) -> ok. cancel(JobRef) -> ecrn_control:cancel(JobRef). - +%%-------------------------------------------------------------------- +%% @doc +%% Get the current date time of the running erlcron system. +%% @end +%%-------------------------------------------------------------------- -spec datetime() -> datetime(). datetime() -> ecrn_control:datetime(). +%%-------------------------------------------------------------------- +%% @doc +%% Set the current date time of the running erlcron system. +%% @end +%%-------------------------------------------------------------------- -spec set_datetime(datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). +%%-------------------------------------------------------------------- +%% @doc +%% Set the current date time of the erlcron system running on different nodes. +%% @end +%%-------------------------------------------------------------------- -spec multi_set_datetime(datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). + +%%-------------------------------------------------------------------- +%% @doc +%% Set the current date time of the erlcron system running on the +%% specified nodes +%% @end +%%-------------------------------------------------------------------- -spec multi_set_datetime([node()], datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime).
erlware/erlcron
b82042ef62d4f2eb959a1d72453156f55f539f6d
Remove invalide functions, uneccesary documentation
diff --git a/src/erlcron.erl b/src/erlcron.erl index 3f8f190..d94fbd9 100644 --- a/src/erlcron.erl +++ b/src/erlcron.erl @@ -1,135 +1,57 @@ %%%---------------------------------------------------------------- %%% @author Eric Newhuis <enewhuis@ecdmarket.com> %%% @copyright 2009-2010 eCD Market %%%----------------------------------------------------------------, -module(erlcron). -export([cron/1, at/2, once/2, cancel/1, datetime/0, set_datetime/1, set_datetime/2, multi_set_datetime/1, multi_set_datetime/2, multi_set_datetime/3]). -include_lib("erlcron/include/erlcron.hrl"). -%% @doc Simple job scheduler for Erlang/OTP -%% -%% This is a simple utility which schedules jobs to be -%% run at a given time or periodically -%% -%% The synax of a job description is quite different from -%% <code>crontab</code>. It is (in this author's opinion) easier to read -%% and is much more in keeping with the Erlang tradition. It is not -%% quite as expressive as <code>cron</code> but this can be compensated -%% for by adding multiple jobs. -%% -%% No output is logged or mailed to anyone. If you want output to -%% be logged or mailed, you must explicitly specify that as part of the -%% job. -%% -%% This does not poll the system on a minute-by-minute -%% basis like <code>cron</code> does. Each job is assigned to a single -%% (Erlang) process. The time until it is to run next is calculated, -%% and the process sleeps for exactly that long. -%% -%% Unlike <code>cron</code>'s one-minute resolution, <code>crone</code> -%% has a 2-second resolution (actually 1 second, but after running the -%% job, the process waits an extra second to avoid accidentally running it -%% more than once.) -%% -%% Because it does not wake up every minute, and because it does not -%% have a fixed configuration file, <code>crone</code> must be stopped and -%% restarted if the user wishes to change the scheduled jobs. -%% -%% It does not handle Daylight Savings Time (or other -%% cases when the system clock is altered) gracefully, and it is recommended -%% that it be stopped and restarted on such occasions. -%% -%% Cron Job Examples -%% -%% <code> -%% -%% {{once, {3, 30, pm}}, -%% {io, fwrite, ["Hello, world!~n"]}} -%% -%% {{once, {12, 23, 32}}, -%% {io, fwrite, ["Hello, world!~n"]}} -%% -%% {{once, 3600}, -%% {io, fwrite, ["Hello, world!~n"]}} -%% -%% {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, -%% {io, fwrite, ["Hello, world!~n"]}} -%% -%% {{daily, {3, 30, pm}}, -%% fun() -> io:fwrite("It's three thirty~n") end} -%% -%% {{daily, [{1, 10, am}, {1, 07, 30, am}]}, -%% {io, fwrite, ["Bing~n"]}} -%% -%% {{weekly, thu, {2, am}}, -%% {io, fwrite, ["It's 2 Thursday morning~n"]}} -%% -%% {{weekly, wed, {2, am}}, -%% {fuxbn() -> io:fwrite("It's 2 Wednesday morning~n") end} -%% -%% {{weekly, fri, {2, am}}, -%% {io, fwrite, ["It's 2 Friday morning~n"]}} -%% -%% {{monthly, 1, {2, am}}, -%% {io, fwrite, ["First of the month!~n"]}} -%% -%% {{monthly, 4, {2, am}}, -%% {io, fwrite, ["Fourth of the month!~n"]}} -%% </code> -%% -%% @end - --spec cron(job()) -> ok. +-spec cron(job()) -> job_ref(). cron(Job) -> - AlarmRef = make_ref(), - ecrn_cron_sup:add_job(AlarmRef, Job), - AlarmRef. + JobRef = make_ref(), + ecrn_cron_sup:add_job(JobRef, Job), + JobRef. --spec at(time() | seconds(), function()) -> ok. +-spec at(time() | seconds(), function()) -> job_ref(). at(When, Fun) -> Job = {{daily, When}, Fun}, cron(Job). --spec once(time() | seconds(), function()) -> ok. +-spec once(time() | seconds(), function()) -> job_ref(). once(When, Fun) -> Job = {{once, When}, Fun}, cron(Job). -spec cancel(job_ref()) -> ok. -cancel(AlarmRef) -> - ecrn_control:cancel(AlarmRef). +cancel(JobRef) -> + ecrn_control:cancel(JobRef). -spec datetime() -> datetime(). datetime() -> ecrn_control:datetime(). -spec set_datetime(datetime()) -> ok. set_datetime(DateTime) -> ecrn_control:set_datetime(DateTime). --spec set_datetime(datetime(), testing | production) -> ok. -set_datetime(DateTime, Atom) when is_atom(Atom) -> - ecrn_control:set_datetime(DateTime, Atom). -spec multi_set_datetime(datetime()) -> ok. multi_set_datetime(DateTime) -> ecrn_control:multi_set_datetime([node()|nodes()], DateTime). -spec multi_set_datetime([node()], datetime()) -> ok. multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> ecrn_control:multi_set_datetime(Nodes, DateTime). -multi_set_datetime(Nodes, DateTime, testing) when is_list(Nodes) -> - ecrn_control:multi_set_datetime(Nodes, DateTime, testing).
erlware/erlcron
0b9441a4d44713b7ffdfec44adfb98339c7c5440
Enhance project README
diff --git a/README b/README index b67959a..1187944 100644 --- a/README +++ b/README @@ -1,3 +1,113 @@ -This provides testable cronish like functionality for Erlang systems, -with the ability to arbitrarily set the time and place along with -fastforwarding through tests. See erlcron.erl for more documentation. \ No newline at end of file +Erlcron provides testable cronish like functionality for Erlang +systems, with the ability to arbitrarily set the time and place along +with fastforwarding through tests. See erlcron.erl for more +documentation. + +The synax of a job description is quite different from crontab. It is +(in this author's opinion) easier to read and is much more in keeping +with the Erlang tradition. It is not quite as expressive as cron but +this can be compensated for by adding multiple jobs. + +No output is logged or mailed to anyone. If you want output to be +logged or mailed, you must explicitly specify that as part of the +job. + +This does not poll the system on a minute-by-minute basis like cron +does. Each job is assigned to a single (Erlang) process. The time +until it is to run next is calculated, and the process sleeps for +exactly that long. + +Unlike cron's one-minute resolution, crone +has a 2-second resolution (actually 1 second, but after running the +job, the process waits an extra second to avoid accidentally running it +more than once.) + +Because it does not wake up every minute, and because it does not +have a fixed configuration file, crone must be stopped and +restarted if the user wishes to change the scheduled jobs. + +It does not handle Daylight Savings Time (or other +cases when the system clock is altered) gracefully, and it is recommended +that it be stopped and restarted on such occasions. + +Cron Job Description Examples: + + {{once, {3, 30, pm}}, + {io, fwrite, ["Hello, world!~n"]}} + + {{once, {12, 23, 32}}, + {io, fwrite, ["Hello, world!~n"]}} + + {{once, 3600}, + {io, fwrite, ["Hello, world!~n"]}} + + {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, + {io, fwrite, ["Hello, world!~n"]}} + + {{daily, {3, 30, pm}}, + fun() -> io:fwrite("It's three thirty~n") end} + + {{daily, [{1, 10, am}, {1, 07, 30, am}]}, + {io, fwrite, ["Bing~n"]}} + + {{weekly, thu, {2, am}}, + {io, fwrite, ["It's 2 Thursday morning~n"]}} + + {{weekly, wed, {2, am}}, + {fuxbn() -> io:fwrite("It's 2 Wednesday morning~n") end} + + {{weekly, fri, {2, am}}, + {io, fwrite, ["It's 2 Friday morning~n"]}} + + {{monthly, 1, {2, am}}, + {io, fwrite, ["First of the month!~n"]}} + + {{monthly, 4, {2, am}}, + {io, fwrite, ["Fourth of the month!~n"]}} + + +Adding a cron to the system: + +Job = {{weekly, thu, {2, am}}, + {io, fwrite, ["It's 2 Thursday morning~n"]}}. + +erlcron:cron(Job). + +A simple way to add a daily cron: + +erlcron:at({3, 30, pm}, Fun). + +A simple way to add a job that will be run once in the future. Where +'once' is the number of seconds until it runs. + +erlcron:once(300, Fun). + + +Cancel a running job. + +erlcron:cancel(JobRef). + + +Get the current date time of the system. + +erlcron:datetime(). + + +Set the current date time of the system. Any tests that need to be run +in the interim will be run as the time rolls forward. + +erlcron:set_datetime(DateTime). + + +Set the current date time of the system on all nodes in the +cluster. Any tests that need to be run in the interim will be run as +the time rolls forward. + +erlcron:multi_set_datetime(DateTime). + +Set the current date time of the system on a specific set of nodes in +the cluster. Any tests that need to be run in the interim will be run +as the time rolls forward. + +erlcron:multi_set_datetime(Nodes, DateTime). +
erlware/erlcron
6e1e8ea4c5db863b6215e3212a3c791278c8a61a
Added erlcron sources
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..901a704 --- /dev/null +++ b/LICENSE @@ -0,0 +1,67 @@ +Copyright (c)2010 eCD Market + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + Neither the name of Cat's Eye Technologies nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + + + +Some code originally copyrighted -> + +Copyright (c)2002 Cat's Eye Technologies. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + Neither the name of Cat's Eye Technologies nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND +CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/README b/README index e69de29..b67959a 100644 --- a/README +++ b/README @@ -0,0 +1,3 @@ +This provides testable cronish like functionality for Erlang systems, +with the ability to arbitrarily set the time and place along with +fastforwarding through tests. See erlcron.erl for more documentation. \ No newline at end of file diff --git a/ebin/erlcron.app b/ebin/erlcron.app new file mode 100644 index 0000000..fabd875 --- /dev/null +++ b/ebin/erlcron.app @@ -0,0 +1,31 @@ +%% -*- Erlang -*- +%% This is the application resource file (.app file) for the ecd_ops application. + +{application, erlcron, + [{description, + "Erlang Implementation of cron"}, + + {vsn, "0.1"}, + + {modules, + [erlcron, + ecrn_app, + ecrn_sup, + ecrn_agent, + ecrn_test, + ecrn_control, + ecrn_cron_sup, + ecrn_reg]}, + + {registered, + [ecrn_agent]}, + + {applications, + [kernel, + stdlib, + sasl, + eunit]}, + + {mod, + {ecrn_app, []}} + ]}. diff --git a/include/erlcron.hrl b/include/erlcron.hrl new file mode 100644 index 0000000..203a984 --- /dev/null +++ b/include/erlcron.hrl @@ -0,0 +1,19 @@ + +-type seconds() :: integer(). +-type date() :: {integer(), integer(), integer()}. +-type time() :: {integer(), integer(), integer()}. +-type datetime() :: {date(), time()}. + +-type cron_time() :: {integer(), am | pm} | {integer(), integer(), am | pm}. +-type constraint() :: {between, cron_time(), cron_time()}. +-type duration() :: {integer(), hr | min | sec}. +-type period() :: cron_time() | [cron_time()] | {every, duration(), constraint()}. +-type dom() :: integer(). +-type dow() :: mon | tue | wed | thu | fri | sat | sun. +-type callable() :: mfa() | function(). +-type run_when() :: {daily, period()} + | {weekly, dow(), period()} + | {monthly, dom(), period()}. + +-type job() :: {run_when(), callable()}. +-opaque job_ref() :: {integer(), reference()}. diff --git a/sinan.cfg b/sinan.cfg new file mode 100644 index 0000000..f5ed897 --- /dev/null +++ b/sinan.cfg @@ -0,0 +1,12 @@ + +project : { + name : sinan + vsn : "0.0.1.0" + +}, + +tasks : { + build : { + compile_args : "-W1 +debug_info" + }, +}, diff --git a/src/ecrn_agent.erl b/src/ecrn_agent.erl new file mode 100644 index 0000000..be9a4b5 --- /dev/null +++ b/src/ecrn_agent.erl @@ -0,0 +1,453 @@ +%%%------------------------------------------------------------------- +%%% @author Eric Merritt <emerritt@ecdmarket.com> +%%% @doc +%%% Agent for cronish testing +%%% @end +%%%------------------------------------------------------------------- +-module(ecrn_agent). + +-behaviour(gen_server). + +%% API +-export([start_link/2, + cancel/1, + get_datetime/1, + set_datetime/3, + recalculate/1]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + terminate/2, code_change/3]). + +-include_lib("erlcron/include/erlcron.hrl"). +-include("erlcron-internal.hrl"). + +-record(state, {job, + alarm_ref, + referenced_seconds, + seconds_at_reference, + timeout_type, + fast_forward=false}). + +-define(MILLISECONDS, 1000). +-define(WAIT_BEFORE_RUN, 2000). + +%%%=================================================================== +%%% API +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @doc +%% Starts the server with the apropriate job and the appropriate ref +%% @end +%%-------------------------------------------------------------------- +-spec start_link(job_ref(), job()) -> ok. +start_link(JobRef, Job) -> + gen_server:start_link(?MODULE, [JobRef, Job], []). + +-spec get_datetime(pid()) -> datetime(). +get_datetime(Pid) -> + gen_server:call(Pid, get_datetime). + +-spec cancel(pid()) -> ok. +cancel(Pid) -> + gen_server:cast(Pid, shutdown). + +-spec set_datetime(pid(), datetime(), datetime()) -> ok. +set_datetime(Pid, DateTime, Actual) -> + gen_server:cast(Pid, {set_datetime, DateTime, Actual}). + +-spec recalculate(pid()) -> ok. +recalculate(Pid) -> + gen_server:cast(Pid, recalculate). + +%%%=================================================================== +%%% gen_server callbacks +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Initiates the server +%% +%% @spec init(Args) -> {ok, State} | +%% {ok, State, Timeout} | +%% ignore | +%% {stop, Reason} +%% @end +%%-------------------------------------------------------------------- +init([JobRef, Job]) -> + State = #state{job=Job, + alarm_ref=JobRef}, + {DateTime, Actual} = ecrn_control:datetime(), + NewState = set_internal_time(State, DateTime, Actual), + case until_next_milliseconds(NewState, Job) of + {ok, Millis} when is_integer(Millis) -> + ecrn_reg:register(JobRef, self()), + {ok, NewState, Millis}; + {error, _} -> + {stop, normal} + end. + + + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling call messages +%% +%% @spec handle_call(Request, From, State) -> +%% {reply, Reply, State} | +%% {reply, Reply, State, Timeout} | +%% {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, Reply, State} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_call(_Msg, _From, State) -> + case until_next_milliseconds(State, State#state.job) of + {ok, Millis} -> + {reply, ok, State, Millis}; + {error, _} -> + {stop, normal, ok, State} + end. + + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling cast messages +%% +%% @spec handle_cast(Msg, State) -> {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_cast(shutdown, State) -> + {stop, normal, State}; +handle_cast({set_datetime, DateTime, Actual}, State) -> + fast_forward(State#state{fast_forward=true}, DateTime), + NewState = set_internal_time(State, DateTime, Actual), + case until_next_milliseconds(NewState, NewState#state.job) of + {ok, Millis} -> + {noreply, NewState, Millis}; + {error, _} -> + {stop, normal, NewState} + end. + + + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling all non call/cast messages +%% +%% @spec handle_info(Info, State) -> {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_info(timeout, State = #state{job = {{once, _}, _}}) -> + do_job_run(State, State#state.job), + {stop, normal, State}; +handle_info(timeout, State = #state{timeout_type=wait_before_run}) -> + NewState = State#state{timeout_type=normal}, + case until_next_milliseconds(NewState, NewState#state.job) of + {ok, Millis} -> + {noreply, NewState, Millis}; + {error, _} -> + {stop, normal, NewState} + end; +handle_info(timeout, State = #state{job = Job}) -> + do_job_run(State, Job), + NewState = State#state{timeout_type=wait_before_run}, + {noreply, NewState, ?WAIT_BEFORE_RUN}. + + + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% This function is called by a gen_server when it is about to +%% terminate. It should be the opposite of Module:init/1 and do any +%% necessary cleaning up. When it returns, the gen_server terminates +%% with Reason. The return value is ignored. +%% +%% @spec terminate(Reason, State) -> void() +%% @end +%%-------------------------------------------------------------------- +terminate(_Reason, #state{alarm_ref=Ref}) -> + ecrn_reg:unregister(Ref), + ok. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Convert process state when code is changed +%% +%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} +%% @end +%%-------------------------------------------------------------------- +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%%%=================================================================== +%%% Internal functions +%%%=================================================================== +do_job_run(State, {_, Job}) when is_record(State, state), is_function(Job) -> + RunFun = fun() -> + Job(State#state.alarm_ref, current_date(State)) + end, + proc_lib:spawn(RunFun); +do_job_run(State, {_, {M, F, A}}) when is_record(State, state) -> + proc_lib:spawn(M, F, A). + +%% @doc Returns the current time, in seconds past midnight. +-spec current_time(record(state)) -> seconds(). +current_time(State) -> + {_, {H,M,S}} = current_date(State), + S + M * 60 + H * 3600. + + +current_date(State = #state{fast_forward=true}) -> + calendar:gregorian_seconds_to_datetime(State#state.referenced_seconds); +current_date(State) -> + Elapsed = ?EPOC_SECONDS - State#state.seconds_at_reference, + calendar:gregorian_seconds_to_datetime(ceiling(Elapsed + + State#state.referenced_seconds)). + + +until_next_milliseconds(State, Job) -> + try + Millis = until_next_time(State, Job) * ?MILLISECONDS, + {ok, Millis} + catch + throw:invalid_once_exception -> + {error, invalid_once_exception} + end. + +normalize_seconds(State, Seconds) -> + case Seconds - current_time(State) of + Value when Value >= 0 -> + Value; + _ -> + throw(invalid_once_exception) + end. + +%% @spec until_next_seconds(job()) -> seconds() +%% @doc Calculates the duration in seconds until the next time +%% a job is to be run. +until_next_time(_State, {{once, Seconds}, _What}) when is_integer(Seconds) -> + Seconds; +until_next_time(State, {{once, {H, M, S}}, _What}) + when is_integer(H), is_integer(M), is_integer(S) -> + normalize_seconds(State, S + (M + (H * 60)) * 60); +until_next_time(State, {{once, Period}, _What}) -> + normalize_seconds(State, resolve_time(Period)); +until_next_time(State, {{daily, Period}, _What}) -> + until_next_daytime(State, Period); +until_next_time(State, {{weekly, DoW, Period}, _What}) -> + OnDay = resolve_dow(DoW), + Today = calendar:day_of_the_week(current_date(State)), + case Today of + OnDay -> + until_next_daytime_or_days_from_now(State, Period, 7); + Today when Today < OnDay -> + until_days_from_now(State, Period, OnDay - Today); + Today when Today > OnDay -> + until_days_from_now(State, Period, (OnDay+7) - Today) + end; +until_next_time(State, {{monthly, DoM, Period}, _What}) -> + {ThisYear, ThisMonth, Today} = current_date(State), + {NextYear, NextMonth} = + case ThisMonth of + 12 -> + {ThisYear + 1, 1}; + _ -> + {ThisYear, ThisMonth + 1} + end, + D1 = calendar:date_to_gregorian_days(ThisYear, ThisMonth, Today), + D2 = calendar:date_to_gregorian_days(NextYear, NextMonth, DoM), + Days = D2 - D1, + case Today of + DoM -> + until_next_daytime_or_days_from_now(State, Period, Days); + _ -> + until_days_from_now(State, Period, Days) + end. + + + +%% @doc Calculates the duration in seconds until the next time this +%% period is to occur during the day. +%% @spec until_next_daytime(period()) -> seconds() +until_next_daytime(State, Period) -> + StartTime = first_time(Period), + EndTime = last_time(Period), + case current_time(State) of + T when T > EndTime -> + until_tomorrow(State, StartTime); + T -> + next_time(Period, T) - T + end. + + +%% @spec last_time(period()) -> seconds() +%% @doc Calculates the last time in a given period. + +last_time(Period) -> + hd(lists:reverse(lists:sort(resolve_period(Period)))). + +%% @spec first_time(period()) -> seconds() +%% @doc Calculates the first time in a given period. + +first_time(Period) -> + hd(lists:sort(resolve_period(Period))). + +%% @spec next_time(period(), seconds()) -> seconds() +%% @doc Calculates the first time in the given period after the given time. + +next_time(Period, Time) -> + R = lists:sort(resolve_period(Period)), + lists:foldl(fun(X, A) -> + case X of + T when T >= Time, T < A -> + T; + _ -> + A + end + end, 24*3600, R). + +%% @spec resolve_period(period()) -> [seconds()] +%% @doc Returns a list of times given a periodic specification. + +resolve_period([]) -> + []; +resolve_period([H | T]) -> + resolve_period(H) ++ resolve_period(T); +resolve_period({every, Duration, {between, TimeA, TimeB}}) -> + Period = resolve_dur(Duration), + StartTime = resolve_time(TimeA), + EndTime = resolve_time(TimeB), + resolve_period0(Period, StartTime, EndTime, []); +resolve_period(Time) -> + [resolve_time(Time)]. + +resolve_period0(_, Time, EndTime, Acc) when Time >= EndTime -> + Acc; +resolve_period0(Period, Time, EndTime, Acc) -> + resolve_period0(Period, Time + Period, EndTime, [Time | Acc]). + +%% @spec resolve_time(time()) -> seconds() +%% @doc Returns seconds past midnight for a given time. + +resolve_time({H, M, S}) when is_integer(S) -> + S + M * 60 + H * 3600; +resolve_time({H, M, S, X}) when is_atom(X) -> + resolve_time({H, X}) + M * 60 + S; +resolve_time({H, M, X}) when is_atom(X) -> + resolve_time({H, X}) + M * 60; +resolve_time({12, am}) -> + 0; +resolve_time({H, am}) -> + H * 3600; +resolve_time({12, pm}) -> + 12 * 3600; +resolve_time({H, pm}) -> + (H + 12) * 3600. + +%% @spec resolve_dur(duration()) -> seconds() +%% @doc Returns seconds for a given duration. + +resolve_dur({Hour, hr}) -> + Hour * 3600; +resolve_dur({Min, min}) -> + Min * 60; +resolve_dur({Sec, sec}) -> + Sec. + +%% @spec resolve_dow(dow()) -> integer() +%% @doc Returns the number of the given day of the week. See the calendar +%% module for day numbers. + +resolve_dow(mon) -> + 1; +resolve_dow(tue) -> + 2; +resolve_dow(wed) -> + 3; +resolve_dow(thu) -> + 4; +resolve_dow(fri) -> + 5; +resolve_dow(sat) -> + 6; +resolve_dow(sun) -> + 7. + +%% @spec until_tomorrow(seconds()) -> seconds() +%% @doc Calculates the duration in seconds until the given time occurs +%% tomorrow. + +until_tomorrow(State, StartTime) -> + (StartTime + 24*3600) - current_time(State). + +%% @spec until_days_from_now(period(), integer()) -> seconds() + +%% @doc Calculates the duration in seconds until the given period +%% occurs several days from now. + +until_days_from_now(State, Period, Days) -> + Days * 24 * 3600 + until_next_daytime(State, Period). + +%% @spec until_next_daytime_or_days_from_now(period(), integer()) -> seconds() +%% @doc Calculates the duration in seconds until the given period +%% occurs, which may be today or several days from now. + +until_next_daytime_or_days_from_now(State, Period, Days) -> + CurrentTime = current_time(State), + case last_time(Period) of + T when T < CurrentTime -> + until_days_from_now(State, Period, Days-1); + _ -> + until_next_daytime(State, Period) + end. + + + +set_internal_time(State, RefDate, CurrentSeconds) -> + NewSeconds = calendar:datetime_to_gregorian_seconds(RefDate), + State#state{referenced_seconds=NewSeconds, + seconds_at_reference=CurrentSeconds}. + +ceiling(X) -> + T = erlang:trunc(X), + case (X - T) of + Neg when Neg < 0 -> T; + Pos when Pos > 0 -> T + 1; + _ -> T + end. + +fast_forward(State, NewDate) -> + try + Seconds = until_next_time(State, State#state.job), + NewSeconds = calendar:datetime_to_gregorian_seconds(NewDate), + Span = NewSeconds - State#state.referenced_seconds, + case Span > Seconds of + true -> + RefSecs = State#state.referenced_seconds, + NewState = State#state{referenced_seconds = RefSecs + Seconds + 2}, + do_job_run(State, State#state.job), + fast_forward(NewState, NewDate); + false -> + ok + end + catch + throw:invalid_once_exception -> + {error, invalid_once_exception} + end. + + + + diff --git a/src/ecrn_app.erl b/src/ecrn_app.erl new file mode 100644 index 0000000..16cd493 --- /dev/null +++ b/src/ecrn_app.erl @@ -0,0 +1,79 @@ +%%%---------------------------------------------------------------- +%%% @author Eric Newhuis <enewhuis@ecdmarket.com> +%%% @doc +%%% erlcron app system +%%% @end +%%%----------------------------------------------------------------, +-module(ecrn_app). + +-behaviour(application). + +-export([manual_start/0, manual_stop/0]). + +%% Application callbacks +-export([start/2, stop/1]). + +%%%=================================================================== +%%% Application callbacks +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% This function is called whenever an application is started using +%% application:start/[1,2], and should start the processes of the +%% application. If the application is structured according to the OTP +%% design principles as a supervision tree, this means starting the +%% top supervisor of the tree. +%% +%% @spec start(StartType, StartArgs) -> {ok, Pid} | +%% {ok, Pid, State} | +%% {error, Reason} +%% StartType = normal | {takeover, Node} | {failover, Node} +%% StartArgs = term() +%% @end +%%-------------------------------------------------------------------- + +start(_StartType, _StartArgs) -> + case ecrn_sup:start_link() of + {ok, Pid} -> + {ok, Pid}; + Error -> + Error + end. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% This function is called whenever an application has stopped. It +%% is intended to be the opposite of Module:start/2 and should do +%% any necessary cleaning up. The return value is ignored. +%% +%% @spec stop(State) -> void() +%% @end +%%-------------------------------------------------------------------- +stop(_State) -> + ok. + +%% +%% @doc +%% start up the app and all the dependent apps. +%% @end +%% +manual_start() -> + application:start(crypto), + application:start(eunit), + application:start(sasl), + application:start(erlcron). + +%% +%% @doc +%% stop the app manually +%% @end +%% +manual_stop() -> + application:stop(erlcron). + +%%%=================================================================== +%%% Internal functions +%%%=================================================================== diff --git a/src/ecrn_control.erl b/src/ecrn_control.erl new file mode 100644 index 0000000..2c0070a --- /dev/null +++ b/src/ecrn_control.erl @@ -0,0 +1,173 @@ +%%%------------------------------------------------------------------- +%%% @author Eric Merritt <emerritt@ecdmarket.com> +%%% @doc +%%% Provides testing/fast forward control for the system +%%% @end +%%%------------------------------------------------------------------- +-module(ecrn_control). + +-behaviour(gen_server). + +%% API +-export([start_link/0, + cancel/1, + datetime/0, + set_datetime/1, + multi_set_datetime/2]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + terminate/2, code_change/3]). + +-define(SERVER, ?MODULE). + +-include("erlcron-internal.hrl"). + +-record(state, {reference_datetime, datetime_at_reference}). + +%%%=================================================================== +%%% API +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @doc +%% Starts the server +%% +%% @spec start_link() -> {ok, Pid} | ignore | {error, Error} +%% @end +%%-------------------------------------------------------------------- +start_link() -> + gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). + +cancel(AlarmRef) -> + gen_server:call(?SERVER, {cancel, AlarmRef}). + +datetime() -> + gen_server:call(?SERVER, get_datetime). + +%% @doc sets the date-time for the erlcron +set_datetime(DateTime={_,_}) -> + gen_server:call(?SERVER, {set_datetime, DateTime}, infinity). + +%% @doc sets the date-time with the erlcron on all nodes +multi_set_datetime(Nodes, DateTime={_,_}) -> + gen_server:multi_call(Nodes, ?SERVER, {set_datetime, DateTime}). + +%%%=================================================================== +%%% gen_server callbacks +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Initiates the server +%% +%% @spec init(Args) -> {ok, State} | +%% {ok, State, Timeout} | +%% ignore | +%% {stop, Reason} +%% @end +%%-------------------------------------------------------------------- +init([]) -> + DateTime = erlang:localtime(), + {ok, #state{reference_datetime=DateTime, datetime_at_reference=?EPOC_SECONDS}}. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling call messages +%% +%% @spec handle_call(Request, From, State) -> +%% {reply, Reply, State} | +%% {reply, Reply, State, Timeout} | +%% {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, Reply, State} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_call({cancel, AlarmRef}, _From, State) -> + {reply, internal_cancel(AlarmRef), State}; +handle_call(get_datetime, _From, State = #state{reference_datetime = DateTime, + datetime_at_reference = Actual}) -> + {reply, {DateTime, Actual}, State}; +handle_call({set_datetime, DateTime}, _From, State) -> + NewState = State#state{reference_datetime=DateTime, + datetime_at_reference=?EPOC_SECONDS}, + case lists:foldl(fun({_, [Pid]}, Acc) -> + + ecrn_agent:set_datetime(Pid, DateTime, + NewState#state.datetime_at_reference), + Acc; + ({Ref, X}, Acc) when is_list(X) -> + [Ref | Acc] + end, + [], + ecrn_reg:get_all()) of + [] -> + {reply, ok, NewState}; + ErrorRefs -> + {reply, {error, ErrorRefs}, NewState} + end. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling cast messages +%% +%% @spec handle_cast(Msg, State) -> {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_cast(_Msg, State) -> + {noreply, State}. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling all non call/cast messages +%% +%% @spec handle_info(Info, State) -> {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_info(_Info, State) -> + {noreply, State}. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% This function is called by a gen_server when it is about to +%% terminate. It should be the opposite of Module:init/1 and do any +%% necessary cleaning up. When it returns, the gen_server terminates +%% with Reason. The return value is ignored. +%% +%% @spec terminate(Reason, State) -> void() +%% @end +%%-------------------------------------------------------------------- +terminate(_Reason, _State) -> + ok. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Convert process state when code is changed +%% +%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} +%% @end +%%-------------------------------------------------------------------- +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%%%=================================================================== +%%% Internal functions +%%%=================================================================== +internal_cancel(AlarmRef) -> + case ecrn_reg:get(AlarmRef) of + undefined -> + undefined; + {ok, [Pid]} -> + {ok, ecrn_agent:cancel(Pid)} + end. diff --git a/src/ecrn_cron_sup.erl b/src/ecrn_cron_sup.erl new file mode 100644 index 0000000..a437d38 --- /dev/null +++ b/src/ecrn_cron_sup.erl @@ -0,0 +1,80 @@ +%%%------------------------------------------------------------------- +%%% @author Eric Merritt <emerritt@ecdmarket.com> +%%% @doc +%%% Simple one for one supervisor for ecd_chron jobs. +%%% @end +%%%------------------------------------------------------------------- +-module(ecrn_cron_sup). + +-behaviour(supervisor). + +%% API +-export([start_link/0, + add_job/2]). + +%% Supervisor callbacks +-export([init/1]). + +-define(SERVER, ?MODULE). + +%%%=================================================================== +%%% API functions +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @doc +%% Starts the supervisor +%% +%% @spec start_link() -> {ok, Pid} | ignore | {error, Error} +%% @end +%%-------------------------------------------------------------------- +start_link() -> + supervisor:start_link({local, ?SERVER}, ?MODULE, []). + + +%%-------------------------------------------------------------------- +%% @doc +%% Add a chron job to be supervised +%% @end +%%-------------------------------------------------------------------- + +add_job(AlarmRef, Task) -> + supervisor:start_child(?SERVER, [AlarmRef, Task]). + + +%%%=================================================================== +%%% Supervisor callbacks +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Whenever a supervisor is started using supervisor:start_link/[2,3], +%% this function is called by the new process to find out about +%% restart strategy, maximum restart frequency and child +%% specifications. +%% +%% @spec init(Args) -> {ok, {SupFlags, [ChildSpec]}} | +%% ignore | +%% {error, Reason} +%% @end +%%-------------------------------------------------------------------- +init([]) -> + RestartStrategy = simple_one_for_one, + MaxRestarts = 1000, + MaxSecondsBetweenRestarts = 3600, + + SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, + + Restart = transient, + Shutdown = 2000, + Type = worker, + + AChild = {ecrn_agent, {ecrn_agent, start_link, []}, + Restart, Shutdown, Type, [ecrn_agent]}, + + {ok, {SupFlags, [AChild]}}. + +%%%=================================================================== +%%% Internal functions +%%%=================================================================== diff --git a/src/ecrn_reg.erl b/src/ecrn_reg.erl new file mode 100644 index 0000000..f7fe934 --- /dev/null +++ b/src/ecrn_reg.erl @@ -0,0 +1,256 @@ +%%%------------------------------------------------------------------- +%%% @author Eric Merritt <emerritt@ecdmarket.com> +%%% @doc +%%% This provides simple pid registration for the server. +%%% @end +%%%------------------------------------------------------------------- +-module(ecrn_reg). + +-behaviour(gen_server). + +%% API +-export([start_link/0, + register/2, + unregister/1, + get/1, + stop/0, + get_all/0]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + terminate/2, code_change/3]). + +-include_lib("eunit/include/eunit.hrl"). + +-define(SERVER, ?MODULE). + +-record(state, {registered}). + +%%%=================================================================== +%%% API +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @doc +%% Starts the server +%% +%% @spec start_link() -> {ok, Pid} | ignore | {error, Error} +%% @end +%%-------------------------------------------------------------------- +start_link() -> + gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). + +%%-------------------------------------------------------------------- +%% @doc +%% Register an arbitrary value with the system, under a set of keys +%% @end +%%-------------------------------------------------------------------- +-spec register(term() | [term()], term()) -> ok. +register(Keys, Body) when is_list(Keys) -> + gen_server:call(?SERVER, {register, Keys, Body}); +register(Key, Body) -> + gen_server:call(?SERVER, {register, [Key], Body}). + +%%-------------------------------------------------------------------- +%% @doc +%% Remove the value registered under a que or set of keys +%% @end +%%-------------------------------------------------------------------- +-spec unregister(term() | [term()]) -> ok. +unregister(Keys) when is_list(Keys) -> + gen_server:call(?SERVER, {unregister, Keys}); +unregister(Key) -> + gen_server:call(?SERVER, {unregister, [Key]}). + +%%-------------------------------------------------------------------- +%% @doc +%% Get a value buy key. +%% @end +%%-------------------------------------------------------------------- +-spec get(term()) -> {ok, term()} | undefined. +get(Key) -> + gen_server:call(?SERVER, {get, Key}). + + +%%-------------------------------------------------------------------- +%% @doc +%% Get all the values. +%% @end +%%-------------------------------------------------------------------- +-spec get_all() -> [{term(), term()}]. +get_all() -> + gen_server:call(?SERVER, get_all). + + +%%-------------------------------------------------------------------- +%% @doc +%% stop this server +%% @end +%%-------------------------------------------------------------------- +-spec stop() -> ok. +stop() -> + gen_server:call(?SERVER, stop). + +%%%=================================================================== +%%% gen_server callbacks +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Initiates the server +%% +%% @spec init(Args) -> {ok, State} | +%% {ok, State, Timeout} | +%% ignore | +%% {stop, Reason} +%% @end +%%-------------------------------------------------------------------- +init([]) -> + {ok, #state{registered=dict:new()}}. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling call messages +%% +%% @spec handle_call(Request, From, State) -> +%% < {reply, Reply, State} | +%% {reply, Reply, State, Timeout} | +%% {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, Reply, State} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_call({register, Keys, Body}, _From, #state{registered=Dict}) -> + {Result, Dict2} = add_for_keys(Keys, Body, Dict, ok), + {reply, Result, #state{registered=Dict2}}; +handle_call({unregister, Keys}, _From, #state{registered=Dict}) -> + Dict2 = remove_for_keys(Keys, Dict), + {reply, ok, #state{registered=Dict2}}; +handle_call({get, Key}, _From, State = #state{registered=Dict}) -> + Value = get_for_key(Key, Dict), + {reply, Value, State}; +handle_call(stop, _From, State) -> + {stop, normal, ok, State}; +handle_call(get_all, _From, State = #state{registered=Dict}) -> + {reply, dict:to_list(Dict), State}. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling cast messages +%% +%% @spec handle_cast(Msg, State) -> {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_cast(_Msg, State) -> + {noreply, State}. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Handling all non call/cast messages +%% +%% @spec handle_info(Info, State) -> {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, State} +%% @end +%%-------------------------------------------------------------------- +handle_info(_Info, State) -> + {noreply, State}. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% This function is called by a gen_server when it is about to +%% terminate. It should be the opposite of Module:init/1 and do any +%% necessary cleaning up. When it returns, the gen_server terminates +%% with Reason. The return value is ignored. +%% +%% @spec terminate(Reason, State) -> void() +%% @end +%%-------------------------------------------------------------------- +terminate(_Reason, _State) -> + ok. + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Convert process state when code is changed +%% +%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} +%% @end +%%-------------------------------------------------------------------- +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%%%=================================================================== +%%% Internal functions +%%%=================================================================== +discarded_keys(Key, {discarded_keys, Keys}) -> + {discarded_keys, [Key | Keys]}; +discarded_keys(Key, ok) -> + {discarded_keys, [Key]}. + +add_for_keys([Key | Rest], Body, Dict, Result) -> + case dict:find(Key, Dict) of + error -> + add_for_keys(Rest, Body, dict:append(Key, Body, Dict), Result); + _Value -> + add_for_keys(Rest, Body, dict:append(Key, Body, Dict), + discarded_keys(Key, Result)) + end; +add_for_keys([], _, Dict, Result) -> + {Result, Dict}. + +remove_for_keys([Key | Rest], Dict) -> + remove_for_keys(Rest, dict:erase(Key, Dict)); +remove_for_keys([],Dict) -> + Dict. + +get_for_key(Key, Dict) -> + case dict:find(Key, Dict) of + error -> + undefined; + Value -> + Value + end. + +%%%=================================================================== +%%% Tests +%%%=================================================================== + +generate_test_() -> + {setup, + fun () -> + ecrn_reg:start_link() + end, + fun (_) -> + ecrn_reg:stop() + end, + {with, + [fun general_tests/1]}}. + +general_tests(_) -> + ?assertMatch(ok, ecrn_reg:register([a, b], boo)), + ?assertMatch({ok, [boo]}, ecrn_reg:get(a)), + ecrn_reg:unregister([a, b]), + ?assertMatch(undefined, ecrn_reg:get(a)), + ?assertMatch(ok, ecrn_reg:register([a, b], boo)), + ?assertMatch(ok, ecrn_reg:register([c, d], boo2)), + ?assertMatch({ok, [boo2]}, ecrn_reg:get(c)), + ?assertMatch({ok, [boo]}, ecrn_reg:get(b)), + ?assertMatch({discarded_keys, [d, c]}, + ecrn_reg:register([c, d], boo2)). + + + + + + + + diff --git a/src/ecrn_sup.erl b/src/ecrn_sup.erl new file mode 100644 index 0000000..4e1496d --- /dev/null +++ b/src/ecrn_sup.erl @@ -0,0 +1,74 @@ +%%%---------------------------------------------------------------- +%%% @author Eric Newhuis <enewhuis@ecdmarket.com> +%%% @doc +%%% @end +%%% @copyright 2009 eCD Market +%%%---------------------------------------------------------------- +-module(ecrn_sup). + +-behaviour(supervisor). + +%% API +-export([start_link/0]). + +%% Supervisor callbacks +-export([init/1]). + +-include("erlcron-internal.hrl"). + +-define(SERVER, ?MODULE). + +%%%=================================================================== +%%% API functions +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @doc +%% Starts the supervisor +%% +%% @spec start_link() -> {ok, Pid} | ignore | {error, Error} +%% @end +%%-------------------------------------------------------------------- + +start_link() -> + supervisor:start_link({local, ?SERVER}, ?MODULE, []). + +%%%=================================================================== +%%% Supervisor callbacks +%%%=================================================================== + +%%-------------------------------------------------------------------- +%% @private +%% @doc +%% Whenever a supervisor is started using supervisor:start_link/[2,3], +%% this function is called by the new process to find out about +%% restart strategy, maximum restart frequency and child +%% specifications. +%% +%% @spec init(Args) -> {ok, {SupFlags, [ChildSpec]}} | +%% ignore | +%% {error, Reason} +%% @end +%%-------------------------------------------------------------------- + +init([]) -> + RestartStrategy = one_for_one, + MaxRestarts = 3, + MaxSecondsBetweenRestarts = 10, + SupFlags = {RestartStrategy, + MaxRestarts, + MaxSecondsBetweenRestarts}, + + ChildSup = {ecrn_cron_sup, {ecrn_cron_sup, start_link, []}, + permanent, 1000, supervisor, [ecrn_cron_sup]}, + RegistrationServer = {ecrn_reg_server, {ecrn_reg, start_link, []}, + permanent, 1000, worker, [ecrn_reg]}, + BroadcastServer = {ecrn_control, {ecrn_control, start_link, []}, + permanent, 1000, worker, [ecrn_control]}, + + + {ok, {SupFlags, [ChildSup, RegistrationServer, BroadcastServer]}}. + +%%%=================================================================== +%%% Internal functions +%%%=================================================================== diff --git a/src/ecrn_test.erl b/src/ecrn_test.erl new file mode 100644 index 0000000..2d60a61 --- /dev/null +++ b/src/ecrn_test.erl @@ -0,0 +1,152 @@ +%%%------------------------------------------------------------------- +%%% @author Eric Merritt <emerritt@ecdmarket.com> +%%%------------------------------------------------------------------- +-module(ecrn_test). + +-include_lib("eunit/include/eunit.hrl"). + +%% -- tests --------------------------------------------------------------------- +cron_test_() -> + {setup, + fun() -> + ecrn_app:manual_start() + end, + fun(_) -> + ecrn_app:manual_stop() + end, + {with, [fun set_alarm_test/1, + fun travel_back_in_time_test/1, + fun cancel_alarm_test/1, + fun big_time_jump_test/1, + fun cron_test/1]}}. + + + +set_alarm_test(_) -> + EpochDay = {2000,1,1}, + EpochDateTime = {EpochDay,{8,0,0}}, + erlcron:set_datetime(EpochDateTime), + Alarm1TimeOfDay = {9,0,0}, + Alarm2TimeOfDay = {9,0,1}, + + Self = self(), + + erlcron:at(Alarm1TimeOfDay, fun(_, _) -> + Self ! ack1 + end), + erlcron:at(Alarm2TimeOfDay, fun(_, _) -> + Self ! ack2 + end), + erlcron:set_datetime({EpochDay, {8, 59, 59}}), +%% +%% The alarm should trigger this nearly immediately. +%% + ?assertMatch(ok, receive + ack1 -> ok + after + 1500 -> timeout + end), +%% +%% The alarm should trigger this 1 second later. +%% + ?assertMatch(ok, receive + ack2 -> ok + after + 2500 -> timeout + end). + +cancel_alarm_test(_) -> + Day = {2000,1,1}, + erlcron:set_datetime({Day,{8,0,0}}), + AlarmTimeOfDay = {9,0,0}, + + Self = self(), + + Ref = erlcron:at(AlarmTimeOfDay, fun(_, _) -> + Self ! ack + end), + erlcron:cancel(Ref), + erlcron:set_datetime({Day, AlarmTimeOfDay}), + ?assertMatch(ok, receive + ack -> ack + after +%% There is no event-driven way to +%% ensure we never receive an ack. + 125 -> ok + end). + +%% Time jumps ahead one day so we should see the alarms from both days. +big_time_jump_test(_) -> + Day1 = {2000,1,1}, + Day2 = {2000,1,2}, + EpochDateTime = {Day1,{8,0,0}}, + erlcron:set_datetime(EpochDateTime), + Alarm1TimeOfDay = {9,0,0}, + Alarm2TimeOfDay = {9,0,1}, + + Self = self(), + + erlcron:at(Alarm1TimeOfDay, fun(_, _) -> + Self ! ack1 + end), + erlcron:at(Alarm2TimeOfDay, fun(_, _) -> + Self ! ack2 + end), + erlcron:set_datetime({Day2, {9, 10, 0}}), + ?assertMatch(ok, receive + ack1 -> ok + after + 1500 -> timeout + end), + ?assertMatch(ok, receive + ack2 -> ok + after + 1500 -> timeout + end), + + ?assertMatch(ok, receive + ack1 -> ok + after + 1500 -> timeout + end), + ?assertMatch(ok, receive + ack2 -> ok + after + 2500 -> timeout + end). + +travel_back_in_time_test(_) -> + Seconds = seconds_now(), + Past = {{2000,1,1},{12,0,0}}, + erlcron:set_datetime(Past), + {ExpectedDateTime, _} = erlcron:datetime(), + ExpectedSeconds = calendar:datetime_to_gregorian_seconds(ExpectedDateTime), + ?assert(ExpectedSeconds >= calendar:datetime_to_gregorian_seconds(Past)), + ?assert(ExpectedSeconds < Seconds). + + +%% Time jumps ahead one day so we should see the alarms from both days. +cron_test(_) -> + Day1 = {2000,1,1}, + AlarmTimeOfDay = {15,29,58}, + erlcron:set_datetime({Day1, AlarmTimeOfDay}), + + Self = self(), + + Job = {{daily, {3, 30, pm}}, + fun(_, _) -> + Self ! ack + end}, + + erlcron:cron(Job), + + ?assertMatch(ok, receive + ack -> ok + after + 2500 -> timeout + end). + +%% -- helpers ------------------------------------------------------------------- + +seconds_now() -> + calendar:datetime_to_gregorian_seconds(calendar:universal_time()). diff --git a/src/erlcron-internal.hrl b/src/erlcron-internal.hrl new file mode 100644 index 0000000..d8a8e3d --- /dev/null +++ b/src/erlcron-internal.hrl @@ -0,0 +1,11 @@ +%%%---------------------------------------------------------------- +%%% @author Eric Merritt <emerritt@ecdmarket.com> +%%% @copyright 2009 eCD Market +%%%---------------------------------------------------------------- +-define(ONE_DAY,(24 * 60 * 60) ). + +-define(EPOC_SECONDS, + fun() -> + {Megasecs, Secs, Microsecs} = erlang:now(), + (Megasecs * 1000000) + Secs + (Microsecs / 1000000) + end()). diff --git a/src/erlcron.erl b/src/erlcron.erl new file mode 100644 index 0000000..3f8f190 --- /dev/null +++ b/src/erlcron.erl @@ -0,0 +1,135 @@ +%%%---------------------------------------------------------------- +%%% @author Eric Newhuis <enewhuis@ecdmarket.com> +%%% @copyright 2009-2010 eCD Market +%%%----------------------------------------------------------------, +-module(erlcron). + +-export([cron/1, + at/2, + once/2, + cancel/1, + datetime/0, + set_datetime/1, + set_datetime/2, + multi_set_datetime/1, + multi_set_datetime/2, + multi_set_datetime/3]). + +-include_lib("erlcron/include/erlcron.hrl"). + +%% @doc Simple job scheduler for Erlang/OTP +%% +%% This is a simple utility which schedules jobs to be +%% run at a given time or periodically +%% +%% The synax of a job description is quite different from +%% <code>crontab</code>. It is (in this author's opinion) easier to read +%% and is much more in keeping with the Erlang tradition. It is not +%% quite as expressive as <code>cron</code> but this can be compensated +%% for by adding multiple jobs. +%% +%% No output is logged or mailed to anyone. If you want output to +%% be logged or mailed, you must explicitly specify that as part of the +%% job. +%% +%% This does not poll the system on a minute-by-minute +%% basis like <code>cron</code> does. Each job is assigned to a single +%% (Erlang) process. The time until it is to run next is calculated, +%% and the process sleeps for exactly that long. +%% +%% Unlike <code>cron</code>'s one-minute resolution, <code>crone</code> +%% has a 2-second resolution (actually 1 second, but after running the +%% job, the process waits an extra second to avoid accidentally running it +%% more than once.) +%% +%% Because it does not wake up every minute, and because it does not +%% have a fixed configuration file, <code>crone</code> must be stopped and +%% restarted if the user wishes to change the scheduled jobs. +%% +%% It does not handle Daylight Savings Time (or other +%% cases when the system clock is altered) gracefully, and it is recommended +%% that it be stopped and restarted on such occasions. +%% +%% Cron Job Examples +%% +%% <code> +%% +%% {{once, {3, 30, pm}}, +%% {io, fwrite, ["Hello, world!~n"]}} +%% +%% {{once, {12, 23, 32}}, +%% {io, fwrite, ["Hello, world!~n"]}} +%% +%% {{once, 3600}, +%% {io, fwrite, ["Hello, world!~n"]}} +%% +%% {{daily, {every, {23, sec}, {between, {3, pm}, {3, 30, pm}}}}, +%% {io, fwrite, ["Hello, world!~n"]}} +%% +%% {{daily, {3, 30, pm}}, +%% fun() -> io:fwrite("It's three thirty~n") end} +%% +%% {{daily, [{1, 10, am}, {1, 07, 30, am}]}, +%% {io, fwrite, ["Bing~n"]}} +%% +%% {{weekly, thu, {2, am}}, +%% {io, fwrite, ["It's 2 Thursday morning~n"]}} +%% +%% {{weekly, wed, {2, am}}, +%% {fuxbn() -> io:fwrite("It's 2 Wednesday morning~n") end} +%% +%% {{weekly, fri, {2, am}}, +%% {io, fwrite, ["It's 2 Friday morning~n"]}} +%% +%% {{monthly, 1, {2, am}}, +%% {io, fwrite, ["First of the month!~n"]}} +%% +%% {{monthly, 4, {2, am}}, +%% {io, fwrite, ["Fourth of the month!~n"]}} +%% </code> +%% +%% @end + +-spec cron(job()) -> ok. +cron(Job) -> + AlarmRef = make_ref(), + ecrn_cron_sup:add_job(AlarmRef, Job), + AlarmRef. + +-spec at(time() | seconds(), function()) -> ok. +at(When, Fun) -> + Job = {{daily, When}, Fun}, + cron(Job). + +-spec once(time() | seconds(), function()) -> ok. +once(When, Fun) -> + Job = {{once, When}, Fun}, + cron(Job). + +-spec cancel(job_ref()) -> ok. +cancel(AlarmRef) -> + ecrn_control:cancel(AlarmRef). + + +-spec datetime() -> datetime(). +datetime() -> + ecrn_control:datetime(). + +-spec set_datetime(datetime()) -> ok. +set_datetime(DateTime) -> + ecrn_control:set_datetime(DateTime). + +-spec set_datetime(datetime(), testing | production) -> ok. +set_datetime(DateTime, Atom) when is_atom(Atom) -> + ecrn_control:set_datetime(DateTime, Atom). + +-spec multi_set_datetime(datetime()) -> ok. +multi_set_datetime(DateTime) -> + ecrn_control:multi_set_datetime([node()|nodes()], DateTime). + +-spec multi_set_datetime([node()], datetime()) -> ok. +multi_set_datetime(Nodes, DateTime) when is_list(Nodes) -> + ecrn_control:multi_set_datetime(Nodes, DateTime). + +multi_set_datetime(Nodes, DateTime, testing) when is_list(Nodes) -> + ecrn_control:multi_set_datetime(Nodes, DateTime, testing).
erlware/erlcron
8e012494ea223322e7f4345e14c7e775ca4504dd
Initial setup commit
diff --git a/README b/README new file mode 100644 index 0000000..e69de29
tladesignz/my-jQuery-plugins
65c326974ea6d6e69429419c5c36b2b2b850d211
Added new plugin jQuery.backgroundSize.
diff --git a/jquery.backgroundsize.js b/jquery.backgroundsize.js new file mode 100644 index 0000000..4d2961d --- /dev/null +++ b/jquery.backgroundsize.js @@ -0,0 +1,47 @@ +/*globals jQuery */ +/** + * This plugin determines the browser capabilities + * regarding CSS3 background-size support. + * + * It adds a property 'backgroundSize' to the + * jQuery.support object which is either an empty string + * (which evaluates to false) or a string containing the + * actual style property which can be used for it. + * + * @author Benjamin Erhart <berhart@tladesignz.com> + * @license MIT http://www.opensource.org/licenses/mit-license.php + * @version 0.1 + * + * @example + * if ($.support.backgroundSize) { + * // .. do something + * } + * $( '#some_element' ).css( $.support.backgroundSize, 'auto 100%' ); + * + * @requires jQuery 1.3 + * @extends jQuery.support + * @constructor + */ +(function( $ ) { + + $.support.backgroundSize = ''; + + $( function() { + var s = document.body.style, + types = [ + 'OBackgroundSize', + 'KhtmlBackgroundSize', + 'WebkitBackgroundSize', + 'MozBackgroundSize', + 'backgroundSize' + ], + i = types.length - 1; + + do { + if (typeof s[ types[ i ] ] === 'string') { + return ($.support.backgroundSize = types[ i ]); + } + } while (i--); + } ); + +}( jQuery ));
tladesignz/my-jQuery-plugins
6ca5bf9603ab3b62c2505a7732d8d1e9b19aea37
Doesn't submit <button> and <input type="button|reset|image"> values any more, since a browser wouldn't do so on a normal form submit, as long as this button isn't used for the submit. Added fifth parameter 'target'. This can be used to regain the behaviour of submitting the buttons value used in submitting the form. Checked against JSLint http://www.jslint.com/
diff --git a/jquery.postForm.js b/jquery.postForm.js index 1196e05..c4faa5c 100644 --- a/jquery.postForm.js +++ b/jquery.postForm.js @@ -1,120 +1,165 @@ +/*jslint white: false, plusplus: false, immed: false */ /** * Construct a jQuery.postForm() function. * @class jQuery.postForm() uses jQuery.post() to post all elements of a form, like * a browser would if the form was submitted. * * Some code inspired by the Dojo Toolkit http://www.dojotoolkit.org/ * * Usage: * - * jQuery.postForm( - * 'test.pl', - * form, - * function( data ) { console.debug( data ) }, * optional - * 'json' * optional - * ); + * $( document.myform.mysubmitbutton ).click( function( evt ) { + * jQuery.postForm( + * 'http://myserver/myformhandler', + * document.myform, + * function( data ) { console.debug( data ); }, // optional + * 'json', // optional + * evt.target // optional + * ); + * + * return false; + * } * * Copyright (c) 2009 Benjamin Erhart, http://www.tladesignz.com/ * * 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. - * - * @version 0.2 + * + * -------------------------------------------------------------------------------- + * + * Changes: + * + * + * Version 0.3.1: + * + * Fixed bug with undefined target + * + * Version 0.3: + * + * Doesn't submit &lt;button&gt; and &lt;input type="button|reset|image"&gt; values + * any more, since a browser wouldn't do so on a normal form submit, as long as this + * button isn't used for the submit. + * + * Added fifth parameter 'target'. This can be used to regain the behaviour of + * submitting the buttons value used in submitting the form. + * + * Checked against JSLint http://www.jslint.com/ + * + * -------------------------------------------------------------------------------- + * + * Credits: + * + * Thanks to Steffen Chmil <sc@dbtech.de> for the hint regarding the submit button values. + * + * -------------------------------------------------------------------------------- + * + * @version 0.3.1 * @author berhart@tladesignz.com * * @requires jQuery jQuery 1.2.3 * @extends jQuery * @addon * @constructor */ (function() { /** - * @param {String} The URL of the page to load. - * @param {Object} The form object (or jQuery object holding the form) whose elements values should be sent. - * @param {Function} A function to be executed whenever the data is loaded successfully. - * @param {String} Type of data to be returned to callback function (JSON, XML, etc.) + * @param {String} url The URL of the page to load. + * @param {Object} form The form object (or jQuery object holding the form) whose elements values should be sent. + * @param {Function} callback (optional) A function to be executed whenever the data is loaded successfully. + * @param {String} type (optional) Type of data to be returned to callback function (JSON, XML, etc.) + * @param {Object} target (optional) Event target element which triggered this postForm call. Used to emulate + * behaviour of browsers standard form handling, which is: the form fields name and value triggering the form + * action will be sent, too. */ - jQuery.postForm = function( url, form, callback, type ) { - var data = {}; - var i; - var j; - var field; - var fType; + jQuery.postForm = function( url, form, callback, type, target ) { + var data = {}, i, j, field, fTag, fType; // remove jQuery wrapping of form object if (form.jquery) { form = form.get( 0 ); } - if (!form || !form.tagName || !form.tagName.toLowerCase() == "form") { - throw( "Attempted to post a non-form element." ); + if (!form || !form.tagName || !form.tagName.toLowerCase() === 'form') { + throw( 'Attempted to post a non-form element.' ); + } + + // BUGFIX: added test if 'target' is defined before it gets used + if (target && target.tagName.toLowerCase() !== 'button' && !target.type.match( /^submit|image$/i )) { + target = null; } for (i = 0; i < form.elements.length; ++i) { field = form.elements[ i ]; - if (!field || field.tagName.toLowerCase() == "fieldset") { + if (!field) { continue; } + fTag = field.tagName.toLowerCase(); fType = field.type.toLowerCase(); - if (fType == "select-multiple") { + // Never submit <fieldset>, <input type="reset"> and <button type="reset">. + // Submit <button> or <input type="submit|image"> values if this element was used to trigger the form submit. + if (fTag === 'fieldset' || fType === 'reset' || (fTag === 'button' || fType === 'submit' || fType === 'image') && field !== target) { + continue; + } + + if (fType === 'select-multiple') { for (j = 0; j < field.options.length; ++j) { if (field.options[ j ].selected) { add( data, field.name, field.options[ j ].value ); } } } - else if (jQuery.inArray( fType, ["radio", "checkbox"] ) > -1) { + else if (fType === 'radio' || fType === 'checkbox') { if (field.checked) { add( data, field.name, field.value ); } } else { add( data, field.name, field.value ); } } jQuery.post( url, data, callback, type ); }; /** * extends the value of an object's key dynamically to an array if more than one is added * @private - * @param {Object} a normal object - * @param {String} object's key - * @param {Any} value to add to object's key + * @param {Object} object a normal object + * @param {String} name object's key + * @param {Any} value value to add to object's key */ function add( object, name, value ) { if (object[ name ]) { - if (typeof object[ name ] == 'object') { + if (typeof object[ name ] === 'object') { object[ name ].push( value ); } else { object[ name ] = [ object[ name ], value ]; } } else { object[ name ] = value; } } })();
fellix/collect4j
eb80c2d7cd453179594e8217d4b94f74e198f07f
Added more site configuration
diff --git a/src/site/apt/contribute.apt b/src/site/apt/contribute.apt new file mode 100644 index 0000000..08b1d18 --- /dev/null +++ b/src/site/apt/contribute.apt @@ -0,0 +1,4 @@ +Help Us + + To help with the Collect4j view the mainlists, and get the source code on github (You need git (git-core) to get the source code) + https://github.com/fellix/collect4j/tree . See in google how to use the github, and join us. \ No newline at end of file diff --git a/src/site/apt/getting.apt b/src/site/apt/getting.apt new file mode 100644 index 0000000..e368c25 --- /dev/null +++ b/src/site/apt/getting.apt @@ -0,0 +1,16 @@ +Getting Stated + + After downloaded Collect4j, the use of this is very simple. + +Simple Consulting + + For Consulting simple collection containing <String>. + This collection is used in all samples in this page + <pre> + List<String> names = new ArrayList<String>(); + names.add("Rafael"); + names.add("John"); + names.add("Edward"); + names.add("Michael"); + names.add("Ralf"); + </pre> \ No newline at end of file diff --git a/src/site/apt/index.apt b/src/site/apt/index.apt new file mode 100644 index 0000000..2d0afe6 --- /dev/null +++ b/src/site/apt/index.apt @@ -0,0 +1,9 @@ +Collect4j + + Welcome to the Collect4j, an discovery how easy is manipulates Java Collections API. + Using a simple DSL, a light and direct syntax, make more easy the consults to an Collection. + +News + + 2007.07.20 + Collect4j-0.1-snapshot released \ No newline at end of file diff --git a/src/site/site.xml b/src/site/site.xml index 23e8ff2..27ed1bc 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -1,23 +1,25 @@ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/DECORATION/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/DECORATION/1.0.0 http://maven.apache.org/xsd/decoration-1.0.0.xsd" name="Collect4j"> <body> <menu name="Overview"> <item name="Introduction" href="index.html"/> <item name="Getting Started" href="getting.html"/> <item name="FAQ" href="faq.html"/> - <item name="Team" href="team.html"/> + <item name="Team" href="team-list.html"/> + <item name="Contribute" href="contribute.html"/> </menu> <menu name="Download"> - <item name="Dowload" href="dowload.html"/> - <item name="Source" href="source.html"/> + <item name="Download" href="download.html"/> + <item name="Source" href="https://github.com/fellix/collect4j/tree"/> </menu> - <menu name="Documentations"> + <menu name="Documentation"> <item name="JavaDoc" href="apidocs/index.html"/> + <item name="Examples" href="samples.html"/> </menu> </body> </project> \ No newline at end of file
fellix/collect4j
835439e69e775f5e8214863c98286ca2c7d8df24
Added Site Descriptor
diff --git a/.project b/.project index d1f11e8..4eb4366 100644 --- a/.project +++ b/.project @@ -1,23 +1,29 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>Collect</name> <comment></comment> <projects> </projects> <buildSpec> + <buildCommand> + <name>org.eclipse.wst.common.project.facet.core.builder</name> + <arguments> + </arguments> + </buildCommand> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> <buildCommand> <name>org.maven.ide.eclipse.maven2Builder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> <nature>org.maven.ide.eclipse.maven2Nature</nature> + <nature>org.eclipse.wst.common.project.facet.core.nature</nature> </natures> </projectDescription> diff --git a/src/main/java/com/rollingwithcode/collect/Test.java b/src/main/java/com/rollingwithcode/collect/Test.java deleted file mode 100644 index f3255c4..0000000 --- a/src/main/java/com/rollingwithcode/collect/Test.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.rollingwithcode.collect; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - - -public class Test { - - /** - * @param args - */ - public static void main(String[] args) { - System.out.println("Começando"); - List<String> lista = new ArrayList<String>(); - lista.add("Uva"); - lista.add("Maça"); - lista.add("Melancia"); - lista.add("Melão"); - lista.add("Maracujá"); - Collection<String> busca = new Collect().in(lista).when().eql("Mel", "Ma"); - for(String s : busca){ - System.out.println(s); - } - List<Pessoa> pessoas = new ArrayList<Pessoa>(); - pessoas.add(new Pessoa("Rafael", 21)); - pessoas.add(new Pessoa("Suélen", 19)); - pessoas.add(new Pessoa("Samuel", 25)); - pessoas.add(new Pessoa("Pedro", 23)); - pessoas.add(new Pessoa("Rafael", 23)); - Collection<Pessoa> buscaP = new Collect().in(pessoas).when("nome").eql("Rafael"); - for(Pessoa p : buscaP){ - System.out.println(p); - } - - buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("idade").eql(23); - for(Pessoa p : buscaP){ - System.out.println(p); - } - System.out.println(); - System.out.println(); - buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("nome", "idade").eql("Rafael", 23); - for(Pessoa p : buscaP){ - System.out.println(p); - } - System.out.println(); - busca = (Collection<String>) new Collect().in(lista).when().like("M"); - for(String s : busca){ - System.out.println(s); - } - - System.out.println(); - buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("nome").like("S"); - for(Pessoa p : buscaP){ - System.out.println(p); - } - - System.out.println(); - buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("idade").like("1"); - for(Pessoa p : buscaP){ - System.out.println(p); - } - - } - private static class Pessoa{ - String nome; - int idade; - - public Pessoa() { - super(); - } - - public Pessoa(String nome, int idade) { - super(); - this.nome = nome; - this.idade = idade; - } - /** - * @return the nome - */ - public String getNome() { - return nome; - } - /** - * @param nome the nome to set - */ - public void setNome(String nome) { - this.nome = nome; - } - /** - * @return the idade - */ - public int getIdade() { - return idade; - } - /** - * @param idade the idade to set - */ - public void setIdade(int idade) { - this.idade = idade; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Pessoa["+nome+", "+idade+" ]"; - } - - } -} diff --git a/src/site/site.xml b/src/site/site.xml new file mode 100644 index 0000000..23e8ff2 --- /dev/null +++ b/src/site/site.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/DECORATION/1.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/DECORATION/1.0.0 http://maven.apache.org/xsd/decoration-1.0.0.xsd" + name="Collect4j"> + <body> + <menu name="Overview"> + <item name="Introduction" href="index.html"/> + <item name="Getting Started" href="getting.html"/> + <item name="FAQ" href="faq.html"/> + <item name="Team" href="team.html"/> + </menu> + <menu name="Download"> + <item name="Dowload" href="dowload.html"/> + <item name="Source" href="source.html"/> + </menu> + + <menu name="Documentations"> + <item name="JavaDoc" href="apidocs/index.html"/> + </menu> + + </body> + </project> \ No newline at end of file
fellix/collect4j
a52294f2b2aa7ab79d2c59cc1fda88b336b38362
Create the Only comparator
diff --git a/pom.xml b/pom.xml index b6bb0dc..e78cece 100644 --- a/pom.xml +++ b/pom.xml @@ -1,88 +1,88 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.rollingwithcode</groupId> <artifactId>collect4j</artifactId> <name>collect4j</name> <version>0.1-SNAPSHOT</version> <description>DSL for consulting Java Collection API Using this DSL you can filter a collection using a high level language. Collect4j supports objects and primitive types. </description> + <!-- Site Definitions --> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> <developers> <developer> <name>Rafael Felix da Silva</name> <email>felix.rafael@gmail.com</email> <url>http://rollingwithcode.blogspot.com</url> <roles> <role>Project Manager</role> <role>Architect</role> </roles> </developer> </developers> <licenses> <license> <name>MIT-LICENSE</name> <url>MIT-LICENSE</url> </license> </licenses> <inceptionYear>2009</inceptionYear> <scm> <connection>scm:git://github.com/fellix/collect4j.git</connection> <url>https://github.com/fellix/collect4j/tree</url> </scm> <mailingLists> <mailingList> <name>Users Mailing List</name> <subscribe></subscribe> <unsubscribe></unsubscribe> <archive>https://sourceforge.net/mailarchive/forum.php?forum_name=collect4j-users</archive> </mailingList> <mailingList> <name>Developers Mailing List</name> <subscribe></subscribe> <unsubscribe></unsubscribe> <archive>https://sourceforge.net/mailarchive/forum.php?forum_name=collect4j-devel</archive> </mailingList> </mailingLists> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.5</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jxr-maven-plugin</artifactId> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> </plugin> <plugin> <artifactId>maven-clover-plugin</artifactId> </plugin> - </plugins> </reporting> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.6</version> <scope>test</scope> </dependency> </dependencies> </project> \ No newline at end of file diff --git a/src/main/java/com/rollingwithcode/collect/CompareHandler.java b/src/main/java/com/rollingwithcode/collect/CompareHandler.java index 7f77388..162dac4 100644 --- a/src/main/java/com/rollingwithcode/collect/CompareHandler.java +++ b/src/main/java/com/rollingwithcode/collect/CompareHandler.java @@ -1,67 +1,81 @@ /** * */ package com.rollingwithcode.collect; import java.util.Collection; import com.rollingwithcode.collect.comparator.CollectComparator; import com.rollingwithcode.collect.comparator.EqualsComparator; import com.rollingwithcode.collect.comparator.LikeComparator; +import com.rollingwithcode.collect.comparator.OnlyComparator; /** * Used to make compare using values * @author Rafael Felix da Silva * @version 1.0 * @since 0.1-snaphost */ public class CompareHandler<E> { private Object[] fields; private Collection<E> collection; /** * Defaults construtor * @param fields to filter * @param collection to eval * @since 1.0 */ public CompareHandler(Object[] fields, Collection<E> collection) { super(); this.fields = fields; this.collection = collection; } /** * Compare object with when same (equals) * @param values for each fields * @return new Collection (ArrayList) with the filter * @since 1.0 * @see #compare(CollectComparator, Object...) * @see EqualsComparator */ public Collection<E> eql(Object...values){ return compare(new EqualsComparator<E>(), values); } /** * Generic method for custom compare * @param comparator the Comparator implementation * @param values passed as parameters * @return Collection for the result * @since 1.0 + * @see CollectComparator#compare(Collection, Object[], Object[]) */ public Collection<E> compare(CollectComparator<E> comparator, Object...values){ return comparator.compare(collection, fields, values); } /** * Compare using like. * @param values for each fields * @return new Collection (ArrayList) with the filter * @since 1.0 - * @see #primitiveLike(Object[]) - * @see #objectLike(Object[]) + * @see LikeComparator * @throws CollectException + * @see #compare(CollectComparator, Object...) */ public Collection<E> like(Object...values){ return compare(new LikeComparator<E>(), values); } + /** + * Compare if any field is equals to all values. + * @param values for each fields + * new Collection (ArrayList) with the filter + * @since 1.0 + * @see OnlyComparator + * @see #compare(CollectComparator, Object...) + * @throws CollectException + */ + public Collection<E> only(Object...values){ + return compare(new OnlyComparator<E>(), values); + } } diff --git a/src/main/java/com/rollingwithcode/collect/comparator/OnlyComparator.java b/src/main/java/com/rollingwithcode/collect/comparator/OnlyComparator.java new file mode 100644 index 0000000..6ad2b08 --- /dev/null +++ b/src/main/java/com/rollingwithcode/collect/comparator/OnlyComparator.java @@ -0,0 +1,100 @@ +/** + * + */ +package com.rollingwithcode.collect.comparator; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; + +import com.rollingwithcode.collect.CollectException; + +/** + * Compare values and use only if equals to all values + * @author Rafael Felix da Silva + * @version 1.0 + * @since 1.0-snapshot + */ +public class OnlyComparator<E> implements CollectComparator<E> { + + @Override + public Collection<E> compare(Collection<E> original, Object[] fields, + Object[] values) { + if(fields != null && fields.length != values.length){ + throw new CollectException("Invalid value or field length to compare"); + } + if(fields == null){ + return primitiveEquals(original, fields, values); + } + try { + return objectEquals(original, fields, values); + } catch (IllegalArgumentException e) { + throw new CollectException(e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new CollectException(e.getMessage(), e); + } + } + + /** + * Compare when the object have same references (equals) + * @param values for each fields + * @return new Collection (ArrayList) with the filter + * @since 1.0 + * @see #objectEquals(Object[]) + * @see #eql(Object...) + */ + @SuppressWarnings("unchecked") + private Collection<E> primitiveEquals(Collection<E> original, Object[] fields, + Object[] values){ + Collection<E> newCollection = new ArrayList<E>(); + for(Object o : original){ + boolean flag = true; + for(Object value : values){ + flag = flag && o.equals(value); + } + if(flag){ + newCollection.add((E) o); + } + } + return newCollection; + } + /** + * Compare values in the fields using reflection + * @param values for each fields + * @return new Collection (ArrayList) with the filter + * @since 1.0 + * @see #primitiveEquals(Object[]) + * @see #eql(Object...) + * @throws IllegalArgumentException + * @throws IllegalAccessException + */ + @SuppressWarnings("unchecked") + private Collection<E> objectEquals(Collection<E> original, Object[] fields, + Object[] values) throws IllegalArgumentException, IllegalAccessException{ + Collection<E> newCollection = new ArrayList<E>(); + Field[] keys = null; + for(Object o : original){ + if(keys == null){ + keys = o.getClass().getDeclaredFields(); + } + boolean flag = true; + Integer i = 0; + for(Object field : fields){ + for(Field f : keys){ + if(f.getName().equals(field)){ + f.setAccessible(true); + Object vl =f.get(o); + flag = flag && vl.equals(values[i]); + } + } + i++; + } + if(flag){ + newCollection.add((E) o); + } + + } + return newCollection; + } + +} diff --git a/src/test/java/com/rollingwithcode/collect/CollectTest.java b/src/test/java/com/rollingwithcode/collect/CollectTest.java index c537a31..93a6885 100644 --- a/src/test/java/com/rollingwithcode/collect/CollectTest.java +++ b/src/test/java/com/rollingwithcode/collect/CollectTest.java @@ -1,141 +1,146 @@ /** * */ package com.rollingwithcode.collect; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import com.rollingwithcode.collect.comparator.CollectComparator; /** * Unit test for the Collect class * @author Rafael Felix da Silva * @version 1.0 * @since 0.1-snapshot */ public class CollectTest { private Collect collect; private List<String> list; private Set<Person> persons; @Before public void before(){ collect = new Collect(); list = new ArrayList<String>(); list.add("Banana"); list.add("Apple"); list.add("Coconut"); list.add("Cherry"); list.add("Guava"); persons = new HashSet<Person>(); persons.add(new Person("John", 32)); persons.add(new Person("Edward", 18)); persons.add(new Person("Rafael", 21)); persons.add(new Person("Dan", 21)); } @Test public void shouldReturnWhenHandler(){ WhenHandler<String> when = collect.in(list); assertNotNull(when); } @Test(expected=NullPointerException.class) public void shouldNotReturnWhenHandler(){ collect.in(null); } @Test public void shouldCollectWithLikeWihoutFields(){ Collection<String> ret = collect.in(list).when().like("C"); assertEquals(2, ret.size()); } @Test public void shouldCollectWithEqlWihoutFields(){ Collection<String> ret = collect.in(list).when().like("Apple"); assertEquals(1, ret.size()); } @Test public void shouldCollectWithLikeWithFields(){ Collection<Person> ret = collect.in(persons).when("name").like("a"); assertEquals(3, ret.size()); } @Test public void shouldCollectWithEqlWithFields(){ Collection<Person> ret = collect.in(persons).when("age").eql(21); assertEquals(2, ret.size()); } @Test public void shouldCollectWithLikeWithTwoFields(){ Collection<Person> ret = collect.in(persons).when("name", "age").like("n", 2); assertEquals(3, ret.size()); } @Test public void shouldCollectWithLikeEqlTwoFields(){ Collection<Person> ret = collect.in(persons).when("name", "age").like("Rafael", 21); assertEquals(2, ret.size()); } - + @Test public void shouldCollectWithCustomCompare(){ Collection<Person> ret = collect.in(persons).when().compare(new CollectComparator<Person>(){ @Override public Collection<Person> compare(Collection<Person> original, Object[] fields, Object[] values) { Collection<Person> newCollection = new ArrayList<Person>(); for(Person p : original){ for(Object v : values){ if(p.getName().startsWith(String.valueOf(v))){ newCollection.add(p); } } } return newCollection; } }, "R"); assertEquals(1, ret.size()); } + @Test + public void shouldCollectWithOnly(){ + Collection<Person> col = collect.in(persons).when("name", "age").only("Rafael", 21); + assertEquals(1, col.size()); + } private class Person{ private String name; private Integer age; public Person(String name, Integer age) { super(); this.name = name; this.age = age; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the age */ public Integer getAge() { return age; } /** * @param age the age to set */ public void setAge(Integer age) { this.age = age; } } }
fellix/collect4j
2088bbece46104fa4ea5952587feee15bde1db53
POM updated
diff --git a/pom.xml b/pom.xml index ae80ff5..b6bb0dc 100644 --- a/pom.xml +++ b/pom.xml @@ -1,45 +1,88 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.rollingwithcode</groupId> - <artifactId>Collect4j</artifactId> + <artifactId>collect4j</artifactId> <name>collect4j</name> <version>0.1-SNAPSHOT</version> - <description>DSL for Java Collection API</description> + <description>DSL for consulting Java Collection API + Using this DSL you can filter a collection using a high level language. + Collect4j supports objects and primitive types. + </description> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> <developers> <developer> <name>Rafael Felix da Silva</name> <email>felix.rafael@gmail.com</email> <url>http://rollingwithcode.blogspot.com</url> <roles> - <role>Creator</role> + <role>Project Manager</role> + <role>Architect</role> </roles> </developer> </developers> <licenses> <license> <name>MIT-LICENSE</name> + <url>MIT-LICENSE</url> </license> </licenses> <inceptionYear>2009</inceptionYear> + <scm> + <connection>scm:git://github.com/fellix/collect4j.git</connection> + <url>https://github.com/fellix/collect4j/tree</url> + </scm> + <mailingLists> + <mailingList> + <name>Users Mailing List</name> + <subscribe></subscribe> + <unsubscribe></unsubscribe> + <archive>https://sourceforge.net/mailarchive/forum.php?forum_name=collect4j-users</archive> + </mailingList> + <mailingList> + <name>Developers Mailing List</name> + <subscribe></subscribe> + <unsubscribe></unsubscribe> + <archive>https://sourceforge.net/mailarchive/forum.php?forum_name=collect4j-devel</archive> + </mailingList> + </mailingLists> + <reporting> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.5</version> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>jxr-maven-plugin</artifactId> + </plugin> + <plugin> + <artifactId>maven-surefire-plugin</artifactId> + </plugin> + <plugin> + <artifactId>maven-clover-plugin</artifactId> + </plugin> + + </plugins> + </reporting> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.6</version> <scope>test</scope> </dependency> </dependencies> </project> \ No newline at end of file
fellix/collect4j
d8674030020dc13399ae619312a609727502afd7
Added JUnit tests
diff --git a/src/test/java/com/rollingwithcode/collect/CollectTest.java b/src/test/java/com/rollingwithcode/collect/CollectTest.java new file mode 100644 index 0000000..c537a31 --- /dev/null +++ b/src/test/java/com/rollingwithcode/collect/CollectTest.java @@ -0,0 +1,141 @@ +/** + * + */ +package com.rollingwithcode.collect; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +import com.rollingwithcode.collect.comparator.CollectComparator; + +/** + * Unit test for the Collect class + * @author Rafael Felix da Silva + * @version 1.0 + * @since 0.1-snapshot + */ +public class CollectTest { + private Collect collect; + private List<String> list; + private Set<Person> persons; + + @Before + public void before(){ + collect = new Collect(); + list = new ArrayList<String>(); + list.add("Banana"); + list.add("Apple"); + list.add("Coconut"); + list.add("Cherry"); + list.add("Guava"); + persons = new HashSet<Person>(); + persons.add(new Person("John", 32)); + persons.add(new Person("Edward", 18)); + persons.add(new Person("Rafael", 21)); + persons.add(new Person("Dan", 21)); + } + + @Test + public void shouldReturnWhenHandler(){ + WhenHandler<String> when = collect.in(list); + assertNotNull(when); + } + @Test(expected=NullPointerException.class) + public void shouldNotReturnWhenHandler(){ + collect.in(null); + } + @Test + public void shouldCollectWithLikeWihoutFields(){ + Collection<String> ret = collect.in(list).when().like("C"); + assertEquals(2, ret.size()); + } + @Test + public void shouldCollectWithEqlWihoutFields(){ + Collection<String> ret = collect.in(list).when().like("Apple"); + assertEquals(1, ret.size()); + } + @Test + public void shouldCollectWithLikeWithFields(){ + Collection<Person> ret = collect.in(persons).when("name").like("a"); + assertEquals(3, ret.size()); + } + @Test + public void shouldCollectWithEqlWithFields(){ + Collection<Person> ret = collect.in(persons).when("age").eql(21); + assertEquals(2, ret.size()); + } + @Test + public void shouldCollectWithLikeWithTwoFields(){ + Collection<Person> ret = collect.in(persons).when("name", "age").like("n", 2); + assertEquals(3, ret.size()); + } + @Test + public void shouldCollectWithLikeEqlTwoFields(){ + Collection<Person> ret = collect.in(persons).when("name", "age").like("Rafael", 21); + assertEquals(2, ret.size()); + } + + public void shouldCollectWithCustomCompare(){ + Collection<Person> ret = collect.in(persons).when().compare(new CollectComparator<Person>(){ + + @Override + public Collection<Person> compare(Collection<Person> original, + Object[] fields, Object[] values) { + Collection<Person> newCollection = new ArrayList<Person>(); + for(Person p : original){ + for(Object v : values){ + if(p.getName().startsWith(String.valueOf(v))){ + newCollection.add(p); + } + } + } + return newCollection; + } + + }, "R"); + assertEquals(1, ret.size()); + } + + private class Person{ + private String name; + private Integer age; + public Person(String name, Integer age) { + super(); + this.name = name; + this.age = age; + } + /** + * @return the name + */ + public String getName() { + return name; + } + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + /** + * @return the age + */ + public Integer getAge() { + return age; + } + /** + * @param age the age to set + */ + public void setAge(Integer age) { + this.age = age; + } + + } +}
fellix/collect4j
2728eab88800438471dc5841fefe2c3252d7f7f1
Import adjusts
diff --git a/src/main/java/com/rollingwithcode/collect/Collect.java b/src/main/java/com/rollingwithcode/collect/Collect.java index 3b60240..6cb3815 100644 --- a/src/main/java/com/rollingwithcode/collect/Collect.java +++ b/src/main/java/com/rollingwithcode/collect/Collect.java @@ -1,28 +1,29 @@ /** * */ package com.rollingwithcode.collect; import java.util.Collection; + /** * Main class for the DSL. * @author Rafael Felix da Silva * @version 1.0 * @since 0.1-snapshot */ public class Collect { /** * Prepare a collection to search inside * @param <T> Generic for the collection * @param collection to eval * @return WhenHandler * @since 1.0 */ public <T> WhenHandler<T> in(Collection<T> collection){ if(collection == null){ throw new NullPointerException("Collection can not be null"); } return new WhenHandler<T>(collection); } } diff --git a/src/main/java/com/rollingwithcode/collect/Test.java b/src/main/java/com/rollingwithcode/collect/Test.java index abc208c..f3255c4 100644 --- a/src/main/java/com/rollingwithcode/collect/Test.java +++ b/src/main/java/com/rollingwithcode/collect/Test.java @@ -1,111 +1,112 @@ package com.rollingwithcode.collect; import java.util.ArrayList; import java.util.Collection; import java.util.List; + public class Test { /** * @param args */ public static void main(String[] args) { System.out.println("Começando"); List<String> lista = new ArrayList<String>(); lista.add("Uva"); lista.add("Maça"); lista.add("Melancia"); lista.add("Melão"); lista.add("Maracujá"); Collection<String> busca = new Collect().in(lista).when().eql("Mel", "Ma"); for(String s : busca){ System.out.println(s); } List<Pessoa> pessoas = new ArrayList<Pessoa>(); pessoas.add(new Pessoa("Rafael", 21)); pessoas.add(new Pessoa("Suélen", 19)); pessoas.add(new Pessoa("Samuel", 25)); pessoas.add(new Pessoa("Pedro", 23)); pessoas.add(new Pessoa("Rafael", 23)); Collection<Pessoa> buscaP = new Collect().in(pessoas).when("nome").eql("Rafael"); for(Pessoa p : buscaP){ System.out.println(p); } buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("idade").eql(23); for(Pessoa p : buscaP){ System.out.println(p); } System.out.println(); System.out.println(); buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("nome", "idade").eql("Rafael", 23); for(Pessoa p : buscaP){ System.out.println(p); } System.out.println(); busca = (Collection<String>) new Collect().in(lista).when().like("M"); for(String s : busca){ System.out.println(s); } System.out.println(); buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("nome").like("S"); for(Pessoa p : buscaP){ System.out.println(p); } System.out.println(); buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("idade").like("1"); for(Pessoa p : buscaP){ System.out.println(p); } } private static class Pessoa{ String nome; int idade; public Pessoa() { super(); } public Pessoa(String nome, int idade) { super(); this.nome = nome; this.idade = idade; } /** * @return the nome */ public String getNome() { return nome; } /** * @param nome the nome to set */ public void setNome(String nome) { this.nome = nome; } /** * @return the idade */ public int getIdade() { return idade; } /** * @param idade the idade to set */ public void setIdade(int idade) { this.idade = idade; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Pessoa["+nome+", "+idade+" ]"; } } } diff --git a/src/main/java/com/rollingwithcode/collect/WhenHandler.java b/src/main/java/com/rollingwithcode/collect/WhenHandler.java index 20aa501..99ca6e7 100644 --- a/src/main/java/com/rollingwithcode/collect/WhenHandler.java +++ b/src/main/java/com/rollingwithcode/collect/WhenHandler.java @@ -1,48 +1,49 @@ /** * */ package com.rollingwithcode.collect; import java.util.Collection; + /** * Make conditions for the collection * @author Rafael Felix da Silva * @version 1.0 * @since 0.1-snaphost */ public class WhenHandler<E> { private Collection<E> collection; /** * Defaults construtor * @param collection * @since 1.0 */ public WhenHandler(Collection<E> collection) { super(); this.collection = collection; if(collection == null){ throw new NullPointerException("Collection cann't be null"); } } /** * Select some fields for filter * @param fields to filter * @return CompareHandler * @since 1.0 * @see #when() */ public CompareHandler<E> when(Object...fields){ return new CompareHandler<E>(fields, collection); } /** * Use the default toString() method to compare * @return CompareHandler * @since 1.0 * @see #when(Object...) */ public CompareHandler<E> when(){ return new CompareHandler<E>(null, collection); } }
fellix/collect4j
6eb723a2fedc5b3ad49af43e9c6660e609c32e55
Adjust some API details
diff --git a/.classpath b/.classpath index 96489ff..c611757 100644 --- a/.classpath +++ b/.classpath @@ -1,10 +1,10 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" output="target/classes" path="src/main/java"/> <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/> <classpathentry kind="src" output="target/test-classes" path="src/test/java"/> <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> - <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/> + <classpathentry exported="true" kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/> <classpathentry kind="output" path="target/classes"/> </classpath> diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..4533ad6 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,12 @@ +#Wed Jul 08 20:22:55 BRT 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/pom.xml b/pom.xml index 6ab086b..ae80ff5 100644 --- a/pom.xml +++ b/pom.xml @@ -1,33 +1,45 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.rollingwithcode</groupId> <artifactId>Collect4j</artifactId> <name>collect4j</name> <version>0.1-SNAPSHOT</version> <description>DSL for Java Collection API</description> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>1.6</source> + <target>1.6</target> + </configuration> + </plugin> + </plugins> + </build> <developers> <developer> <name>Rafael Felix da Silva</name> <email>felix.rafael@gmail.com</email> <url>http://rollingwithcode.blogspot.com</url> <roles> <role>Creator</role> </roles> </developer> </developers> <licenses> <license> <name>MIT-LICENSE</name> </license> </licenses> <inceptionYear>2009</inceptionYear> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.6</version> <scope>test</scope> </dependency> </dependencies> </project> \ No newline at end of file diff --git a/src/main/java/com/rollingwithcode/collect/CompareHandler.java b/src/main/java/com/rollingwithcode/collect/CompareHandler.java index c872afd..7f77388 100644 --- a/src/main/java/com/rollingwithcode/collect/CompareHandler.java +++ b/src/main/java/com/rollingwithcode/collect/CompareHandler.java @@ -1,140 +1,67 @@ /** * */ package com.rollingwithcode.collect; -import java.lang.reflect.Field; -import java.util.ArrayList; import java.util.Collection; import com.rollingwithcode.collect.comparator.CollectComparator; import com.rollingwithcode.collect.comparator.EqualsComparator; +import com.rollingwithcode.collect.comparator.LikeComparator; /** * Used to make compare using values * @author Rafael Felix da Silva * @version 1.0 * @since 0.1-snaphost */ public class CompareHandler<E> { private Object[] fields; private Collection<E> collection; /** * Defaults construtor * @param fields to filter * @param collection to eval * @since 1.0 */ public CompareHandler(Object[] fields, Collection<E> collection) { super(); this.fields = fields; this.collection = collection; } /** * Compare object with when same (equals) * @param values for each fields * @return new Collection (ArrayList) with the filter * @since 1.0 * @see #compare(CollectComparator, Object...) * @see EqualsComparator */ public Collection<E> eql(Object...values){ return compare(new EqualsComparator<E>(), values); } /** * Generic method for custom compare * @param comparator the Comparator implementation * @param values passed as parameters * @return Collection for the result * @since 1.0 */ public Collection<E> compare(CollectComparator<E> comparator, Object...values){ return comparator.compare(collection, fields, values); } /** * Compare using like. * @param values for each fields * @return new Collection (ArrayList) with the filter * @since 1.0 * @see #primitiveLike(Object[]) * @see #objectLike(Object[]) * @throws CollectException */ public Collection<E> like(Object...values){ - if(fields != null && fields.length != values.length){ - throw new CollectException("Invalid value or field length to compare"); - } - if(fields == null){ - return primitiveLike(values); - } - try{ - return objectLike(values); - } catch (IllegalArgumentException e) { - throw new CollectException(e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new CollectException(e.getMessage(), e); - } - } - /** - * Verify if the toString (String.valueOf) of the object contains each passed value - * @param values for each fields - * @return new Collection (ArrayList) with the filter - * @since 1.0 - * @see Object#toString() - * @see String#valueOf(Object) - * @see #objectLike(Object[]) - * @see #like(Object...) - */ - @SuppressWarnings("unchecked") - private Collection<E> primitiveLike(Object[] values){ - Collection<E> newCollection = new ArrayList<E>(); - for(Object o : collection){ - for(Object value : values){ - if(String.valueOf(o).contains(String.valueOf(value))){ - if(!newCollection.contains(o)){ - newCollection.add((E)o); - } - } - } - } - return newCollection; - } - /** - * Verify if the toString (String.valueOf) of the select fields in the object contains each passed value - * @param values for each fields - * @return new Collection (ArrayList) with the filter - * @since 1.0 - * @see Object#toString() - * @see String#valueOf(Object) - * @see #primitiveLike(Object[]) - * @see #like(Object...) - */ - @SuppressWarnings("unchecked") - private Collection<E> objectLike(Object[] values) throws IllegalArgumentException, IllegalAccessException{ - Collection<E> newCollection = new ArrayList<E>(); - Field[] keys = null; - for(Object o : collection){ - if(keys == null){ - keys = o.getClass().getDeclaredFields(); - } - Integer i = 0; - for(Object field : fields){ - for(Field f : keys){ - if(f.getName().equals(field)){ - f.setAccessible(true); - if(String.valueOf(f.get(o)).contains(String.valueOf(values[i]))){ - if(!newCollection.contains(o)){ - newCollection.add((E)o); - } - } - } - } - i++; - } - - } - return newCollection; + return compare(new LikeComparator<E>(), values); } } diff --git a/src/main/java/com/rollingwithcode/collect/comparator/LikeComparator.java b/src/main/java/com/rollingwithcode/collect/comparator/LikeComparator.java new file mode 100644 index 0000000..724def2 --- /dev/null +++ b/src/main/java/com/rollingwithcode/collect/comparator/LikeComparator.java @@ -0,0 +1,100 @@ +/** + * + */ +package com.rollingwithcode.collect.comparator; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; + +import com.rollingwithcode.collect.CollectException; + +/** + * Make an comparator with the contains method + * @author Rafael Felix da Silva + * @since 0.1-snapshot + * @version 1.0 + */ +public class LikeComparator<E> implements CollectComparator<E> { + + @Override + public Collection<E> compare(Collection<E> original, Object[] fields, Object[] values) { + if(fields != null && fields.length != values.length){ + throw new CollectException("Invalid value or field length to compare"); + } + if(fields == null){ + return primitiveLike(original, fields, values); + } + try{ + return objectLike(original, fields, values); + } catch (IllegalArgumentException e) { + throw new CollectException(e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new CollectException(e.getMessage(), e); + } + } + + /** + * Verify if the toString (String.valueOf) of the object contains each passed value + * @param values for each fields + * @return new Collection (ArrayList) with the filter + * @since 1.0 + * @see Object#toString() + * @see String#valueOf(Object) + * @see #objectLike(Object[]) + * @see #like(Object...) + */ + @SuppressWarnings("unchecked") + private Collection<E> primitiveLike(Collection<E> original, Object[] fields, + Object[] values){ + Collection<E> newCollection = new ArrayList<E>(); + for(Object o : original){ + for(Object value : values){ + if(String.valueOf(o).contains(String.valueOf(value))){ + if(!newCollection.contains(o)){ + newCollection.add((E)o); + } + } + } + } + return newCollection; + } + /** + * Verify if the toString (String.valueOf) of the select fields in the object contains each passed value + * @param values for each fields + * @return new Collection (ArrayList) with the filter + * @since 1.0 + * @see Object#toString() + * @see String#valueOf(Object) + * @see #primitiveLike(Object[]) + * @see #like(Object...) + */ + @SuppressWarnings("unchecked") + private Collection<E> objectLike(Collection<E> original, Object[] fields, + Object[] values) throws IllegalArgumentException, IllegalAccessException{ + Collection<E> newCollection = new ArrayList<E>(); + Field[] keys = null; + for(Object o : original){ + if(keys == null){ + keys = o.getClass().getDeclaredFields(); + } + Integer i = 0; + for(Object field : fields){ + for(Field f : keys){ + if(f.getName().equals(field)){ + f.setAccessible(true); + if(String.valueOf(f.get(o)).contains(String.valueOf(values[i]))){ + if(!newCollection.contains(o)){ + newCollection.add((E)o); + } + } + } + } + i++; + } + + } + return newCollection; + } + +} diff --git a/src/test/java/com/rollingwithcode/collect/CollectTest.java b/src/test/java/com/rollingwithcode/collect/CollectTest.java deleted file mode 100644 index e810057..0000000 --- a/src/test/java/com/rollingwithcode/collect/CollectTest.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.rollingwithcode.collect; - - - -public class CollectTest { -}
fellix/collect4j
4ef93c4e0e16bd9f76a5c3930c12c38ef7fc4b40
Added some API Implementation for User customizations
diff --git a/src/main/java/com/rollingwithcode/collect/Collect.java b/src/main/java/com/rollingwithcode/collect/Collect.java index b426034..3b60240 100644 --- a/src/main/java/com/rollingwithcode/collect/Collect.java +++ b/src/main/java/com/rollingwithcode/collect/Collect.java @@ -1,28 +1,28 @@ /** * */ package com.rollingwithcode.collect; import java.util.Collection; /** * Main class for the DSL. * @author Rafael Felix da Silva * @version 1.0 * @since 0.1-snapshot */ public class Collect { /** * Prepare a collection to search inside * @param <T> Generic for the collection * @param collection to eval * @return WhenHandler * @since 1.0 */ - public <T> WhenHandler in(Collection<T> collection){ + public <T> WhenHandler<T> in(Collection<T> collection){ if(collection == null){ throw new NullPointerException("Collection can not be null"); } - return new WhenHandler(collection); + return new WhenHandler<T>(collection); } } diff --git a/src/main/java/com/rollingwithcode/collect/CompareHandler.java b/src/main/java/com/rollingwithcode/collect/CompareHandler.java index 42694b1..c872afd 100644 --- a/src/main/java/com/rollingwithcode/collect/CompareHandler.java +++ b/src/main/java/com/rollingwithcode/collect/CompareHandler.java @@ -1,193 +1,140 @@ /** * */ package com.rollingwithcode.collect; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; +import com.rollingwithcode.collect.comparator.CollectComparator; +import com.rollingwithcode.collect.comparator.EqualsComparator; + /** * Used to make compare using values * @author Rafael Felix da Silva * @version 1.0 * @since 0.1-snaphost */ -public class CompareHandler { +public class CompareHandler<E> { private Object[] fields; - private Collection<?> collection; + private Collection<E> collection; /** * Defaults construtor * @param fields to filter * @param collection to eval * @since 1.0 */ - public CompareHandler(Object[] fields, Collection<?> collection) { + public CompareHandler(Object[] fields, Collection<E> collection) { super(); this.fields = fields; this.collection = collection; } /** * Compare object with when same (equals) * @param values for each fields * @return new Collection (ArrayList) with the filter * @since 1.0 - * @see #primitiveEquals(Object[]) - * @see #objectEquals(Object[]) - * @throws CollectException + * @see #compare(CollectComparator, Object...) + * @see EqualsComparator */ - public Collection<?> eql(Object...values){ - if(fields != null && fields.length != values.length){ - throw new CollectException("Invalid value or field length to compare"); - } - if(fields == null){ - return primitiveEquals(values); - } - try { - return objectEquals(values); - } catch (IllegalArgumentException e) { - throw new CollectException(e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new CollectException(e.getMessage(), e); - } + public Collection<E> eql(Object...values){ + return compare(new EqualsComparator<E>(), values); } /** - * Compare when the object have same references (equals) - * @param values for each fields - * @return new Collection (ArrayList) with the filter + * Generic method for custom compare + * @param comparator the Comparator implementation + * @param values passed as parameters + * @return Collection for the result * @since 1.0 - * @see #objectEquals(Object[]) - * @see #eql(Object...) */ - private Collection<?> primitiveEquals(Object[] values){ - Collection<Object> newCollection = new ArrayList<Object>(); - for(Object o : collection){ - for(Object value : values){ - if(o.equals(value)){ - if(!newCollection.contains(o)){ - newCollection.add(o); - } - } - } - } - return newCollection; - } - /** - * Compare values in the fields using reflection - * @param values for each fields - * @return new Collection (ArrayList) with the filter - * @since 1.0 - * @see #primitiveEquals(Object[]) - * @see #eql(Object...) - * @throws IllegalArgumentException - * @throws IllegalAccessException - */ - private Collection<?> objectEquals(Object[] values) throws IllegalArgumentException, IllegalAccessException{ - Collection<Object> newCollection = new ArrayList<Object>(); - Field[] keys = null; - for(Object o : collection){ - if(keys == null){ - keys = o.getClass().getDeclaredFields(); - } - Integer i = 0; - for(Object field : fields){ - for(Field f : keys){ - if(f.getName().equals(field)){ - f.setAccessible(true); - if(f.get(o).equals(values[i])){ - if(!newCollection.contains(o)){ - newCollection.add(o); - } - } - } - } - i++; - } - - } - return newCollection; + public Collection<E> compare(CollectComparator<E> comparator, Object...values){ + return comparator.compare(collection, fields, values); } + /** * Compare using like. * @param values for each fields * @return new Collection (ArrayList) with the filter * @since 1.0 * @see #primitiveLike(Object[]) * @see #objectLike(Object[]) * @throws CollectException */ - public Collection<?> like(Object...values){ + public Collection<E> like(Object...values){ if(fields != null && fields.length != values.length){ throw new CollectException("Invalid value or field length to compare"); } if(fields == null){ return primitiveLike(values); } try{ return objectLike(values); } catch (IllegalArgumentException e) { throw new CollectException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new CollectException(e.getMessage(), e); } } /** * Verify if the toString (String.valueOf) of the object contains each passed value * @param values for each fields * @return new Collection (ArrayList) with the filter * @since 1.0 * @see Object#toString() * @see String#valueOf(Object) * @see #objectLike(Object[]) * @see #like(Object...) */ - private Collection<?> primitiveLike(Object[] values){ - Collection<Object> newCollection = new ArrayList<Object>(); + @SuppressWarnings("unchecked") + private Collection<E> primitiveLike(Object[] values){ + Collection<E> newCollection = new ArrayList<E>(); for(Object o : collection){ for(Object value : values){ if(String.valueOf(o).contains(String.valueOf(value))){ if(!newCollection.contains(o)){ - newCollection.add(o); + newCollection.add((E)o); } } } } return newCollection; } /** * Verify if the toString (String.valueOf) of the select fields in the object contains each passed value * @param values for each fields * @return new Collection (ArrayList) with the filter * @since 1.0 * @see Object#toString() * @see String#valueOf(Object) * @see #primitiveLike(Object[]) * @see #like(Object...) */ - private Collection<?> objectLike(Object[] values) throws IllegalArgumentException, IllegalAccessException{ - Collection<Object> newCollection = new ArrayList<Object>(); + @SuppressWarnings("unchecked") + private Collection<E> objectLike(Object[] values) throws IllegalArgumentException, IllegalAccessException{ + Collection<E> newCollection = new ArrayList<E>(); Field[] keys = null; for(Object o : collection){ if(keys == null){ keys = o.getClass().getDeclaredFields(); } Integer i = 0; for(Object field : fields){ for(Field f : keys){ if(f.getName().equals(field)){ f.setAccessible(true); if(String.valueOf(f.get(o)).contains(String.valueOf(values[i]))){ if(!newCollection.contains(o)){ - newCollection.add(o); + newCollection.add((E)o); } } } } i++; } } return newCollection; } } diff --git a/src/main/java/com/rollingwithcode/collect/Test.java b/src/main/java/com/rollingwithcode/collect/Test.java index 8ae6898..abc208c 100644 --- a/src/main/java/com/rollingwithcode/collect/Test.java +++ b/src/main/java/com/rollingwithcode/collect/Test.java @@ -1,111 +1,111 @@ package com.rollingwithcode.collect; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class Test { /** * @param args */ public static void main(String[] args) { System.out.println("Começando"); List<String> lista = new ArrayList<String>(); lista.add("Uva"); lista.add("Maça"); lista.add("Melancia"); lista.add("Melão"); lista.add("Maracujá"); - Collection<String> busca = (Collection<String>) new Collect().in(lista).when().eql("Mel", "Ma"); + Collection<String> busca = new Collect().in(lista).when().eql("Mel", "Ma"); for(String s : busca){ System.out.println(s); } List<Pessoa> pessoas = new ArrayList<Pessoa>(); pessoas.add(new Pessoa("Rafael", 21)); pessoas.add(new Pessoa("Suélen", 19)); pessoas.add(new Pessoa("Samuel", 25)); pessoas.add(new Pessoa("Pedro", 23)); pessoas.add(new Pessoa("Rafael", 23)); - Collection<Pessoa> buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("nome").eql("Rafael"); + Collection<Pessoa> buscaP = new Collect().in(pessoas).when("nome").eql("Rafael"); for(Pessoa p : buscaP){ System.out.println(p); } buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("idade").eql(23); for(Pessoa p : buscaP){ System.out.println(p); } System.out.println(); System.out.println(); buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("nome", "idade").eql("Rafael", 23); for(Pessoa p : buscaP){ System.out.println(p); } System.out.println(); busca = (Collection<String>) new Collect().in(lista).when().like("M"); for(String s : busca){ System.out.println(s); } System.out.println(); buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("nome").like("S"); for(Pessoa p : buscaP){ System.out.println(p); } System.out.println(); buscaP = (Collection<Pessoa>) new Collect().in(pessoas).when("idade").like("1"); for(Pessoa p : buscaP){ System.out.println(p); } } private static class Pessoa{ String nome; int idade; public Pessoa() { super(); } public Pessoa(String nome, int idade) { super(); this.nome = nome; this.idade = idade; } /** * @return the nome */ public String getNome() { return nome; } /** * @param nome the nome to set */ public void setNome(String nome) { this.nome = nome; } /** * @return the idade */ public int getIdade() { return idade; } /** * @param idade the idade to set */ public void setIdade(int idade) { this.idade = idade; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Pessoa["+nome+", "+idade+" ]"; } } } diff --git a/src/main/java/com/rollingwithcode/collect/WhenHandler.java b/src/main/java/com/rollingwithcode/collect/WhenHandler.java index a620f95..20aa501 100644 --- a/src/main/java/com/rollingwithcode/collect/WhenHandler.java +++ b/src/main/java/com/rollingwithcode/collect/WhenHandler.java @@ -1,48 +1,48 @@ /** * */ package com.rollingwithcode.collect; import java.util.Collection; /** * Make conditions for the collection * @author Rafael Felix da Silva * @version 1.0 * @since 0.1-snaphost */ -public class WhenHandler { - private Collection<?> collection; +public class WhenHandler<E> { + private Collection<E> collection; /** * Defaults construtor * @param collection * @since 1.0 */ - public WhenHandler(Collection<?> collection) { + public WhenHandler(Collection<E> collection) { super(); this.collection = collection; if(collection == null){ throw new NullPointerException("Collection cann't be null"); } } /** * Select some fields for filter * @param fields to filter * @return CompareHandler * @since 1.0 * @see #when() */ - public CompareHandler when(Object...fields){ - return new CompareHandler(fields, collection); + public CompareHandler<E> when(Object...fields){ + return new CompareHandler<E>(fields, collection); } /** * Use the default toString() method to compare * @return CompareHandler * @since 1.0 * @see #when(Object...) */ - public CompareHandler when(){ - return new CompareHandler(null, collection); + public CompareHandler<E> when(){ + return new CompareHandler<E>(null, collection); } } diff --git a/src/main/java/com/rollingwithcode/collect/comparator/CollectComparator.java b/src/main/java/com/rollingwithcode/collect/comparator/CollectComparator.java new file mode 100644 index 0000000..46db8df --- /dev/null +++ b/src/main/java/com/rollingwithcode/collect/comparator/CollectComparator.java @@ -0,0 +1,25 @@ +/** + * + */ +package com.rollingwithcode.collect.comparator; + +import java.util.Collection; + +/** + * Interface used for compare the objects + * @param <E> Generic type for the compare + * @author Rafael Felix da Silva + * @version 1.0 + * @since 0.1-snapshot + */ +public interface CollectComparator<E> { + /** + * Performe the Compare using this class + * @param original Collection to compare + * @param fields to compare + * @param values to match with the fields + * @return new Collection<E> + * @since 1.0 + */ + Collection<E> compare(Collection<E> original, Object[] fields, Object[] values); +} diff --git a/src/main/java/com/rollingwithcode/collect/comparator/EqualsComparator.java b/src/main/java/com/rollingwithcode/collect/comparator/EqualsComparator.java new file mode 100644 index 0000000..fb52ec6 --- /dev/null +++ b/src/main/java/com/rollingwithcode/collect/comparator/EqualsComparator.java @@ -0,0 +1,97 @@ +/** + * + */ +package com.rollingwithcode.collect.comparator; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Collection; + +import com.rollingwithcode.collect.CollectException; + +/** + * Implements comparator for equals values + * @author Rafael Felix da Silva + * @since 0.1-snapshot + * @version 1.0 + */ +public class EqualsComparator<E> implements CollectComparator<E> { + + @Override + public Collection<E> compare(Collection<E> original, Object[] fields, + Object[] values) { + if(fields != null && fields.length != values.length){ + throw new CollectException("Invalid value or field length to compare"); + } + if(fields == null){ + return primitiveEquals(original, fields, values); + } + try { + return objectEquals(original, fields, values); + } catch (IllegalArgumentException e) { + throw new CollectException(e.getMessage(), e); + } catch (IllegalAccessException e) { + throw new CollectException(e.getMessage(), e); + } + } + /** + * Compare when the object have same references (equals) + * @param values for each fields + * @return new Collection (ArrayList) with the filter + * @since 1.0 + * @see #objectEquals(Object[]) + * @see #eql(Object...) + */ + @SuppressWarnings("unchecked") + private Collection<E> primitiveEquals(Collection<E> original, Object[] fields, + Object[] values){ + Collection<E> newCollection = new ArrayList<E>(); + for(Object o : original){ + for(Object value : values){ + if(o.equals(value)){ + if(!newCollection.contains(o)){ + newCollection.add((E) o); + } + } + } + } + return newCollection; + } + /** + * Compare values in the fields using reflection + * @param values for each fields + * @return new Collection (ArrayList) with the filter + * @since 1.0 + * @see #primitiveEquals(Object[]) + * @see #eql(Object...) + * @throws IllegalArgumentException + * @throws IllegalAccessException + */ + @SuppressWarnings("unchecked") + private Collection<E> objectEquals(Collection<E> original, Object[] fields, + Object[] values) throws IllegalArgumentException, IllegalAccessException{ + Collection<E> newCollection = new ArrayList<E>(); + Field[] keys = null; + for(Object o : original){ + if(keys == null){ + keys = o.getClass().getDeclaredFields(); + } + Integer i = 0; + for(Object field : fields){ + for(Field f : keys){ + if(f.getName().equals(field)){ + f.setAccessible(true); + if(f.get(o).equals(values[i])){ + if(!newCollection.contains(o)){ + newCollection.add((E) o); + } + } + } + } + i++; + } + + } + return newCollection; + } +}
fellix/collect4j
077e51ccb16fb8f33408ce84ebaa73dece76c566
Added README and Project License
diff --git a/CONTRIBUTORS b/CONTRIBUTORS new file mode 100644 index 0000000..a0139de --- /dev/null +++ b/CONTRIBUTORS @@ -0,0 +1,10 @@ +== Founder + +Rafael Felix da Silva created this project on 04/07/2009 + +== Contributors + +The following people have submitted changes which have been applied to the library: + +* Rafael Felix da Silva + diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100644 index 0000000..8eaf6db --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2008 [name of plugin creator] + +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. diff --git a/README.markdown b/README.markdown new file mode 100644 index 0000000..fabed3e --- /dev/null +++ b/README.markdown @@ -0,0 +1,61 @@ +# Collect4j +Collect4j is an DSL (Domain Specific Language) for manipulates Java Collections API. +Simple Commands do filter and access values in a collection. + +## Using +Add the jar file collect4j-X.X.jar to your classpath, or dowload from maven repositories (repo1) + +## Supports + - eql for equals comparision + - like for string content + - supports generics (objects is supported too) + - comparates some fields (Only for your custom class) + +## Usage Samples +- Simple Collections +<pre> + List<String> list = new ArrayList<String>(); + list.add("Uva"); + list.add("Maça"); + list.add("Melancia"); + list.add("Melão"); + list.add("Maracujá"); + Collection<String> busca = (Collection<String>) new Collect().in(lista).when().like("Mel", "Ma"); //Search in the collection when the content contatis the passed string. +</pre> + +Generics Collections +<pre> +public class Person{ + String name; + int age; + + public Person() { + super(); + } + + public Person(String name, int age) { + super(); + this.name = name; + this.age = age; + } + //Getters and setters + /** + * Some cases the to string is used too + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "Person["+name+", "+age+" ]"; + } + + } + + List<Person> persons = new ArrayList<Person>(); + persons.add(new Person("Rafael", 21)); + persons.add(new Person("Suélen", 19)); + persons.add(new Person("Pedro", 23)); + persons.add(new Person("Rodrigo", 23)); + Collection<Person> busca = (Collection<Person>) new Collect().in(persons).when("age").eql("23");//Compare with the field age is equals to 23, and return a new collection + Collection<Person> busca = (Collection<Person>) new Collect().in(persons).when().eql("23");//Compare the Person#toString() contais the string "23" +</pre> +
bratta/mongodb-mac-startup
ac256faedffac3abea53a92d699cf30d6709a519
allow log file configuration and change the stop command
diff --git a/MongoDB/MongoDB b/MongoDB/MongoDB index fb77da6..ac3b7e3 100755 --- a/MongoDB/MongoDB +++ b/MongoDB/MongoDB @@ -1,45 +1,46 @@ #!/bin/bash if [ -z $1 ] ; then echo "Usage: $0 [start|stop|restart] " exit 1 fi # Source the common setup functions for startup scripts test -r /etc/rc.common || exit 1 . /etc/rc.common # Set up some defaults -DBPATH="/usr/local/mongodb/db" +DBPATH='/usr/local/mongodb/db' +LOGPATH='/usr/local/mongodb/log/mongod.log' MONGOD_PORT=27017 StartService(){ - /usr/local/mongodb/bin/mongod run --dbpath=$DBPATH --port $MONGOD_PORT > /dev/null 2>&1 & + /usr/local/mongodb/bin/mongod run --dbpath=$DBPATH --logpath=$LOGPATH --port $MONGOD_PORT > /dev/null 2>&1 & } StopService() { pidfile=$DBPATH/mongod.lock # If the lockfile exists, it contains the PID if [ -e $pidfile ]; then pid=`cat $pidfile` fi # If we don't have a PID, check for it if [ "$pid" == "" ]; then pid=`/usr/sbin/lsof -i tcp:$MONGOD_PORT | tail -1 | awk '{print $2}'` fi - + # If we've found a PID, let's kill it if [ "$pid" != "" ]; then - kill -2 $pid + kill -15 $pid fi } RestartService() { StopService sleep 3 StartService } RunService $1