repo
string
commit
string
message
string
diff
string
glejeune/ruby-xslt
c04db7b83dda6633a76c25dc5a6a82e94bd82d12
Version bump to 0.9.8
diff --git a/VERSION b/VERSION index 3eefcb9..e3e1807 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.0 +0.9.8
glejeune/ruby-xslt
820fcd28ec9f1fde11b76860649daaa30548deda
Version bump to 1.0.0
diff --git a/VERSION b/VERSION index c81aa44..3eefcb9 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.9.7 +1.0.0
glejeune/ruby-xslt
9801b3b0c7370778251b95861af228e224595f04
Ruby 1.9 compatibility bug correction
diff --git a/ext/xslt_lib/extconf.rb b/ext/xslt_lib/extconf.rb index fb4bf5b..8b09630 100644 --- a/ext/xslt_lib/extconf.rb +++ b/ext/xslt_lib/extconf.rb @@ -1,58 +1,61 @@ #!/usr/bin/ruby -w # See the LICENSE file for copyright and distribution information require "mkmf" def help print <<HELP "extconf.rb" configures this package to adapt to many kinds of systems. Usage: ruby extconf.rb [OPTION]... Configuration: --help display this help and exit --with-xslt-lib=PATH --with-xslt-include=PATH --with-xslt-dir=PATH specify the directory name for the libxslt include files and/or library --disable-error-handler disables the new error handler --disable-exslt disables libexslt support <http://exslt.org/> HELP end if ARGV.include?( "--help" ) or ARGV.include?( "-h" ) help() exit 0 end if enable_config("error-handler", true) $CFLAGS += " -DUSE_ERROR_HANDLER" end #$LIBPATH.push(Config::CONFIG['libdir']) def crash(str) printf(" extconf failure: %s\n", str) exit 1 end dir_config( 'xml2' ) dir_config( 'xslt' ) have_library "xml2", "xmlParseDoc" || crash("need libxml2") have_library "xslt", "xsltParseStylesheetFile" || crash("need libxslt") -have_header "rubyio.h" + +if /^1.8/.match RUBY_VERSION + $CFLAGS += " -DRUBY_1_8" +end if enable_config("exslt", true) have_library "exslt", "exsltRegisterAll" $CFLAGS += " -DUSE_EXSLT" end $CFLAGS = '-g -Wall ' + `xml2-config --cflags`.chomp + " " + `xslt-config --cflags`.chomp + " " + $CFLAGS create_header() create_makefile("xml/xslt_lib") diff --git a/ext/xslt_lib/rb_utils.h b/ext/xslt_lib/rb_utils.h index a737b7e..ca81544 100644 --- a/ext/xslt_lib/rb_utils.h +++ b/ext/xslt_lib/rb_utils.h @@ -1,38 +1,38 @@ /** * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Please see the LICENSE file for copyright and distribution information */ #ifndef __RUBY_RB_UTILS_H__ #define __RUBY_RB_UTILS_H__ #include <ruby.h> -#if defined(HAVE_RUBYIO_H) +#ifdef RUBY_1_8 #include <rubyio.h> #else #include <ruby/io.h> #endif #include <stdio.h> #include <string.h> #include <sys/stat.h> char * getRubyObjectName( VALUE ); int isFile( const char *filename ); #endif diff --git a/ext/xslt_lib/xslt.h b/ext/xslt_lib/xslt.h index 48e21a1..9c97cfc 100644 --- a/ext/xslt_lib/xslt.h +++ b/ext/xslt_lib/xslt.h @@ -1,102 +1,102 @@ /** * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Please see the LICENSE file for copyright and distribution information */ #ifndef __RUBY_XSLT_H__ #define __RUBY_XSLT_H__ #include <ruby.h> -#if defined(HAVE_RUBYIO_H) +#ifdef RUBY_1_8 #include <rubyio.h> #else #include <ruby/io.h> #endif #include <string.h> #include <libxml/xmlmemory.h> #include <libxml/debugXML.h> #include <libxml/HTMLtree.h> #include <libxml/xmlIO.h> #include <libxml/xinclude.h> #include <libxml/catalog.h> #include <libxslt/extra.h> #include <libxslt/xslt.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> #include <libxslt/imports.h> #ifdef USE_EXSLT #include <libexslt/exslt.h> #endif #ifdef MEMWATCH #include "memwatch.h" #endif #include "rb_utils.h" #include "parser.h" #include "parameters.h" #include "extfunc.h" #define RUBY_XSLT_VERSION "0.9.7" #define RUBY_XSLT_VERNUM 097 #define RUBY_XSLT_XSLSRC_TYPE_NULL 0 #define RUBY_XSLT_XSLSRC_TYPE_STR 1 #define RUBY_XSLT_XSLSRC_TYPE_FILE 2 #define RUBY_XSLT_XSLSRC_TYPE_REXML 4 #define RUBY_XSLT_XSLSRC_TYPE_SMART 8 #define RUBY_XSLT_XSLSRC_TYPE_PARSED 16 #define RUBY_XSLT_XMLSRC_TYPE_NULL 0 #define RUBY_XSLT_XMLSRC_TYPE_STR 1 #define RUBY_XSLT_XMLSRC_TYPE_FILE 2 #define RUBY_XSLT_XMLSRC_TYPE_REXML 4 #define RUBY_XSLT_XMLSRC_TYPE_SMART 8 #define RUBY_XSLT_XMLSRC_TYPE_PARSED 16 RUBY_EXTERN VALUE eXSLTError; RUBY_EXTERN VALUE eXSLTParsingError; RUBY_EXTERN VALUE eXSLTTransformationError; typedef struct RbTxslt { int iXmlType; VALUE xXmlData; VALUE oXmlObject; VALUE xXmlString; xmlDocPtr tXMLDocument; int iXslType; VALUE xXslData; VALUE oXslObject; VALUE xXslString; xsltStylesheetPtr tParsedXslt; int iXmlResultType; VALUE xXmlResultCache; VALUE pxParams; int iNbParams; } RbTxslt; #endif
glejeune/ruby-xslt
45e9fc28e0c979b2aad1e9a8d19a620ae05360b2
Maybe we are ready for 0.9.7
diff --git a/ext/xslt_lib/xslt.h b/ext/xslt_lib/xslt.h index 7128630..48e21a1 100644 --- a/ext/xslt_lib/xslt.h +++ b/ext/xslt_lib/xslt.h @@ -1,102 +1,102 @@ /** * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Please see the LICENSE file for copyright and distribution information */ #ifndef __RUBY_XSLT_H__ #define __RUBY_XSLT_H__ #include <ruby.h> #if defined(HAVE_RUBYIO_H) #include <rubyio.h> #else #include <ruby/io.h> #endif #include <string.h> #include <libxml/xmlmemory.h> #include <libxml/debugXML.h> #include <libxml/HTMLtree.h> #include <libxml/xmlIO.h> #include <libxml/xinclude.h> #include <libxml/catalog.h> #include <libxslt/extra.h> #include <libxslt/xslt.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> #include <libxslt/imports.h> #ifdef USE_EXSLT #include <libexslt/exslt.h> #endif #ifdef MEMWATCH #include "memwatch.h" #endif #include "rb_utils.h" #include "parser.h" #include "parameters.h" #include "extfunc.h" -#define RUBY_XSLT_VERSION "0.9.6" -#define RUBY_XSLT_VERNUM 096 +#define RUBY_XSLT_VERSION "0.9.7" +#define RUBY_XSLT_VERNUM 097 #define RUBY_XSLT_XSLSRC_TYPE_NULL 0 #define RUBY_XSLT_XSLSRC_TYPE_STR 1 #define RUBY_XSLT_XSLSRC_TYPE_FILE 2 #define RUBY_XSLT_XSLSRC_TYPE_REXML 4 #define RUBY_XSLT_XSLSRC_TYPE_SMART 8 #define RUBY_XSLT_XSLSRC_TYPE_PARSED 16 #define RUBY_XSLT_XMLSRC_TYPE_NULL 0 #define RUBY_XSLT_XMLSRC_TYPE_STR 1 #define RUBY_XSLT_XMLSRC_TYPE_FILE 2 #define RUBY_XSLT_XMLSRC_TYPE_REXML 4 #define RUBY_XSLT_XMLSRC_TYPE_SMART 8 #define RUBY_XSLT_XMLSRC_TYPE_PARSED 16 RUBY_EXTERN VALUE eXSLTError; RUBY_EXTERN VALUE eXSLTParsingError; RUBY_EXTERN VALUE eXSLTTransformationError; typedef struct RbTxslt { int iXmlType; VALUE xXmlData; VALUE oXmlObject; VALUE xXmlString; xmlDocPtr tXMLDocument; int iXslType; VALUE xXslData; VALUE oXslObject; VALUE xXslString; xsltStylesheetPtr tParsedXslt; int iXmlResultType; VALUE xXmlResultCache; VALUE pxParams; int iNbParams; } RbTxslt; #endif
glejeune/ruby-xslt
4837eee958bc2ed2d7f58ea7af075c115cfe3acb
Bug correction : Issue #1
diff --git a/.gitignore b/.gitignore index 0be9aa0..35645cd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,23 +1,24 @@ ## MAC OS .DS_Store ## TEXTMATE *.tmproj tmtags ## EMACS *~ \#* .\#* ## VIM *.swp ## PROJECT::GENERAL coverage rdoc pkg ## PROJECT::SPECIFIC ext/xslt_lib/Makefile ext/xslt_lib/mkmf.log +examples \ No newline at end of file diff --git a/ext/xslt_lib/parameters.c b/ext/xslt_lib/parameters.c index 828ec96..5cb2693 100644 --- a/ext/xslt_lib/parameters.c +++ b/ext/xslt_lib/parameters.c @@ -1,59 +1,59 @@ /** * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "xslt.h" /** * parameters support, patch from : * * Eustáquio "TaQ" Rangel * [email protected] * http://beam.to/taq * */ VALUE each_pair( VALUE obj ) { return rb_funcall( obj, rb_intern("each"), 0, 0 ); } VALUE process_pair( VALUE pair, VALUE rbparams ) { VALUE key, value; // Thx to alex__ int count = FIX2INT( rb_funcall( rbparams, rb_intern("size"), 0, 0 ) ); // static int count = 0; char *xValue = NULL; Check_Type( pair, T_ARRAY ); key = RARRAY_PTR(pair)[0]; - value = RARRAY_PTR(pair)[1]; + value = rb_obj_clone( RARRAY_PTR(pair)[1] ); Check_Type( key, T_STRING ); Check_Type( value, T_STRING ); xValue = STR2CSTR( value ); if( xValue[0] != '\'' && xValue[strlen( xValue ) - 1] != '\'' ) { value = rb_str_concat( value, rb_str_new2( "'" ) ); value = rb_str_concat( rb_str_new2( "'" ), value ); } rb_ary_store( rbparams, count, key ); rb_ary_store( rbparams, count + 1, value ); count += 2; return Qnil; } diff --git a/ruby-xslt.gemspec b/ruby-xslt.gemspec index 01f97fd..a767b84 100644 --- a/ruby-xslt.gemspec +++ b/ruby-xslt.gemspec @@ -1,66 +1,77 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{ruby-xslt} s.version = "0.9.7" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Gregoire Lejeune"] - s.date = %q{2010-05-21} + s.date = %q{2010-05-22} s.description = %q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>} s.email = %q{[email protected]} s.extensions = ["ext/xslt_lib/extconf.rb"] s.extra_rdoc_files = [ "ChangeLog", - "README" + "README.rdoc" ] s.files = [ ".gitignore", "AUTHORS", "COPYING", "ChangeLog", - "README", + "README.rdoc", "Rakefile", "VERSION", "ext/xslt_lib/extconf.rb", "ext/xslt_lib/extfunc.c", "ext/xslt_lib/extfunc.h", "ext/xslt_lib/parameters.c", "ext/xslt_lib/parameters.h", "ext/xslt_lib/parser.c", "ext/xslt_lib/parser.h", "ext/xslt_lib/rb_utils.c", "ext/xslt_lib/rb_utils.h", "ext/xslt_lib/xslt.h", "ext/xslt_lib/xslt_lib.c", "lib/xml/xslt.rb", + "ruby-xslt.gemspec", "setup.rb", "test/subdir/result.xsl", "test/subdir/test.xsl", "test/t.xml", "test/t.xsl", "test/test.rb" ] s.homepage = %q{http://github.com/glejeune/ruby-xslt} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.7} s.summary = %q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>} s.test_files = [ - "test/test.rb" + "test/test.rb", + "examples/bug.rb", + "examples/fuzface.rb", + "examples/fuzface_data.rb", + "examples/fuzface_error.rb", + "examples/fuzface_REXML.rb", + "examples/fuzface_to_s.rb", + "examples/fuzface_XML-Simple.rb", + "examples/info.rb", + "examples/test_functions.rb", + "examples/test_parameters.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
glejeune/ruby-xslt
e0391158e9b9f0cba9d3ce579754d64647a632b2
Compatibility with ruby 1.8 and 1.9
diff --git a/.gitignore b/.gitignore index c1e0daf..0be9aa0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,23 @@ ## MAC OS .DS_Store ## TEXTMATE *.tmproj tmtags ## EMACS *~ \#* .\#* ## VIM *.swp ## PROJECT::GENERAL coverage rdoc pkg ## PROJECT::SPECIFIC +ext/xslt_lib/Makefile +ext/xslt_lib/mkmf.log diff --git a/ext/xslt_lib/extconf.h b/ext/xslt_lib/extconf.h deleted file mode 100644 index cda0cc8..0000000 --- a/ext/xslt_lib/extconf.h +++ /dev/null @@ -1,3 +0,0 @@ -#ifndef EXTCONF_H -#define EXTCONF_H -#endif diff --git a/ext/xslt_lib/extconf.rb b/ext/xslt_lib/extconf.rb index e3a8c79..fb4bf5b 100644 --- a/ext/xslt_lib/extconf.rb +++ b/ext/xslt_lib/extconf.rb @@ -1,57 +1,58 @@ #!/usr/bin/ruby -w # See the LICENSE file for copyright and distribution information require "mkmf" def help print <<HELP "extconf.rb" configures this package to adapt to many kinds of systems. Usage: ruby extconf.rb [OPTION]... Configuration: --help display this help and exit --with-xslt-lib=PATH --with-xslt-include=PATH --with-xslt-dir=PATH specify the directory name for the libxslt include files and/or library --disable-error-handler disables the new error handler --disable-exslt disables libexslt support <http://exslt.org/> HELP end if ARGV.include?( "--help" ) or ARGV.include?( "-h" ) help() exit 0 end if enable_config("error-handler", true) $CFLAGS += " -DUSE_ERROR_HANDLER" end #$LIBPATH.push(Config::CONFIG['libdir']) def crash(str) printf(" extconf failure: %s\n", str) exit 1 end dir_config( 'xml2' ) dir_config( 'xslt' ) have_library "xml2", "xmlParseDoc" || crash("need libxml2") have_library "xslt", "xsltParseStylesheetFile" || crash("need libxslt") +have_header "rubyio.h" if enable_config("exslt", true) have_library "exslt", "exsltRegisterAll" $CFLAGS += " -DUSE_EXSLT" end $CFLAGS = '-g -Wall ' + `xml2-config --cflags`.chomp + " " + `xslt-config --cflags`.chomp + " " + $CFLAGS create_header() create_makefile("xml/xslt_lib") diff --git a/ext/xslt_lib/rb_utils.h b/ext/xslt_lib/rb_utils.h index c00c6f8..a737b7e 100644 --- a/ext/xslt_lib/rb_utils.h +++ b/ext/xslt_lib/rb_utils.h @@ -1,34 +1,38 @@ /** * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Please see the LICENSE file for copyright and distribution information */ #ifndef __RUBY_RB_UTILS_H__ #define __RUBY_RB_UTILS_H__ #include <ruby.h> -#include <ruby/io.h> +#if defined(HAVE_RUBYIO_H) + #include <rubyio.h> +#else + #include <ruby/io.h> +#endif #include <stdio.h> #include <string.h> #include <sys/stat.h> char * getRubyObjectName( VALUE ); int isFile( const char *filename ); #endif diff --git a/ext/xslt_lib/xslt.h b/ext/xslt_lib/xslt.h index 30819ba..7128630 100644 --- a/ext/xslt_lib/xslt.h +++ b/ext/xslt_lib/xslt.h @@ -1,98 +1,102 @@ /** * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Please see the LICENSE file for copyright and distribution information */ #ifndef __RUBY_XSLT_H__ #define __RUBY_XSLT_H__ #include <ruby.h> -#include <ruby/io.h> +#if defined(HAVE_RUBYIO_H) + #include <rubyio.h> +#else + #include <ruby/io.h> +#endif #include <string.h> #include <libxml/xmlmemory.h> #include <libxml/debugXML.h> #include <libxml/HTMLtree.h> #include <libxml/xmlIO.h> #include <libxml/xinclude.h> #include <libxml/catalog.h> #include <libxslt/extra.h> #include <libxslt/xslt.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> #include <libxslt/imports.h> #ifdef USE_EXSLT #include <libexslt/exslt.h> #endif #ifdef MEMWATCH #include "memwatch.h" #endif #include "rb_utils.h" #include "parser.h" #include "parameters.h" #include "extfunc.h" #define RUBY_XSLT_VERSION "0.9.6" #define RUBY_XSLT_VERNUM 096 #define RUBY_XSLT_XSLSRC_TYPE_NULL 0 #define RUBY_XSLT_XSLSRC_TYPE_STR 1 #define RUBY_XSLT_XSLSRC_TYPE_FILE 2 #define RUBY_XSLT_XSLSRC_TYPE_REXML 4 #define RUBY_XSLT_XSLSRC_TYPE_SMART 8 #define RUBY_XSLT_XSLSRC_TYPE_PARSED 16 #define RUBY_XSLT_XMLSRC_TYPE_NULL 0 #define RUBY_XSLT_XMLSRC_TYPE_STR 1 #define RUBY_XSLT_XMLSRC_TYPE_FILE 2 #define RUBY_XSLT_XMLSRC_TYPE_REXML 4 #define RUBY_XSLT_XMLSRC_TYPE_SMART 8 #define RUBY_XSLT_XMLSRC_TYPE_PARSED 16 RUBY_EXTERN VALUE eXSLTError; RUBY_EXTERN VALUE eXSLTParsingError; RUBY_EXTERN VALUE eXSLTTransformationError; typedef struct RbTxslt { int iXmlType; VALUE xXmlData; VALUE oXmlObject; VALUE xXmlString; xmlDocPtr tXMLDocument; int iXslType; VALUE xXslData; VALUE oXslObject; VALUE xXslString; xsltStylesheetPtr tParsedXslt; int iXmlResultType; VALUE xXmlResultCache; VALUE pxParams; int iNbParams; } RbTxslt; #endif diff --git a/ruby-xslt.gemspec b/ruby-xslt.gemspec new file mode 100644 index 0000000..01f97fd --- /dev/null +++ b/ruby-xslt.gemspec @@ -0,0 +1,66 @@ +# Generated by jeweler +# DO NOT EDIT THIS FILE DIRECTLY +# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{ruby-xslt} + s.version = "0.9.7" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["Gregoire Lejeune"] + s.date = %q{2010-05-21} + s.description = %q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>} + s.email = %q{[email protected]} + s.extensions = ["ext/xslt_lib/extconf.rb"] + s.extra_rdoc_files = [ + "ChangeLog", + "README" + ] + s.files = [ + ".gitignore", + "AUTHORS", + "COPYING", + "ChangeLog", + "README", + "Rakefile", + "VERSION", + "ext/xslt_lib/extconf.rb", + "ext/xslt_lib/extfunc.c", + "ext/xslt_lib/extfunc.h", + "ext/xslt_lib/parameters.c", + "ext/xslt_lib/parameters.h", + "ext/xslt_lib/parser.c", + "ext/xslt_lib/parser.h", + "ext/xslt_lib/rb_utils.c", + "ext/xslt_lib/rb_utils.h", + "ext/xslt_lib/xslt.h", + "ext/xslt_lib/xslt_lib.c", + "lib/xml/xslt.rb", + "setup.rb", + "test/subdir/result.xsl", + "test/subdir/test.xsl", + "test/t.xml", + "test/t.xsl", + "test/test.rb" + ] + s.homepage = %q{http://github.com/glejeune/ruby-xslt} + s.rdoc_options = ["--charset=UTF-8"] + s.require_paths = ["lib"] + s.rubygems_version = %q{1.3.7} + s.summary = %q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/>} + s.test_files = [ + "test/test.rb" + ] + + if s.respond_to? :specification_version then + current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION + s.specification_version = 3 + + if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then + else + end + else + end +end +
glejeune/ruby-xslt
638281a728bac0cd3a14c97feb87dfa4e68d72cf
Remove unnecessary files and add Rakefile (using Jeweler)
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c1e0daf --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +## MAC OS +.DS_Store + +## TEXTMATE +*.tmproj +tmtags + +## EMACS +*~ +\#* +.\#* + +## VIM +*.swp + +## PROJECT::GENERAL +coverage +rdoc +pkg + +## PROJECT::SPECIFIC diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..4198ce2 --- /dev/null +++ b/Rakefile @@ -0,0 +1,52 @@ +require 'rubygems' +require 'rake' + +begin + require 'jeweler' + Jeweler::Tasks.new do |gem| + gem.name = "ruby-xslt" + gem.summary = %Q{Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/> } + gem.description = gem.summary + gem.email = "[email protected]" + gem.homepage = "http://github.com/glejeune/ruby-xslt" + gem.authors = ["Gregoire Lejeune"] + gem.extensions = FileList["ext/**/extconf.rb"].to_a + end + Jeweler::GemcutterTasks.new +rescue LoadError + puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" +end + +require 'rake/testtask' +Rake::TestTask.new(:test) do |test| + test.libs << 'lib' << 'test' + test.pattern = 'test/**/test_*.rb' + test.verbose = true +end + +begin + require 'rcov/rcovtask' + Rcov::RcovTask.new do |test| + test.libs << 'test' + test.pattern = 'test/**/test_*.rb' + test.verbose = true + end +rescue LoadError + task :rcov do + abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov" + end +end + +task :test => :check_dependencies + +task :default => :test + +require 'rake/rdoctask' +Rake::RDocTask.new do |rdoc| + version = File.exist?('VERSION') ? File.read('VERSION') : "" + + rdoc.rdoc_dir = 'rdoc' + rdoc.title = "syncftp #{version}" + rdoc.rdoc_files.include('README*') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/VERSION b/VERSION index 77d6f4c..c81aa44 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.0 +0.9.7 diff --git a/ext/xslt_lib/Makefile b/ext/xslt_lib/Makefile deleted file mode 100644 index e7fd9a0..0000000 --- a/ext/xslt_lib/Makefile +++ /dev/null @@ -1,181 +0,0 @@ - -SHELL = /bin/sh - -#### Start of system configuration section. #### - -srcdir = . -topdir = /usr/local/include/ruby-1.9.1 -hdrdir = /usr/local/include/ruby-1.9.1 -arch_hdrdir = /usr/local/include/ruby-1.9.1/$(arch) -VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby -prefix = $(DESTDIR)/usr/local -exec_prefix = $(prefix) -vendorhdrdir = $(rubyhdrdir)/vendor_ruby -sitehdrdir = $(rubyhdrdir)/site_ruby -rubyhdrdir = $(includedir)/$(RUBY_INSTALL_NAME)-$(ruby_version) -vendordir = $(libdir)/$(RUBY_INSTALL_NAME)/vendor_ruby -sitedir = $(libdir)/$(RUBY_INSTALL_NAME)/site_ruby -mandir = $(datarootdir)/man -localedir = $(datarootdir)/locale -libdir = $(exec_prefix)/lib -psdir = $(docdir) -pdfdir = $(docdir) -dvidir = $(docdir) -htmldir = $(docdir) -infodir = $(datarootdir)/info -docdir = $(datarootdir)/doc/$(PACKAGE) -oldincludedir = $(DESTDIR)/usr/include -includedir = $(prefix)/include -localstatedir = $(prefix)/var -sharedstatedir = $(prefix)/com -sysconfdir = $(prefix)/etc -datadir = $(datarootdir) -datarootdir = $(prefix)/share -libexecdir = $(exec_prefix)/libexec -sbindir = $(exec_prefix)/sbin -bindir = $(exec_prefix)/bin -rubylibdir = $(libdir)/$(ruby_install_name)/$(ruby_version) -archdir = $(rubylibdir)/$(arch) -sitelibdir = $(sitedir)/$(ruby_version) -sitearchdir = $(sitelibdir)/$(sitearch) -vendorlibdir = $(vendordir)/$(ruby_version) -vendorarchdir = $(vendorlibdir)/$(sitearch) - -CC = gcc -CXX = g++ -LIBRUBY = $(LIBRUBY_A) -LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a -LIBRUBYARG_SHARED = -Wl,-R -Wl,$(libdir) -L$(libdir) -l$(RUBY_SO_NAME) -LIBRUBYARG_STATIC = -Wl,-R -Wl,$(libdir) -L$(libdir) -l$(RUBY_SO_NAME)-static -OUTFLAG = -o -COUTFLAG = -o - -RUBY_EXTCONF_H = extconf.h -cflags = $(optflags) $(debugflags) $(warnflags) -optflags = -O2 -debugflags = -g -warnflags = -Wall -Wno-parentheses -CFLAGS = -fPIC -g -Wall -I/usr/include/libxml2 -I/usr/include/libxml2 $(cflags) -DUSE_ERROR_HANDLER -DUSE_EXSLT -INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) -DEFS = -D_FILE_OFFSET_BITS=64 -CPPFLAGS = -DRUBY_EXTCONF_H=\"$(RUBY_EXTCONF_H)\" $(DEFS) $(cppflags) -CXXFLAGS = $(CFLAGS) $(cxxflags) -ldflags = -L. -rdynamic -Wl,-export-dynamic -dldflags = -archflag = -DLDFLAGS = $(ldflags) $(dldflags) $(archflag) -LDSHARED = $(CC) -shared -LDSHAREDXX = $(CXX) -shared -AR = ar -EXEEXT = - -RUBY_INSTALL_NAME = ruby -RUBY_SO_NAME = ruby -arch = i686-linux -sitearch = i686-linux -ruby_version = 1.9.1 -ruby = /usr/local/bin/ruby -RUBY = $(ruby) -RM = rm -f -RM_RF = $(RUBY) -run -e rm -- -rf -RMDIRS = $(RUBY) -run -e rmdir -- -p -MAKEDIRS = mkdir -p -INSTALL = /usr/bin/install -c -INSTALL_PROG = $(INSTALL) -m 0755 -INSTALL_DATA = $(INSTALL) -m 644 -COPY = cp - -#### End of system configuration section. #### - -preload = - -libpath = . $(libdir) -LIBPATH = -L. -L$(libdir) -Wl,-R$(libdir) -DEFFILE = - -CLEANFILES = mkmf.log -DISTCLEANFILES = -DISTCLEANDIRS = - -extout = -extout_prefix = -target_prefix = /xml -LOCAL_LIBS = -LIBS = -lexslt -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc -SRCS = extfunc.c parser.c xslt_lib.c rb_utils.c parameters.c -OBJS = extfunc.o parser.o xslt_lib.o rb_utils.o parameters.o -TARGET = xslt_lib -DLLIB = $(TARGET).so -EXTSTATIC = -STATIC_LIB = - -BINDIR = $(bindir) -RUBYCOMMONDIR = $(sitedir)$(target_prefix) -RUBYLIBDIR = /usr/local/lib/ruby/gems/1.9.1/gems/ruby-xslt-0.9.6/lib$(target_prefix) -RUBYARCHDIR = /usr/local/lib/ruby/gems/1.9.1/gems/ruby-xslt-0.9.6/lib$(target_prefix) -HDRDIR = $(rubyhdrdir)/ruby$(target_prefix) -ARCHHDRDIR = $(rubyhdrdir)/$(arch)/ruby$(target_prefix) - -TARGET_SO = $(DLLIB) -CLEANLIBS = $(TARGET).so -CLEANOBJS = *.o *.bak - -all: $(DLLIB) -static: $(STATIC_LIB) - -clean-rb-default:: -clean-rb:: -clean-so:: -clean: clean-so clean-rb-default clean-rb - @-$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) - -distclean-rb-default:: -distclean-rb:: -distclean-so:: -distclean: clean distclean-so distclean-rb-default distclean-rb - @-$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log - @-$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES) - @-$(RMDIRS) $(DISTCLEANDIRS) - -realclean: distclean -install: install-so install-rb - -install-so: $(RUBYARCHDIR) -install-so: $(RUBYARCHDIR)/$(DLLIB) -$(RUBYARCHDIR)/$(DLLIB): $(DLLIB) - $(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR) -install-rb: pre-install-rb install-rb-default -install-rb-default: pre-install-rb-default -pre-install-rb: Makefile -pre-install-rb-default: Makefile -$(RUBYARCHDIR): - $(MAKEDIRS) $@ - -site-install: site-install-so site-install-rb -site-install-so: install-so -site-install-rb: install-rb - -.SUFFIXES: .c .m .cc .cxx .cpp .C .o - -.cc.o: - $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< - -.cxx.o: - $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< - -.cpp.o: - $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< - -.C.o: - $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< - -.c.o: - $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $< - -$(DLLIB): $(OBJS) Makefile - @-$(RM) $(@) - $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS) - - - -$(OBJS): $(hdrdir)/ruby.h $(hdrdir)/ruby/defines.h $(arch_hdrdir)/ruby/config.h $(RUBY_EXTCONF_H) diff --git a/ext/xslt_lib/gem_make.out b/ext/xslt_lib/gem_make.out deleted file mode 100644 index d4254b3..0000000 --- a/ext/xslt_lib/gem_make.out +++ /dev/null @@ -1,19 +0,0 @@ -/usr/local/bin/ruby extconf.rb install ruby-xslt -checking for xmlParseDoc() in -lxml2... yes -checking for xsltParseStylesheetFile() in -lxslt... yes -checking for exsltRegisterAll() in -lexslt... yes -creating extconf.h -creating Makefile - -make -gcc -I. -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -DRUBY_EXTCONF_H=\"extconf.h\" -D_FILE_OFFSET_BITS=64 -fPIC -g -Wall -I/usr/include/libxml2 -I/usr/include/libxml2 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER -DUSE_EXSLT -o extfunc.o -c extfunc.c -In file included from xslt.h:25, - from extfunc.c:19: -/usr/local/include/ruby-1.9.1/ruby/backward/rubyio.h:2:2: warning: #warning use "ruby/io.h" instead of "rubyio.h" -In file included from rb_utils.h:25, - from xslt.h:51, - from extfunc.c:19: -/usr/local/include/ruby-1.9.1/ruby/backward/rubyio.h:2:2: warning: #warning use "ruby/io.h" instead of "rubyio.h" -extfunc.c: In function ‘value2xpathObj’: -extfunc.c:141: error: ‘struct RArray’ has no member named ‘len’ -make: *** [extfunc.o] Error 1 diff --git a/ext/xslt_lib/mkmf.log b/ext/xslt_lib/mkmf.log deleted file mode 100644 index 5b7a17f..0000000 --- a/ext/xslt_lib/mkmf.log +++ /dev/null @@ -1,98 +0,0 @@ -have_library: checking for xmlParseDoc() in -lxml2... -------------------- yes - -"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lpthread -lrt -ldl -lcrypt -lm -lc" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: int main() {return 0;} -/* end */ - -"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" -conftest.c: In function ‘t’: -conftest.c:5: error: ‘xmlParseDoc’ undeclared (first use in this function) -conftest.c:5: error: (Each undeclared identifier is reported only once -conftest.c:5: error: for each function it appears in.) -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: /*top*/ -4: int main() {return 0;} -5: int t() { void ((*volatile p)()); p = (void ((*)()))xmlParseDoc; return 0; } -/* end */ - -"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" -conftest.c: In function ‘t’: -conftest.c:5: warning: implicit declaration of function ‘xmlParseDoc’ -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: /*top*/ -4: int main() {return 0;} -5: int t() { xmlParseDoc(); return 0; } -/* end */ - --------------------- - -have_library: checking for xsltParseStylesheetFile() in -lxslt... -------------------- yes - -"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -lxml2 -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" -conftest.c: In function ‘t’: -conftest.c:5: error: ‘xsltParseStylesheetFile’ undeclared (first use in this function) -conftest.c:5: error: (Each undeclared identifier is reported only once -conftest.c:5: error: for each function it appears in.) -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: /*top*/ -4: int main() {return 0;} -5: int t() { void ((*volatile p)()); p = (void ((*)()))xsltParseStylesheetFile; return 0; } -/* end */ - -"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -lxml2 -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" -conftest.c: In function ‘t’: -conftest.c:5: warning: implicit declaration of function ‘xsltParseStylesheetFile’ -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: /*top*/ -4: int main() {return 0;} -5: int t() { xsltParseStylesheetFile(); return 0; } -/* end */ - --------------------- - -have_library: checking for exsltRegisterAll() in -lexslt... -------------------- yes - -"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -lxslt -lxml2 -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lexslt -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" -conftest.c: In function ‘t’: -conftest.c:5: error: ‘exsltRegisterAll’ undeclared (first use in this function) -conftest.c:5: error: (Each undeclared identifier is reported only once -conftest.c:5: error: for each function it appears in.) -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: /*top*/ -4: int main() {return 0;} -5: int t() { void ((*volatile p)()); p = (void ((*)()))exsltRegisterAll; return 0; } -/* end */ - -"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -lxslt -lxml2 -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lexslt -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" -conftest.c: In function ‘t’: -conftest.c:5: warning: implicit declaration of function ‘exsltRegisterAll’ -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: /*top*/ -4: int main() {return 0;} -5: int t() { exsltRegisterAll(); return 0; } -/* end */ - --------------------- -
glejeune/ruby-xslt
061c20db978cc5e4e4532a61e10550584f0937c7
Version bump to 0.0.0
diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..77d6f4c --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.0.0
glejeune/ruby-xslt
a3caf77ec648dc001028137ecf9633eeb53e7448
Ruby 1.9 compatible branch of ruby-xslt.
diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..97fe075 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,32 @@ += Authors + +Gregoire Lejeune <gregoire dot lejeune at free dot fr> +* Maintener + +Eustáquio "TaQ" Rangel <eustaquiorangel at yahoo dot com> +* Add parameters support + +Brendan Taylor <whateley at gmail dot com> +* Add external function support +* Add media_type function +* Changes to the way XSLT files are loaded, so that we can keep their base URI straight + +<kiyoya at gmail dot com> +* Add definitions for some error classes and sets libxml error function + +Pau Garcia i Quiles <pgquiles at elpauer dot org> +* gemspec + +Stéphane Mariel <smariel at rift dot fr> +* Bugfix in extfunc.c + +Tom <[email protected]> +* Found and patched some serious memory leaks + +== Thanks to : + +knu <knu at freebsd dot org> for FreeBSD port (see http://www.freshports.org/textproc/ruby-xslt/) + +Robert Shaw <rshaw at opendarwin dot org> for opendarwin port (see http://rb-xslt.darwinports.com/) + +Alexis Bernard aka alex__ for testing diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d60c31a --- /dev/null +++ b/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library General +Public License instead of this License. diff --git a/ChangeLog b/ChangeLog new file mode 100644 index 0000000..edaedfd --- /dev/null +++ b/ChangeLog @@ -0,0 +1,81 @@ +0.9.6 : +* "found and patched some serious memory leaks" (thanks to Tom) + +0.9.5 : +* Bugfix in extconf.c (thanks to Stephane Mariel) + +0.9.4 : +* ... + +0.9.3 : +* Due to recent changes in Gentoo Linux's install system, ruby-xslt no longer installs correctly. Brendan fixed this. +* Cleaned up extconf.rb +* Removed unused debugging code (memwatch) +* Moved some things out of C into Ruby +* Made error handling much more useful +* Added some unit tests + +0.9.2 : +* Changes to the way XSLT files are loaded, so that we can keep their base URI straight - Sorry Brendan !!! +* Major corrections + +0.9.1 : +* Add XML/Smart support. XML/Simple support is still available +* Add REXML support. +* Add error classes and sets libxml error function +* Move samples scripts from tests to examples and add unit tests +* Changes to the way XSLT files are loaded, so that we can keep their base URI straight +* Major bugs corrections + +0.8.2 : +* Configuration changes: + + ruby extconf.rb --enable-exslt (on by default) : enables libexslt support <http://exslt.org/> + + ruby extconf.rb --enable-error-handler (off by default) : enables a VERY crude error handler. error messages are appended to the class variable XML::XSLT and can be accessed with the class method XML::XSLT.errors (not very good, but better than trapping $stderr) + +* API changes: + + XML::XSLT.new.extFunction("do-this", "http://fake.none", MyClass, "do_this") + + is now + + XML::XSLT.extFunction("do-this", "http://fake.none", MyClass) + + The callback function will now call the function with the same name as the function that was called. One (possibly confusing) exception is that when you register a function with a '-' in it the name of the ruby method called has the '-'s replaced with '_'s. This is because there seems to be a convention of naming XPath functions with hyphens and they're illegal in Ruby method names. + + The big stability change is that the external function table is now stored in a hash of hashes on the XSLT class object. (rather than a global xmlHash) It makes more sense to make it a property of the class and the hashes are an easy way to implement it. + + The type of objects that are passed to and returned from extension functions has changed to be more sane. REXML is now required to convert an xmlXPathObj to and from a VALUE; nodesets are passed to Ruby as an array of REXML::Elements and REXML::Elements / REXML::Documents returned from Ruby get turned into nodesets. + +* Potential problems: + + xsltCleanupGlobals() shouldn't be called until we're done with whatever functions that are registered (probably when our program doesn't need ruby-xslt at all any more). + +0.8.1 : +* Major bug correction + +0.8.0 : +* Major bug correction in parameters support + +0.7.0 : +* Add external functions support + +0.6.0 : +* Major bug correction + +0.5.0 : +* Add XML/Simple support +* Add parameters support + +0.4.0 : +* Add cache + +0.3.0 : +* Major bug correction + +0.2.0 : +* Major bug correction + +0.1.0 : +* Initial version diff --git a/README b/README new file mode 100644 index 0000000..fb2761b --- /dev/null +++ b/README @@ -0,0 +1,132 @@ += Ruby/XSLT + +== About + +Ruby/XSLT is a simple XSLT class based on libxml <http://xmlsoft.org/> and libxslt <http://xmlsoft.org/XSLT/> + +== Licence + +Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Gregoire Lejeune <gregoire dot lejeune at free dot fr> + +Ruby/XSLT is freely distributable according to the terms of the +GNU General Public License (see the file 'COPYING'). + +This program is distributed without any warranty. See the file +'COPYING' for details. + +=== CVS access +The CVS repository is available at rubyforge.org[http://rubyforge.org/projects/ruby-asp]. You can browse[http://rubyforge.org/cgi-bin/viewcvs.cgi/ruby-xslt/?cvsroot=ruby-asp] it or access it via anonymous access : + + cvs -d :pserver:[email protected]:/var/cvs/ruby-asp login + cvs -d :pserver:[email protected]:/var/cvs/ruby-asp checkout ruby-xslt + +See this page[http://rubyforge.org/scm/?group_id=423] for more informations + +== INSTALLATION + + sudo gem install ruby-xslt + +or + + ruby extconf.rb # see CONFIGURATION for more options + make + make test + make doc + sudo make install + +=== CONFIGURATION + + --help display this help and exit + + --with-xslt-lib=PATH + --with-xslt-include=PATH + --with-xslt-dir=PATH specify the directory name for the libxslt include + files and/or library + + --disable-error-handler disables the new error handler + + --disable-exslt disables libexslt support <http://exslt.org/> + + +== EXAMPLES + +=== Simple example + require 'xml/xslt' + + xslt = XML::XSLT.new() + xslt.xml = "text.xml" + xslt.xsl = "test.xsl" + + out = xslt.serve() + print out; + +=== REXML support + require 'rexml/document' + require 'xml/xslt' + + xslt = XML::XSLT.new() + + xslt.xml = REXML::Document.new File.read( "test.xml" ) + xslt.xsl = REXML::Document.new File.read( "test.xsl" ) + + out = xslt.serve() + print out; + +=== XML::Smart support + require 'xml/smart' + require 'xml/xslt' + + xslt = XML::XSLT.new() + + xslt.xml = XML::Smart.open( "test.xml" ) + xslt.xsl = XML::Smart.open( "test.xsl" ) + + out = xslt.serve() + print out; + +=== Parameters support + require "xml/xslt" + + xslt = XML::XSLT.new() + xslt.xsl = "parameter.xsl" + xslt.xml = "test.xml" + xslt.parameters = { "p1" => "the first parameter ...", + "p2" => "'and the second one!'" } + xslt.save("test1.html") + + xslt.parameters = { "p1" => "Ruby...", + "p2" => "'...is cool !'" } + xslt.save("test2.html") + +=== External functions support + require "xml/xslt" + + xslt = XML::XSLT.new() + xslt.xsl = "functions.xsl" + xslt.xml = "test.xml" + + XML::XSLT.registerExtFunc("http://test.none", "round-trip") do |arg| + arg + end + + XML::XSLT.registerExtFunc("http://test.none", "type") do |arg| + arg.class.to_s + end + + print xslt.serve + +=== Error handling + + XML::XSLT.registerErrorHandler { |string| puts string } + + xslt = XML::XSLT.new + xslt.xml = "not xml" + +This fragment would print: + + Entity: line 1: + parser + error : + Start Tag expected, '<' not found + not xml + ^ diff --git a/ext/xslt_lib/Makefile b/ext/xslt_lib/Makefile new file mode 100644 index 0000000..e7fd9a0 --- /dev/null +++ b/ext/xslt_lib/Makefile @@ -0,0 +1,181 @@ + +SHELL = /bin/sh + +#### Start of system configuration section. #### + +srcdir = . +topdir = /usr/local/include/ruby-1.9.1 +hdrdir = /usr/local/include/ruby-1.9.1 +arch_hdrdir = /usr/local/include/ruby-1.9.1/$(arch) +VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby +prefix = $(DESTDIR)/usr/local +exec_prefix = $(prefix) +vendorhdrdir = $(rubyhdrdir)/vendor_ruby +sitehdrdir = $(rubyhdrdir)/site_ruby +rubyhdrdir = $(includedir)/$(RUBY_INSTALL_NAME)-$(ruby_version) +vendordir = $(libdir)/$(RUBY_INSTALL_NAME)/vendor_ruby +sitedir = $(libdir)/$(RUBY_INSTALL_NAME)/site_ruby +mandir = $(datarootdir)/man +localedir = $(datarootdir)/locale +libdir = $(exec_prefix)/lib +psdir = $(docdir) +pdfdir = $(docdir) +dvidir = $(docdir) +htmldir = $(docdir) +infodir = $(datarootdir)/info +docdir = $(datarootdir)/doc/$(PACKAGE) +oldincludedir = $(DESTDIR)/usr/include +includedir = $(prefix)/include +localstatedir = $(prefix)/var +sharedstatedir = $(prefix)/com +sysconfdir = $(prefix)/etc +datadir = $(datarootdir) +datarootdir = $(prefix)/share +libexecdir = $(exec_prefix)/libexec +sbindir = $(exec_prefix)/sbin +bindir = $(exec_prefix)/bin +rubylibdir = $(libdir)/$(ruby_install_name)/$(ruby_version) +archdir = $(rubylibdir)/$(arch) +sitelibdir = $(sitedir)/$(ruby_version) +sitearchdir = $(sitelibdir)/$(sitearch) +vendorlibdir = $(vendordir)/$(ruby_version) +vendorarchdir = $(vendorlibdir)/$(sitearch) + +CC = gcc +CXX = g++ +LIBRUBY = $(LIBRUBY_A) +LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a +LIBRUBYARG_SHARED = -Wl,-R -Wl,$(libdir) -L$(libdir) -l$(RUBY_SO_NAME) +LIBRUBYARG_STATIC = -Wl,-R -Wl,$(libdir) -L$(libdir) -l$(RUBY_SO_NAME)-static +OUTFLAG = -o +COUTFLAG = -o + +RUBY_EXTCONF_H = extconf.h +cflags = $(optflags) $(debugflags) $(warnflags) +optflags = -O2 +debugflags = -g +warnflags = -Wall -Wno-parentheses +CFLAGS = -fPIC -g -Wall -I/usr/include/libxml2 -I/usr/include/libxml2 $(cflags) -DUSE_ERROR_HANDLER -DUSE_EXSLT +INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir) +DEFS = -D_FILE_OFFSET_BITS=64 +CPPFLAGS = -DRUBY_EXTCONF_H=\"$(RUBY_EXTCONF_H)\" $(DEFS) $(cppflags) +CXXFLAGS = $(CFLAGS) $(cxxflags) +ldflags = -L. -rdynamic -Wl,-export-dynamic +dldflags = +archflag = +DLDFLAGS = $(ldflags) $(dldflags) $(archflag) +LDSHARED = $(CC) -shared +LDSHAREDXX = $(CXX) -shared +AR = ar +EXEEXT = + +RUBY_INSTALL_NAME = ruby +RUBY_SO_NAME = ruby +arch = i686-linux +sitearch = i686-linux +ruby_version = 1.9.1 +ruby = /usr/local/bin/ruby +RUBY = $(ruby) +RM = rm -f +RM_RF = $(RUBY) -run -e rm -- -rf +RMDIRS = $(RUBY) -run -e rmdir -- -p +MAKEDIRS = mkdir -p +INSTALL = /usr/bin/install -c +INSTALL_PROG = $(INSTALL) -m 0755 +INSTALL_DATA = $(INSTALL) -m 644 +COPY = cp + +#### End of system configuration section. #### + +preload = + +libpath = . $(libdir) +LIBPATH = -L. -L$(libdir) -Wl,-R$(libdir) +DEFFILE = + +CLEANFILES = mkmf.log +DISTCLEANFILES = +DISTCLEANDIRS = + +extout = +extout_prefix = +target_prefix = /xml +LOCAL_LIBS = +LIBS = -lexslt -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc +SRCS = extfunc.c parser.c xslt_lib.c rb_utils.c parameters.c +OBJS = extfunc.o parser.o xslt_lib.o rb_utils.o parameters.o +TARGET = xslt_lib +DLLIB = $(TARGET).so +EXTSTATIC = +STATIC_LIB = + +BINDIR = $(bindir) +RUBYCOMMONDIR = $(sitedir)$(target_prefix) +RUBYLIBDIR = /usr/local/lib/ruby/gems/1.9.1/gems/ruby-xslt-0.9.6/lib$(target_prefix) +RUBYARCHDIR = /usr/local/lib/ruby/gems/1.9.1/gems/ruby-xslt-0.9.6/lib$(target_prefix) +HDRDIR = $(rubyhdrdir)/ruby$(target_prefix) +ARCHHDRDIR = $(rubyhdrdir)/$(arch)/ruby$(target_prefix) + +TARGET_SO = $(DLLIB) +CLEANLIBS = $(TARGET).so +CLEANOBJS = *.o *.bak + +all: $(DLLIB) +static: $(STATIC_LIB) + +clean-rb-default:: +clean-rb:: +clean-so:: +clean: clean-so clean-rb-default clean-rb + @-$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) + +distclean-rb-default:: +distclean-rb:: +distclean-so:: +distclean: clean distclean-so distclean-rb-default distclean-rb + @-$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log + @-$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES) + @-$(RMDIRS) $(DISTCLEANDIRS) + +realclean: distclean +install: install-so install-rb + +install-so: $(RUBYARCHDIR) +install-so: $(RUBYARCHDIR)/$(DLLIB) +$(RUBYARCHDIR)/$(DLLIB): $(DLLIB) + $(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR) +install-rb: pre-install-rb install-rb-default +install-rb-default: pre-install-rb-default +pre-install-rb: Makefile +pre-install-rb-default: Makefile +$(RUBYARCHDIR): + $(MAKEDIRS) $@ + +site-install: site-install-so site-install-rb +site-install-so: install-so +site-install-rb: install-rb + +.SUFFIXES: .c .m .cc .cxx .cpp .C .o + +.cc.o: + $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< + +.cxx.o: + $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< + +.cpp.o: + $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< + +.C.o: + $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $< + +.c.o: + $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $< + +$(DLLIB): $(OBJS) Makefile + @-$(RM) $(@) + $(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS) + + + +$(OBJS): $(hdrdir)/ruby.h $(hdrdir)/ruby/defines.h $(arch_hdrdir)/ruby/config.h $(RUBY_EXTCONF_H) diff --git a/ext/xslt_lib/extconf.h b/ext/xslt_lib/extconf.h new file mode 100644 index 0000000..cda0cc8 --- /dev/null +++ b/ext/xslt_lib/extconf.h @@ -0,0 +1,3 @@ +#ifndef EXTCONF_H +#define EXTCONF_H +#endif diff --git a/ext/xslt_lib/extconf.rb b/ext/xslt_lib/extconf.rb new file mode 100644 index 0000000..e3a8c79 --- /dev/null +++ b/ext/xslt_lib/extconf.rb @@ -0,0 +1,57 @@ +#!/usr/bin/ruby -w +# See the LICENSE file for copyright and distribution information + +require "mkmf" + +def help + print <<HELP +"extconf.rb" configures this package to adapt to many kinds of systems. + +Usage: ruby extconf.rb [OPTION]... + +Configuration: + --help display this help and exit + + --with-xslt-lib=PATH + --with-xslt-include=PATH + --with-xslt-dir=PATH specify the directory name for the libxslt include + files and/or library + + --disable-error-handler disables the new error handler + + --disable-exslt disables libexslt support <http://exslt.org/> +HELP +end + +if ARGV.include?( "--help" ) or ARGV.include?( "-h" ) + help() + exit 0 +end + +if enable_config("error-handler", true) + $CFLAGS += " -DUSE_ERROR_HANDLER" +end + +#$LIBPATH.push(Config::CONFIG['libdir']) + +def crash(str) + printf(" extconf failure: %s\n", str) + exit 1 +end + +dir_config( 'xml2' ) +dir_config( 'xslt' ) + +have_library "xml2", "xmlParseDoc" || crash("need libxml2") +have_library "xslt", "xsltParseStylesheetFile" || crash("need libxslt") + +if enable_config("exslt", true) + have_library "exslt", "exsltRegisterAll" + $CFLAGS += " -DUSE_EXSLT" +end + +$CFLAGS = '-g -Wall ' + `xml2-config --cflags`.chomp + " " + `xslt-config --cflags`.chomp + " " + $CFLAGS + +create_header() +create_makefile("xml/xslt_lib") + diff --git a/ext/xslt_lib/extfunc.c b/ext/xslt_lib/extfunc.c new file mode 100644 index 0000000..613ccb8 --- /dev/null +++ b/ext/xslt_lib/extfunc.c @@ -0,0 +1,213 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "xslt.h" + +extern VALUE mXML; +extern VALUE cXSLT; + +/** + * external function support, patch from : + * + * Brendan Taylor + * [email protected] + * + */ + + +/* converts an xmlXPathObjectPtr to a Ruby VALUE + * number -> float + * boolean -> boolean + * string -> string + * nodeset -> an array of REXML::Elements + */ +VALUE xpathObj2value(xmlXPathObjectPtr obj, xmlDocPtr doc) +{ + VALUE ret = Qnil; + + if (obj == NULL) { + return ret; + } + + switch (obj->type) { + case XPATH_NODESET: + rb_require("rexml/document"); + ret = rb_ary_new(); + + if ((obj->nodesetval != NULL) && (obj->nodesetval->nodeNr != 0)) { + xmlBufferPtr buff = xmlBufferCreate(); + xmlNodePtr node; + int i; + + // this assumes all the nodes are elements, which is a bad idea + for (i = 0; i < obj->nodesetval->nodeNr; i++) { + node = obj->nodesetval->nodeTab[i]; + + if( node->type == XML_ELEMENT_NODE ) { + xmlNodeDump(buff, doc, node, 0, 0); + + VALUE cREXML = rb_const_get(rb_cObject, rb_intern("REXML")); + VALUE cDocument = rb_const_get(cREXML, rb_intern("Document")); + VALUE rDocument = rb_funcall(cDocument, rb_intern("new"), 1,rb_str_new2((char *)buff->content)); + VALUE rElement = rb_funcall(rDocument, rb_intern("root"), 0); + + rb_ary_push(ret, rElement); + + // empty the buffer (xmlNodeDump appends rather than replaces) + xmlBufferEmpty(buff); + } else if ( node->type == XML_TEXT_NODE ) { + rb_ary_push(ret, rb_str_new2((char *)node->content)); + } else if ( node->type == XML_ATTRIBUTE_NODE ) { + // BUG: should ensure children is not null (shouldn't) + rb_ary_push(ret, rb_str_new2((char *)node->children->content)); + } else { + rb_warning( "Unsupported node type in node set: %d", node->type ); + } + } + xmlBufferFree(buff); + } + break; + case XPATH_BOOLEAN: + ret = obj->boolval ? Qtrue : Qfalse; + break; + case XPATH_NUMBER: + ret = rb_float_new(obj->floatval); + break; + case XPATH_STRING: + ret = rb_str_new2((char *) obj->stringval); + break; + /* these cases were in libxslt's python bindings, but i don't know what they are, so i'll leave them alone */ + case XPATH_XSLT_TREE: + case XPATH_POINT: + case XPATH_RANGE: + case XPATH_LOCATIONSET: + default: + rb_warning("xpathObj2value: can't convert XPath object type %d to Ruby object\n", obj->type ); + } + xmlXPathFreeObject(obj); + return ret; +} + +/* + * converts a Ruby VALUE to an xmlXPathObjectPtr + * boolean -> boolean + * number -> number + * string -> escaped string + * array -> array of parsed nodes + */ +xmlXPathObjectPtr value2xpathObj (VALUE val) { + xmlXPathObjectPtr ret = NULL; + + switch (TYPE(val)) { + case T_TRUE: + case T_FALSE: + ret = xmlXPathNewBoolean(RTEST(val)); + break; + case T_FIXNUM: + case T_FLOAT: + ret = xmlXPathNewFloat(NUM2DBL(val)); + break; + case T_STRING: + { + xmlChar *str; + + // we need the Strdup (this is the major bugfix for 0.8.1) + str = xmlStrdup((const xmlChar *) STR2CSTR(val)); + ret = xmlXPathWrapString(str); + } + break; + case T_NIL: + ret = xmlXPathNewNodeSet(NULL); + break; + case T_ARRAY: { + int i,j; + ret = xmlXPathNewNodeSet(NULL); + + for(i = RARRAY_LEN(val); i > 0; i--) { + xmlXPathObjectPtr obj = value2xpathObj( rb_ary_shift( val ) ); + if ((obj->nodesetval != NULL) && (obj->nodesetval->nodeNr != 0)) { + for(j = 0; j < obj->nodesetval->nodeNr; j++) { + xmlXPathNodeSetAdd( ret->nodesetval, obj->nodesetval->nodeTab[j] ); + } + } + } + break; } + case T_DATA: + case T_OBJECT: { + if( strcmp( getRubyObjectName( val ), "REXML::Document" ) == 0 || strcmp(getRubyObjectName( val ), "REXML::Element") == 0 ) { + + VALUE to_s = rb_funcall( val, rb_intern( "to_s" ), 0 ); + xmlDocPtr doc = xmlParseDoc((xmlChar *) STR2CSTR(to_s)); + + ret = xmlXPathNewNodeSet((xmlNode *)doc->children); + break; + } else if( strcmp( getRubyObjectName( val ), "REXML::Text" ) == 0 ) { + VALUE to_s = rb_funcall( val, rb_intern( "to_s" ), 0 ); + + xmlChar *str; + + str = xmlStrdup((const xmlChar *) STR2CSTR(to_s)); + ret = xmlXPathWrapString(str); + break; + } + // this drops through so i can reuse the error message + } + default: + rb_warning( "value2xpathObj: can't convert class %s to XPath object\n", getRubyObjectName(val)); + return NULL; + } + + return ret; +} + +/* + * chooses what registered function to call and calls it + */ +void xmlXPathFuncCallback( xmlXPathParserContextPtr ctxt, int nargs) { + VALUE result, arguments[nargs]; + VALUE ns_hash, func_hash, block; + const xmlChar *namespace, *name; + xmlXPathObjectPtr obj; + int i; + + if (ctxt == NULL || ctxt->context == NULL) + return; + + name = ctxt->context->function; + namespace = ctxt->context->functionURI; + + ns_hash = rb_cvar_get(cXSLT, rb_intern("@@extFunctions")); + + func_hash = rb_hash_aref(ns_hash, rb_str_new2((char *)namespace)); + + if(func_hash == Qnil) { + rb_warning( "xmlXPathFuncCallback: namespace %s not registered!\n", namespace ); + } + + block = rb_hash_aref(func_hash, rb_str_new2((char *)name)); + + for (i = nargs - 1; i >= 0; i--) { + obj = valuePop(ctxt); + arguments[i] = xpathObj2value(obj, ctxt->context->doc); + } + + result = rb_funcall2( block, rb_intern("call"), nargs, arguments); + + obj = value2xpathObj(result); + valuePush(ctxt, obj); +} diff --git a/ext/xslt_lib/extfunc.h b/ext/xslt_lib/extfunc.h new file mode 100644 index 0000000..c528c92 --- /dev/null +++ b/ext/xslt_lib/extfunc.h @@ -0,0 +1,26 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "xslt.h" + +#include <libxml/xpathInternals.h> +#include <libxslt/extensions.h> + +VALUE xpathObj2value( xmlXPathObjectPtr, xmlDocPtr ); +xmlXPathObjectPtr value2xpathObj( VALUE ); +void xmlXPathFuncCallback( xmlXPathParserContextPtr, int ); diff --git a/ext/xslt_lib/gem_make.out b/ext/xslt_lib/gem_make.out new file mode 100644 index 0000000..d4254b3 --- /dev/null +++ b/ext/xslt_lib/gem_make.out @@ -0,0 +1,19 @@ +/usr/local/bin/ruby extconf.rb install ruby-xslt +checking for xmlParseDoc() in -lxml2... yes +checking for xsltParseStylesheetFile() in -lxslt... yes +checking for exsltRegisterAll() in -lexslt... yes +creating extconf.h +creating Makefile + +make +gcc -I. -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -DRUBY_EXTCONF_H=\"extconf.h\" -D_FILE_OFFSET_BITS=64 -fPIC -g -Wall -I/usr/include/libxml2 -I/usr/include/libxml2 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER -DUSE_EXSLT -o extfunc.o -c extfunc.c +In file included from xslt.h:25, + from extfunc.c:19: +/usr/local/include/ruby-1.9.1/ruby/backward/rubyio.h:2:2: warning: #warning use "ruby/io.h" instead of "rubyio.h" +In file included from rb_utils.h:25, + from xslt.h:51, + from extfunc.c:19: +/usr/local/include/ruby-1.9.1/ruby/backward/rubyio.h:2:2: warning: #warning use "ruby/io.h" instead of "rubyio.h" +extfunc.c: In function ‘value2xpathObj’: +extfunc.c:141: error: ‘struct RArray’ has no member named ‘len’ +make: *** [extfunc.o] Error 1 diff --git a/ext/xslt_lib/mkmf.log b/ext/xslt_lib/mkmf.log new file mode 100644 index 0000000..5b7a17f --- /dev/null +++ b/ext/xslt_lib/mkmf.log @@ -0,0 +1,98 @@ +have_library: checking for xmlParseDoc() in -lxml2... -------------------- yes + +"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lpthread -lrt -ldl -lcrypt -lm -lc" +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: int main() {return 0;} +/* end */ + +"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" +conftest.c: In function ‘t’: +conftest.c:5: error: ‘xmlParseDoc’ undeclared (first use in this function) +conftest.c:5: error: (Each undeclared identifier is reported only once +conftest.c:5: error: for each function it appears in.) +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: /*top*/ +4: int main() {return 0;} +5: int t() { void ((*volatile p)()); p = (void ((*)()))xmlParseDoc; return 0; } +/* end */ + +"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" +conftest.c: In function ‘t’: +conftest.c:5: warning: implicit declaration of function ‘xmlParseDoc’ +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: /*top*/ +4: int main() {return 0;} +5: int t() { xmlParseDoc(); return 0; } +/* end */ + +-------------------- + +have_library: checking for xsltParseStylesheetFile() in -lxslt... -------------------- yes + +"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -lxml2 -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" +conftest.c: In function ‘t’: +conftest.c:5: error: ‘xsltParseStylesheetFile’ undeclared (first use in this function) +conftest.c:5: error: (Each undeclared identifier is reported only once +conftest.c:5: error: for each function it appears in.) +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: /*top*/ +4: int main() {return 0;} +5: int t() { void ((*volatile p)()); p = (void ((*)()))xsltParseStylesheetFile; return 0; } +/* end */ + +"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -lxml2 -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" +conftest.c: In function ‘t’: +conftest.c:5: warning: implicit declaration of function ‘xsltParseStylesheetFile’ +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: /*top*/ +4: int main() {return 0;} +5: int t() { xsltParseStylesheetFile(); return 0; } +/* end */ + +-------------------- + +have_library: checking for exsltRegisterAll() in -lexslt... -------------------- yes + +"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -lxslt -lxml2 -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lexslt -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" +conftest.c: In function ‘t’: +conftest.c:5: error: ‘exsltRegisterAll’ undeclared (first use in this function) +conftest.c:5: error: (Each undeclared identifier is reported only once +conftest.c:5: error: for each function it appears in.) +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: /*top*/ +4: int main() {return 0;} +5: int t() { void ((*volatile p)()); p = (void ((*)()))exsltRegisterAll; return 0; } +/* end */ + +"gcc -o conftest -I/usr/local/include/ruby-1.9.1/i686-linux -I/usr/local/include/ruby-1.9.1/ruby/backward -I/usr/local/include/ruby-1.9.1 -I. -D_FILE_OFFSET_BITS=64 -O2 -g -Wall -Wno-parentheses -DUSE_ERROR_HANDLER conftest.c -L. -L/usr/local/lib -Wl,-R/usr/local/lib -L. -rdynamic -Wl,-export-dynamic -lxslt -lxml2 -Wl,-R -Wl,/usr/local/lib -L/usr/local/lib -lruby-static -lexslt -lxslt -lxml2 -lpthread -lrt -ldl -lcrypt -lm -lc" +conftest.c: In function ‘t’: +conftest.c:5: warning: implicit declaration of function ‘exsltRegisterAll’ +checked program was: +/* begin */ +1: #include "ruby.h" +2: +3: /*top*/ +4: int main() {return 0;} +5: int t() { exsltRegisterAll(); return 0; } +/* end */ + +-------------------- + diff --git a/ext/xslt_lib/parameters.c b/ext/xslt_lib/parameters.c new file mode 100644 index 0000000..828ec96 --- /dev/null +++ b/ext/xslt_lib/parameters.c @@ -0,0 +1,59 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "xslt.h" + +/** + * parameters support, patch from : + * + * Eustáquio "TaQ" Rangel + * [email protected] + * http://beam.to/taq + * + */ +VALUE each_pair( VALUE obj ) { + return rb_funcall( obj, rb_intern("each"), 0, 0 ); +} + +VALUE process_pair( VALUE pair, VALUE rbparams ) { + VALUE key, value; + // Thx to alex__ + int count = FIX2INT( rb_funcall( rbparams, rb_intern("size"), 0, 0 ) ); + // static int count = 0; + char *xValue = NULL; + + Check_Type( pair, T_ARRAY ); + + key = RARRAY_PTR(pair)[0]; + value = RARRAY_PTR(pair)[1]; + + Check_Type( key, T_STRING ); + Check_Type( value, T_STRING ); + + xValue = STR2CSTR( value ); + if( xValue[0] != '\'' && xValue[strlen( xValue ) - 1] != '\'' ) { + value = rb_str_concat( value, rb_str_new2( "'" ) ); + value = rb_str_concat( rb_str_new2( "'" ), value ); + } + + rb_ary_store( rbparams, count, key ); + rb_ary_store( rbparams, count + 1, value ); + + count += 2; + return Qnil; +} diff --git a/ext/xslt_lib/parameters.h b/ext/xslt_lib/parameters.h new file mode 100644 index 0000000..f480135 --- /dev/null +++ b/ext/xslt_lib/parameters.h @@ -0,0 +1,20 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +VALUE each_pair( VALUE ); +VALUE process_pair( VALUE, VALUE ); diff --git a/ext/xslt_lib/parser.c b/ext/xslt_lib/parser.c new file mode 100644 index 0000000..6fd72f5 --- /dev/null +++ b/ext/xslt_lib/parser.c @@ -0,0 +1,195 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "xslt.h" +#include "parser.h" + +extern VALUE cXSLT; + +xmlDocPtr parse_xml( char* xml, int iXmlType ) { + xmlDocPtr tXMLDocument = NULL; + + /** Act: Parse XML */ + if( iXmlType == RUBY_XSLT_XMLSRC_TYPE_STR ) { + tXMLDocument = xmlParseMemory( xml, strlen( xml ) ); + } else if( iXmlType == RUBY_XSLT_XMLSRC_TYPE_FILE ) { + tXMLDocument = xmlParseFile( xml ); + } + + if( tXMLDocument == NULL ) { + rb_raise( eXSLTParsingError, "XML parsing error" ); + return( NULL ); + } + + return( tXMLDocument ); +} + +xsltStylesheetPtr parse_xsl( char* xsl, int iXslType ) { + xsltStylesheetPtr tParsedXslt = NULL; + xmlDocPtr tXSLDocument = NULL; + + /** Rem: For encoding */ + xmlCharEncodingHandlerPtr encoder = NULL; + const xmlChar *encoding = NULL; + + /** Act: Encoding support */ + xmlInitCharEncodingHandlers( ); + + /** Act: Parse XSL */ + if( iXslType == RUBY_XSLT_XSLSRC_TYPE_STR ) { + tXSLDocument = xmlParseMemory( xsl, strlen( xsl ) ); + if( tXSLDocument == NULL ) { + rb_raise( eXSLTParsingError, "XSL parsing error" ); + return( NULL ); + } + + tParsedXslt = xsltParseStylesheetDoc( tXSLDocument ); + } else if( iXslType == RUBY_XSLT_XSLSRC_TYPE_FILE ) { + tParsedXslt = xsltParseStylesheetFile( BAD_CAST xsl ); + } + + if( tParsedXslt == NULL ) { + rb_raise( eXSLTParsingError, "XSL Stylesheet parsing error" ); + return( NULL ); + } + + /** Act: Get encoding */ + XSLT_GET_IMPORT_PTR( encoding, tParsedXslt, encoding ) + encoder = xmlFindCharEncodingHandler((char *)encoding); + + if( encoding != NULL ) { + encoder = xmlFindCharEncodingHandler((char *)encoding); + if( (encoder != NULL) && (xmlStrEqual((const xmlChar *)encoder->name, (const xmlChar *) "UTF-8")) ) { + encoder = NULL; + } + } + + return( tParsedXslt ); +} + +/** + * xOut = parser( char *xml, int iXmlType, char *xslt, int iXslType, char **pxParams ); + */ +char* parse( xsltStylesheetPtr tParsedXslt, xmlDocPtr tXMLDocument, char **pxParams ) { + xmlDocPtr tXMLDocumentResult = NULL; + int iXMLDocumentResult; + xmlChar *tXMLDocumentResultString; + int tXMLDocumentResultLenght; + + tXMLDocumentResult = xsltApplyStylesheet( tParsedXslt, tXMLDocument, (const char**) pxParams ); + if( tXMLDocumentResult == NULL ) { + rb_raise( eXSLTTransformationError, "Stylesheet transformation error" ); + return( NULL ); + } + + iXMLDocumentResult = xsltSaveResultToString( &tXMLDocumentResultString, &tXMLDocumentResultLenght, tXMLDocumentResult, tParsedXslt ); + + xmlFreeDoc(tXMLDocumentResult); + + return((char*)tXMLDocumentResultString); +} + +/** + * vOut = object_to_string( VALUE object ); + */ +VALUE object_to_string( VALUE object ) { + VALUE vOut = Qnil; + + switch( TYPE( object ) ) { + case T_STRING: + { + if( isFile( STR2CSTR( object ) ) == 0 ) { + vOut = object; + } else { + long iBufferLength; + long iCpt; + char *xBuffer; + + FILE* fStream = fopen( STR2CSTR( object ), "r" ); + if( fStream == NULL ) { + return( Qnil ); + } + + fseek( fStream, 0L, 2 ); + iBufferLength = ftell( fStream ); + xBuffer = (char *)malloc( (int)iBufferLength + 1 ); + if( !xBuffer ) + rb_raise( rb_eNoMemError, "Memory allocation error" ); + + xBuffer[iBufferLength] = 0; + fseek( fStream, 0L, 0 ); + iCpt = fread( xBuffer, 1, (int)iBufferLength, fStream ); + + if( iCpt != iBufferLength ) { + free( (char *)xBuffer ); + rb_raise( rb_eSystemCallError, "Read file error" ); + } + + vOut = rb_str_new2( xBuffer ); + free( xBuffer ); + + fclose( fStream ); + } + } + break; + + case T_DATA: + case T_OBJECT: + { + if( strcmp( getRubyObjectName( object ), "XML::Smart::Dom" ) == 0 || + strcmp( getRubyObjectName( object ), "XML::Simple::Dom" ) == 0 ) { + vOut = rb_funcall( object, rb_intern( "to_s" ), 0 ); + } else if ( strcmp( getRubyObjectName( object ), "REXML::Document" ) == 0 ) { + vOut = rb_funcall( object, rb_intern( "to_s" ), 0 ); + } else { + rb_raise( rb_eSystemCallError, "Can't read XML from object %s", getRubyObjectName( object ) ); + } + } + break; + + default: + rb_raise( rb_eArgError, "XML object #0x%x not supported", TYPE( object ) ); + } + + return( vOut ); +} + +/** + * bOut = objectIsFile( VALUE object ); + */ +int objectIsFile( VALUE object ) { + int bOut = 0; + + switch( TYPE( object ) ) { + case T_STRING: + { + if( isFile( STR2CSTR( object ) ) == 0 ) + bOut = 0; + else + bOut = 1; + } + break; + + case T_DATA: + case T_OBJECT: + default: + bOut = 0; + } + + return( bOut ); +} diff --git a/ext/xslt_lib/parser.h b/ext/xslt_lib/parser.h new file mode 100644 index 0000000..a8f2843 --- /dev/null +++ b/ext/xslt_lib/parser.h @@ -0,0 +1,30 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef __RUBY_XSLT_PARSER_H__ +#define __RUBY_XSLT_PARSER_H__ +extern int xmlLoadExtDtdDefaultValue; + +xmlDocPtr parse_xml( char* , int ); +xsltStylesheetPtr parse_xsl( char*, int ); +char* parse( xsltStylesheetPtr, xmlDocPtr, char ** ); + +VALUE object_to_string( VALUE ); +int objectIsFile( VALUE ); +#endif + diff --git a/ext/xslt_lib/rb_utils.c b/ext/xslt_lib/rb_utils.c new file mode 100644 index 0000000..1eec15f --- /dev/null +++ b/ext/xslt_lib/rb_utils.c @@ -0,0 +1,31 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "rb_utils.h" + +char * getRubyObjectName( VALUE rb_Object ) { + VALUE klass = rb_funcall( rb_Object, rb_intern( "class" ), 0 ); + return( STR2CSTR( rb_funcall( klass, rb_intern( "to_s" ), 0 ) ) ); +} + +int isFile( const char *filename ) { + struct stat stbuf; + + if( stat( filename, &stbuf ) ) return 0; + return( ( (stbuf.st_mode & S_IFMT) == S_IFREG ) ? 1 : 0 ); +} diff --git a/ext/xslt_lib/rb_utils.h b/ext/xslt_lib/rb_utils.h new file mode 100644 index 0000000..c00c6f8 --- /dev/null +++ b/ext/xslt_lib/rb_utils.h @@ -0,0 +1,34 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* Please see the LICENSE file for copyright and distribution information */ + +#ifndef __RUBY_RB_UTILS_H__ +#define __RUBY_RB_UTILS_H__ + +#include <ruby.h> +#include <ruby/io.h> + +#include <stdio.h> +#include <string.h> +#include <sys/stat.h> + +char * getRubyObjectName( VALUE ); +int isFile( const char *filename ); + +#endif diff --git a/ext/xslt_lib/xslt.h b/ext/xslt_lib/xslt.h new file mode 100644 index 0000000..30819ba --- /dev/null +++ b/ext/xslt_lib/xslt.h @@ -0,0 +1,98 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* Please see the LICENSE file for copyright and distribution information */ + +#ifndef __RUBY_XSLT_H__ +#define __RUBY_XSLT_H__ + +#include <ruby.h> +#include <ruby/io.h> + +#include <string.h> + +#include <libxml/xmlmemory.h> +#include <libxml/debugXML.h> +#include <libxml/HTMLtree.h> +#include <libxml/xmlIO.h> +#include <libxml/xinclude.h> +#include <libxml/catalog.h> + +#include <libxslt/extra.h> +#include <libxslt/xslt.h> +#include <libxslt/xsltInternals.h> +#include <libxslt/transform.h> +#include <libxslt/xsltutils.h> +#include <libxslt/imports.h> + +#ifdef USE_EXSLT + #include <libexslt/exslt.h> +#endif + +#ifdef MEMWATCH + #include "memwatch.h" +#endif + +#include "rb_utils.h" +#include "parser.h" +#include "parameters.h" +#include "extfunc.h" + +#define RUBY_XSLT_VERSION "0.9.6" +#define RUBY_XSLT_VERNUM 096 + +#define RUBY_XSLT_XSLSRC_TYPE_NULL 0 +#define RUBY_XSLT_XSLSRC_TYPE_STR 1 +#define RUBY_XSLT_XSLSRC_TYPE_FILE 2 +#define RUBY_XSLT_XSLSRC_TYPE_REXML 4 +#define RUBY_XSLT_XSLSRC_TYPE_SMART 8 +#define RUBY_XSLT_XSLSRC_TYPE_PARSED 16 + +#define RUBY_XSLT_XMLSRC_TYPE_NULL 0 +#define RUBY_XSLT_XMLSRC_TYPE_STR 1 +#define RUBY_XSLT_XMLSRC_TYPE_FILE 2 +#define RUBY_XSLT_XMLSRC_TYPE_REXML 4 +#define RUBY_XSLT_XMLSRC_TYPE_SMART 8 +#define RUBY_XSLT_XMLSRC_TYPE_PARSED 16 + +RUBY_EXTERN VALUE eXSLTError; +RUBY_EXTERN VALUE eXSLTParsingError; +RUBY_EXTERN VALUE eXSLTTransformationError; + +typedef struct RbTxslt { + int iXmlType; + VALUE xXmlData; + VALUE oXmlObject; + VALUE xXmlString; + xmlDocPtr tXMLDocument; + + int iXslType; + VALUE xXslData; + VALUE oXslObject; + VALUE xXslString; + xsltStylesheetPtr tParsedXslt; + + int iXmlResultType; + VALUE xXmlResultCache; + + VALUE pxParams; + int iNbParams; + +} RbTxslt; + +#endif diff --git a/ext/xslt_lib/xslt_lib.c b/ext/xslt_lib/xslt_lib.c new file mode 100644 index 0000000..4c441e6 --- /dev/null +++ b/ext/xslt_lib/xslt_lib.c @@ -0,0 +1,599 @@ +/** + * Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "xslt.h" + +VALUE mXML; +VALUE cXSLT; +VALUE eXSLTError; +VALUE eXSLTParsingError; +VALUE eXSLTTransformationError; + +void ruby_xslt_free( RbTxslt *pRbTxslt ) { + if( pRbTxslt != NULL ) { + if( pRbTxslt->tParsedXslt != NULL ) + xsltFreeStylesheet(pRbTxslt->tParsedXslt); + + if( pRbTxslt->tXMLDocument != NULL ) + xmlFreeDoc(pRbTxslt->tXMLDocument); + + free( pRbTxslt ); + } + + xsltCleanupGlobals(); + xmlCleanupParser(); + xmlMemoryDump(); +} + +void ruby_xslt_mark( RbTxslt *pRbTxslt ) { + if( pRbTxslt == NULL ) return; + if( !NIL_P(pRbTxslt->xXmlData) ) rb_gc_mark( pRbTxslt->xXmlData ); + if( !NIL_P(pRbTxslt->oXmlObject) ) rb_gc_mark( pRbTxslt->oXmlObject ); + if( !NIL_P(pRbTxslt->xXmlString) ) rb_gc_mark( pRbTxslt->xXmlString ); + + if( !NIL_P(pRbTxslt->xXslData) ) rb_gc_mark( pRbTxslt->xXslData ); + if( !NIL_P(pRbTxslt->oXslObject) ) rb_gc_mark( pRbTxslt->oXslObject ); + if( !NIL_P(pRbTxslt->xXslString) ) rb_gc_mark( pRbTxslt->xXslString ); + + if( !NIL_P(pRbTxslt->xXmlResultCache) ) rb_gc_mark( pRbTxslt->xXmlResultCache ); + + if( !NIL_P(pRbTxslt->pxParams) ) rb_gc_mark( pRbTxslt->pxParams ); +} + +/** + * oXSLT = XML::XSLT::new() + * + * Create a new XML::XSLT object + */ +VALUE ruby_xslt_new( VALUE class ) { + RbTxslt *pRbTxslt; + + pRbTxslt = (RbTxslt *)malloc(sizeof(RbTxslt)); + if( pRbTxslt == NULL ) + rb_raise(rb_eNoMemError, "No memory left for XSLT struct"); + + pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_NULL; + pRbTxslt->xXmlData = Qnil; + pRbTxslt->oXmlObject = Qnil; + pRbTxslt->xXmlString = Qnil; + pRbTxslt->tXMLDocument = NULL; + + pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_NULL; + pRbTxslt->xXslData = Qnil; + pRbTxslt->oXslObject = Qnil; + pRbTxslt->xXslString = Qnil; + pRbTxslt->tParsedXslt = NULL; + + pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL; + pRbTxslt->xXmlResultCache = Qnil; + + pRbTxslt->pxParams = Qnil; + pRbTxslt->iNbParams = 0; + + xmlInitMemory(); + xmlSubstituteEntitiesDefault( 1 ); + xmlLoadExtDtdDefaultValue = 1; + + return( Data_Wrap_Struct( class, ruby_xslt_mark, ruby_xslt_free, pRbTxslt ) ); +} + +/** + * ---------------------------------------------------------------------------- + */ + +/** + * oXSLT.xml=<data|REXML::Document|XML::Smart|file> + * + * Set XML data. + * + * Parameter can be type String, REXML::Document, XML::Smart::Dom or Filename + * + * Examples : + * # Parameter as String + * oXSLT.xml = <<XML + * <?xml version="1.0" encoding="UTF-8"?> + * <test>This is a test string</test> + * XML + * + * # Parameter as REXML::Document + * require 'rexml/document' + * oXSLT.xml = REXML::Document.new File.open( "test.xml" ) + * + * # Parameter as XML::Smart::Dom + * require 'xml/smart' + * oXSLT.xml = XML::Smart.open( "test.xml" ) + * + * # Parameter as Filename + * oXSLT.xml = "test.xml" + */ +VALUE ruby_xslt_xml_obj_set( VALUE self, VALUE xml_doc_obj ) { + RbTxslt *pRbTxslt; + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + pRbTxslt->oXmlObject = xml_doc_obj; + pRbTxslt->xXmlString = object_to_string( xml_doc_obj ); + if( pRbTxslt->xXmlString == Qnil ) { + rb_raise( eXSLTError, "Can't get XML data" ); + } + pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_STR; + pRbTxslt->xXmlData = pRbTxslt->xXmlString; + + pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL; + + if( pRbTxslt->tXMLDocument != NULL ) { + xmlFreeDoc(pRbTxslt->tXMLDocument); + } + + pRbTxslt->tXMLDocument = parse_xml( STR2CSTR( pRbTxslt->xXmlData ), pRbTxslt->iXmlType ); + if( pRbTxslt->tXMLDocument == NULL ) { + rb_raise( eXSLTParsingError, "XML parsing error" ); + } + + pRbTxslt->iXmlType = RUBY_XSLT_XMLSRC_TYPE_PARSED; + + return( Qnil ); +} + +/** + * XML::XSLT#xmlfile=<file> is deprecated. Please use XML::XSLT#xml=<file> + */ +VALUE ruby_xslt_xml_obj_set_d( VALUE self, VALUE xml_doc_obj ) { + rb_warn( "XML::XSLT#xmlfile=<file> is deprecated. Please use XML::XSLT#xml=<file> !" ); + return( ruby_xslt_xml_obj_set( self, xml_doc_obj ) ); +} + +/** + * string = oXSLT.xml + * + * Return XML, set by XML::XSLT#xml=, as string + */ +VALUE ruby_xslt_xml_2str_get( VALUE self ) { + RbTxslt *pRbTxslt; + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + return( pRbTxslt->xXmlString ); +} + +/** + * object = oXSLT.xmlobject + * + * Return the XML object set by XML::XSLT#xml= + */ +VALUE ruby_xslt_xml_2obj_get( VALUE self ) { + RbTxslt *pRbTxslt; + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + return( pRbTxslt->oXmlObject ); +} + +/** + * ---------------------------------------------------------------------------- + */ + +/** + * oXSLT.xsl=<data|REXML::Document|XML::Smart|file> + * + * Set XSL data. + * + * Parameter can be type String, REXML::Document, XML::Smart::Dom or Filename + * + * Examples : + * # Parameter as String + * oXSLT.xsl = <<XML + * <?xml version="1.0" ?> + * <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> + * <xsl:template match="/"> + * <xsl:apply-templates /> + * </xsl:template> + * </xsl:stylesheet> + * XML + * + * # Parameter as REXML::Document + * require 'rexml/document' + * oXSLT.xsl = REXML::Document.new File.open( "test.xsl" ) + * + * # Parameter as XML::Smart::Dom + * require 'xml/smart' + * oXSLT.xsl = XML::Smart.open( "test.xsl" ) + * + * # Parameter as Filename + * oXSLT.xsl = "test.xsl" + */ +VALUE ruby_xslt_xsl_obj_set( VALUE self, VALUE xsl_doc_obj ) { + RbTxslt *pRbTxslt; + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + pRbTxslt->oXslObject = xsl_doc_obj; + pRbTxslt->xXslString = object_to_string( xsl_doc_obj ); + if( pRbTxslt->xXslString == Qnil ) { + rb_raise( eXSLTError, "Can't get XSL data" ); + } + + if( objectIsFile( xsl_doc_obj ) ) { + pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_FILE; + pRbTxslt->xXslData = pRbTxslt->oXslObject; + } else { + pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_STR; + pRbTxslt->xXslData = pRbTxslt->xXslString; + } + + pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL; + + if( pRbTxslt->tParsedXslt != NULL ) { + xsltFreeStylesheet(pRbTxslt->tParsedXslt); + } + + pRbTxslt->tParsedXslt = parse_xsl( STR2CSTR( pRbTxslt->xXslData ), pRbTxslt->iXslType ); + if( pRbTxslt->tParsedXslt == NULL ) { + rb_raise( eXSLTParsingError, "XSL Stylesheet parsing error" ); + } + + pRbTxslt->iXslType = RUBY_XSLT_XSLSRC_TYPE_PARSED; + + return( Qnil ); +} + +/** + * XML::XSLT#xslfile=<file> is deprecated. Please use XML::XSLT#xsl=<file> + */ +VALUE ruby_xslt_xsl_obj_set_d( VALUE self, VALUE xsl_doc_obj ) { + rb_warning( "XML::XSLT#xslfile=<file> is deprecated. Please use XML::XSLT#xsl=<file> !" ); + return( ruby_xslt_xsl_obj_set( self, xsl_doc_obj ) ); +} + +/** + * string = oXSLT.xsl + * + * Return XSL, set by XML::XSLT#xsl=, as string + */ +VALUE ruby_xslt_xsl_2str_get( VALUE self ) { + RbTxslt *pRbTxslt; + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + return( pRbTxslt->xXslString ); +} + +/** + * object = oXSLT.xslobject + * + * Return the XSL object set by XML::XSLT#xsl= + */ +VALUE ruby_xslt_xsl_2obj_get( VALUE self ) { + RbTxslt *pRbTxslt; + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + return( pRbTxslt->oXslObject ); +} + +/** + * ---------------------------------------------------------------------------- + */ + +/** + * output_string = oXSLT.serve( ) + * + * Return the stylesheet transformation + */ +VALUE ruby_xslt_serve( VALUE self ) { + RbTxslt *pRbTxslt; + char *xOut; + char **pxParams = NULL; + + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + if( pRbTxslt->iXmlResultType == RUBY_XSLT_XMLSRC_TYPE_NULL ) { + + if( pRbTxslt->pxParams != Qnil ){ + int iCpt; + + pxParams = (char **)ALLOCA_N( void *, pRbTxslt->iNbParams ); + MEMZERO( pxParams, void *, pRbTxslt->iNbParams ); + + for( iCpt = 0; iCpt <= pRbTxslt->iNbParams - 3; iCpt++ ) { + pxParams[iCpt] = STR2CSTR( rb_ary_entry( pRbTxslt->pxParams, iCpt ) ); + } + } + + if( pRbTxslt->iXslType != RUBY_XSLT_XSLSRC_TYPE_NULL && + pRbTxslt->iXmlType != RUBY_XSLT_XMLSRC_TYPE_NULL ) { + xOut = parse( pRbTxslt->tParsedXslt, pRbTxslt->tXMLDocument, pxParams ); + if( xOut == NULL ) { + pRbTxslt->xXmlResultCache = Qnil; + pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL; + } else { + pRbTxslt->xXmlResultCache = rb_str_new2( xOut ); + pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_STR; + free( xOut ); + } + } else { + pRbTxslt->xXmlResultCache = Qnil; + pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL; + } + } + + return( pRbTxslt->xXmlResultCache ); +} + +/** + * oXSLT.save( "result.xml" ) + * + * Save the stylesheet transformation to file + */ +VALUE ruby_xslt_save( VALUE self, VALUE xOutFilename ) { + char *xOut; + VALUE rOut; + FILE *fOutFile; + + rOut = ruby_xslt_serve( self ); + + if( rOut != Qnil ) { + xOut = STR2CSTR( rOut ); + + fOutFile = fopen( STR2CSTR( xOutFilename ), "w" ); + if( fOutFile == NULL ) { + free( xOut ); + rb_raise( rb_eRuntimeError, "Can't create file %s\n", STR2CSTR( xOutFilename ) ); + rOut = Qnil; + } else { + fwrite( xOut, 1, strlen( xOut ), fOutFile ); + fclose( fOutFile ); + } + } + + return( rOut ); +} + +/** + * ---------------------------------------------------------------------------- + */ + +#ifdef USE_ERROR_HANDLER +/** + * Brendan Taylor + * [email protected] + */ +/* + * libxml2/libxslt error handling function + * + * converts the error to a String and passes it off to a block + * registered using XML::XSLT.register_error_handler + */ +void ruby_xslt_error_handler(void *ctx, const char *msg, ...) { + va_list ap; + char *str; + char *larger; + int chars; + int size = 150; + + VALUE block = rb_cvar_get(cXSLT, rb_intern("@@error_handler")); + + /* the following was cut&pasted from the libxslt python bindings */ + str = (char *) xmlMalloc(150); + if (str == NULL) + return; + + while (1) { + va_start(ap, msg); + chars = vsnprintf(str, size, msg, ap); + va_end(ap); + if ((chars > -1) && (chars < size)) + break; + if (chars > -1) + size += chars + 1; + else + size += 100; + if ((larger = (char *) xmlRealloc(str, size)) == NULL) { + xmlFree(str); + return; + } + str = larger; + } + + rb_funcall( block, rb_intern("call"), 1, rb_str_new2(str)); +} +#endif + +/** + * ---------------------------------------------------------------------------- + */ + +/** + * parameters support, patch from : + * + * Eustáquio "TaQ" Rangel + * [email protected] + * http://beam.to/taq + * + * Corrections : Greg + */ +/** + * oXSLT.parameters={ "key" => "value", "key" => "value", ... } + */ +VALUE ruby_xslt_parameters_set( VALUE self, VALUE parameters ) { + RbTxslt *pRbTxslt; + Check_Type( parameters, T_HASH ); + + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + if( !NIL_P(parameters) ){ + pRbTxslt->pxParams = rb_ary_new( ); + // each_pair and process_pair defined ind parameters.c + (void)rb_iterate( each_pair, parameters, process_pair, pRbTxslt->pxParams ); + pRbTxslt->iNbParams = FIX2INT( rb_funcall( parameters, rb_intern("size"), 0, 0 ) ) * 2 + 2; + pRbTxslt->iXmlResultType = RUBY_XSLT_XMLSRC_TYPE_NULL; + } + + return( Qnil ); +} + +/** + * ---------------------------------------------------------------------------- + */ + +/** + * media type information, path from : + * + * Brendan Taylor + * [email protected] + * + */ +/** + * mediaTypeString = oXSLT.mediaType( ) + * + * Return the XSL output's media type + */ +VALUE ruby_xslt_media_type( VALUE self ) { + RbTxslt *pRbTxslt; + xsltStylesheetPtr vXSLTSheet = NULL; + + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + vXSLTSheet = pRbTxslt->tParsedXslt; + + if ( (vXSLTSheet == NULL) || (vXSLTSheet->mediaType == NULL) ) { + return Qnil; + } else { + return rb_str_new2( (char *)(vXSLTSheet->mediaType) ); + } +} + +/** + * ---------------------------------------------------------------------------- + */ + +/** + * internal use only. + */ + VALUE ruby_xslt_reg_function( VALUE class, VALUE namespace, VALUE name ) { + xsltRegisterExtModuleFunction( BAD_CAST STR2CSTR(name), BAD_CAST STR2CSTR(namespace), xmlXPathFuncCallback ); + + return Qnil; + } + +/** + * string = oXSLT.xsl_to_s( ) + */ +VALUE ruby_xslt_to_s( VALUE self ) { + VALUE vStrOut; + RbTxslt *pRbTxslt; + xsltStylesheetPtr vXSLTSheet = NULL; + char *xKlassName = rb_class2name( CLASS_OF( self ) ); + + Data_Get_Struct( self, RbTxslt, pRbTxslt ); + + //vXSLTSheet = xsltParseStylesheetDoc( xmlParseMemory( STR2CSTR( pRbTxslt->xXslData ), strlen( STR2CSTR( pRbTxslt->xXslData ) ) ) ); + vXSLTSheet = pRbTxslt->tParsedXslt; + if (vXSLTSheet == NULL) return Qnil; + + vStrOut = rb_str_new( 0, strlen(xKlassName)+1024 ); + (void) sprintf( RSTRING_PTR(vStrOut), + "#<%s: parent=%p,next=%p,imports=%p,docList=%p," + "doc=%p,stripSpaces=%p,stripAll=%d,cdataSection=%p," + "variables=%p,templates=%p,templatesHash=%p," + "rootMatch=%p,keyMatch=%p,elemMatch=%p," + "attrMatch=%p,parentMatch=%p,textMatch=%p," + "piMatch=%p,commentMatch=%p,nsAliases=%p," + "attributeSets=%p,nsHash=%p,nsDefs=%p,keys=%p," + "method=%s,methodURI=%s,version=%s,encoding=%s," + "omitXmlDeclaration=%d,decimalFormat=%p,standalone=%d," + "doctypePublic=%s,doctypeSystem=%s,indent=%d," + "mediaType=%s,preComps=%p,warnings=%d,errors=%d," + "exclPrefix=%s,exclPrefixTab=%p,exclPrefixNr=%d," + "exclPrefixMax=%d>", + xKlassName, + vXSLTSheet->parent, vXSLTSheet->next, vXSLTSheet->imports, vXSLTSheet->docList, + vXSLTSheet->doc, vXSLTSheet->stripSpaces, vXSLTSheet->stripAll, vXSLTSheet->cdataSection, + vXSLTSheet->variables, vXSLTSheet->templates, vXSLTSheet->templatesHash, + vXSLTSheet->rootMatch, vXSLTSheet->keyMatch, vXSLTSheet->elemMatch, + vXSLTSheet->attrMatch, vXSLTSheet->parentMatch, vXSLTSheet->textMatch, + vXSLTSheet->piMatch, vXSLTSheet->commentMatch, vXSLTSheet->nsAliases, + vXSLTSheet->attributeSets, vXSLTSheet->nsHash, vXSLTSheet->nsDefs, vXSLTSheet->keys, + vXSLTSheet->method, vXSLTSheet->methodURI, vXSLTSheet->version, vXSLTSheet->encoding, + vXSLTSheet->omitXmlDeclaration, vXSLTSheet->decimalFormat, vXSLTSheet->standalone, + vXSLTSheet->doctypePublic, vXSLTSheet->doctypeSystem, vXSLTSheet->indent, + vXSLTSheet->mediaType, vXSLTSheet->preComps, vXSLTSheet->warnings, vXSLTSheet->errors, + vXSLTSheet->exclPrefix, vXSLTSheet->exclPrefixTab, vXSLTSheet->exclPrefixNr, + vXSLTSheet->exclPrefixMax ); + + vStrOut = strlen(RSTRING_PTR(vStrOut)); + if( OBJ_TAINTED(self) ) OBJ_TAINT(vStrOut); + + // xsltFreeStylesheet(vXSLTSheet); + + return( vStrOut ); +} + +/** + * ---------------------------------------------------------------------------- + */ + +void Init_xslt_lib( void ) { + mXML = rb_define_module( "XML" ); + cXSLT = rb_define_class_under( mXML, "XSLT", rb_cObject ); + + eXSLTError = rb_define_class_under( cXSLT, "XSLTError", rb_eRuntimeError ); + eXSLTParsingError = rb_define_class_under( cXSLT, "ParsingError", eXSLTError ); + eXSLTTransformationError = rb_define_class_under( cXSLT, "TransformationError", eXSLTError ); + + rb_define_const( cXSLT, "MAX_DEPTH", INT2NUM(xsltMaxDepth) ); + rb_define_const( cXSLT, "MAX_SORT", INT2NUM(XSLT_MAX_SORT) ); + rb_define_const( cXSLT, "ENGINE_VERSION", rb_str_new2(xsltEngineVersion) ); + rb_define_const( cXSLT, "LIBXSLT_VERSION", INT2NUM(xsltLibxsltVersion) ); + rb_define_const( cXSLT, "LIBXML_VERSION", INT2NUM(xsltLibxmlVersion) ); + rb_define_const( cXSLT, "XSLT_NAMESPACE", rb_str_new2((char *)XSLT_NAMESPACE) ); + rb_define_const( cXSLT, "DEFAULT_VENDOR", rb_str_new2(XSLT_DEFAULT_VENDOR) ); + rb_define_const( cXSLT, "DEFAULT_VERSION", rb_str_new2(XSLT_DEFAULT_VERSION) ); + rb_define_const( cXSLT, "DEFAULT_URL", rb_str_new2(XSLT_DEFAULT_URL) ); + rb_define_const( cXSLT, "NAMESPACE_LIBXSLT", rb_str_new2((char *)XSLT_LIBXSLT_NAMESPACE) ); + rb_define_const( cXSLT, "NAMESPACE_NORM_SAXON", rb_str_new2((char *)XSLT_NORM_SAXON_NAMESPACE) ); + rb_define_const( cXSLT, "NAMESPACE_SAXON", rb_str_new2((char *)XSLT_SAXON_NAMESPACE) ); + rb_define_const( cXSLT, "NAMESPACE_XT", rb_str_new2((char *)XSLT_XT_NAMESPACE) ); + rb_define_const( cXSLT, "NAMESPACE_XALAN", rb_str_new2((char *)XSLT_XALAN_NAMESPACE) ); + + rb_define_const( cXSLT, "RUBY_XSLT_VERSION", rb_str_new2(RUBY_XSLT_VERSION) ); + + rb_define_singleton_method( cXSLT, "new", ruby_xslt_new, 0 ); + rb_define_singleton_method( cXSLT, "registerFunction", ruby_xslt_reg_function, 2); + + rb_define_method( cXSLT, "serve", ruby_xslt_serve, 0 ); + rb_define_method( cXSLT, "save", ruby_xslt_save, 1 ); + + rb_define_method( cXSLT, "xml=", ruby_xslt_xml_obj_set, 1 ); + rb_define_method( cXSLT, "xmlfile=", ruby_xslt_xml_obj_set_d, 1 ); // DEPRECATED + rb_define_method( cXSLT, "xml", ruby_xslt_xml_2str_get, 0 ); + rb_define_method( cXSLT, "xmlobject", ruby_xslt_xml_2obj_get, 0 ); + + rb_define_method( cXSLT, "xsl=", ruby_xslt_xsl_obj_set, 1 ); + rb_define_method( cXSLT, "xslfile=", ruby_xslt_xsl_obj_set_d, 1 ); // DEPRECATED + rb_define_method( cXSLT, "xsl", ruby_xslt_xsl_2str_get, 0 ); + rb_define_method( cXSLT, "xslobject", ruby_xslt_xsl_2obj_get, 0 ); + + rb_define_method( cXSLT, "parameters=", ruby_xslt_parameters_set, 1 ); + rb_define_method( cXSLT, "xsl_to_s", ruby_xslt_to_s, 0 ); + + rb_define_method( cXSLT, "mediaType", ruby_xslt_media_type, 0 ); + +#ifdef USE_ERROR_HANDLER + xmlSetGenericErrorFunc( NULL, ruby_xslt_error_handler ); + xsltSetGenericErrorFunc( NULL, ruby_xslt_error_handler ); +#endif + +#ifdef USE_EXSLT + exsltRegisterAll(); +#endif +} diff --git a/lib/xml/xslt.rb b/lib/xml/xslt.rb new file mode 100644 index 0000000..51e1926 --- /dev/null +++ b/lib/xml/xslt.rb @@ -0,0 +1,82 @@ +## +# Copyright (C) 2005, 2006, 2007, 2008 Gregoire Lejeune <[email protected]> +# +# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +require "xml/xslt_lib" + +module XML + class XSLT + @@extFunctions = {} + + # sets up a block for callback when the XPath function + # namespace:name( ... ) is encountered in a stylesheet. + # + # XML::XSLT.registerExtFunc(namespace_uri, name) do |*args| + # puts args.inspect + # end + # + # XPath arguments are converted to Ruby objects accordingly: + # + # number (eg. <tt>1</tt>):: Float + # boolean (eg. <tt>false()</tt>):: TrueClass/FalseClass + # nodeset (eg. <tt>/entry/*</tt>):: Array of REXML::Elements + # variable (eg. <tt>$var</tt>):: UNIMPLEMENTED + # + # It works the same in the other direction, eg. if the block + # returns an array of REXML::Elements the value of the function + # will be a nodeset. + # + # Note: currently, passing a nodeset to Ruby or REXML::Elements to + # libxslt serializes the nodes and then parses them. Doing this + # with large sets is a bad idea. In the future they'll be passed + # back and forth using Ruby's libxml2 bindings. + def self.registerExtFunc(namespace, name, &block) + @@extFunctions[namespace] ||= {} + @@extFunctions[namespace][name] = block + XML::XSLT.registerFunction(namespace, name) + end + + # deprecated, see +registerExtFunc+ + def self.extFunction(name, ns_uri, receiver) #:nodoc: + self.registerExtFunc(ns_uri, name) do |*args| + receiver.send(name.gsub(/-/, "_"), *args) + end + end + + # registers a block to be called when libxml2 or libxslt encounter an error + # eg: + # + # XML::XSLT.registerErrorHandler do |error_str| + # $stderr.puts error_str + # end + # + def self.registerErrorHandler(&block) + @@error_handler = block + end + + # set up default error handler + self.registerErrorHandler do |error_str| + $stderr.puts error_str + end + + alias :media_type :mediaType + class <<XML::XSLT + alias :register_ext_func :registerExtFunc + alias :register_error_handler :registerErrorHandler + end + end +end diff --git a/setup.rb b/setup.rb new file mode 100644 index 0000000..424a5f3 --- /dev/null +++ b/setup.rb @@ -0,0 +1,1585 @@ +# +# setup.rb +# +# Copyright (c) 2000-2005 Minero Aoki +# +# This program is free software. +# You can distribute/modify this program under the terms of +# the GNU LGPL, Lesser General Public License version 2.1. +# + +unless Enumerable.method_defined?(:map) # Ruby 1.4.6 + module Enumerable + alias map collect + end +end + +unless File.respond_to?(:read) # Ruby 1.6 + def File.read(fname) + open(fname) {|f| + return f.read + } + end +end + +unless Errno.const_defined?(:ENOTEMPTY) # Windows? + module Errno + class ENOTEMPTY + # We do not raise this exception, implementation is not needed. + end + end +end + +def File.binread(fname) + open(fname, 'rb') {|f| + return f.read + } +end + +# for corrupted Windows' stat(2) +def File.dir?(path) + File.directory?((path[-1,1] == '/') ? path : path + '/') +end + + +class ConfigTable + + include Enumerable + + def initialize(rbconfig) + @rbconfig = rbconfig + @items = [] + @table = {} + # options + @install_prefix = nil + @config_opt = nil + @verbose = true + @no_harm = false + end + + attr_accessor :install_prefix + attr_accessor :config_opt + + attr_writer :verbose + + def verbose? + @verbose + end + + attr_writer :no_harm + + def no_harm? + @no_harm + end + + def [](key) + lookup(key).resolve(self) + end + + def []=(key, val) + lookup(key).set val + end + + def names + @items.map {|i| i.name } + end + + def each(&block) + @items.each(&block) + end + + def key?(name) + @table.key?(name) + end + + def lookup(name) + @table[name] or setup_rb_error "no such config item: #{name}" + end + + def add(item) + @items.push item + @table[item.name] = item + end + + def remove(name) + item = lookup(name) + @items.delete_if {|i| i.name == name } + @table.delete_if {|name, i| i.name == name } + item + end + + def load_script(path, inst = nil) + if File.file?(path) + MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path + end + end + + def savefile + '.config' + end + + def load_savefile + begin + File.foreach(savefile()) do |line| + k, v = *line.split(/=/, 2) + self[k] = v.strip + end + rescue Errno::ENOENT + setup_rb_error $!.message + "\n#{File.basename($0)} config first" + end + end + + def save + @items.each {|i| i.value } + File.open(savefile(), 'w') {|f| + @items.each do |i| + f.printf "%s=%s\n", i.name, i.value if i.value? and i.value + end + } + end + + def load_standard_entries + standard_entries(@rbconfig).each do |ent| + add ent + end + end + + def standard_entries(rbconfig) + c = rbconfig + + rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) + + major = c['MAJOR'].to_i + minor = c['MINOR'].to_i + teeny = c['TEENY'].to_i + version = "#{major}.#{minor}" + + # ruby ver. >= 1.4.4? + newpath_p = ((major >= 2) or + ((major == 1) and + ((minor >= 5) or + ((minor == 4) and (teeny >= 4))))) + + if c['rubylibdir'] + # V > 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = c['rubylibdir'] + librubyverarch = c['archdir'] + siteruby = c['sitedir'] + siterubyver = c['sitelibdir'] + siterubyverarch = c['sitearchdir'] + elsif newpath_p + # 1.4.4 <= V <= 1.6.3 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = c['sitedir'] + siterubyver = "$siteruby/#{version}" + siterubyverarch = "$siterubyver/#{c['arch']}" + else + # V < 1.4.4 + libruby = "#{c['prefix']}/lib/ruby" + librubyver = "#{c['prefix']}/lib/ruby/#{version}" + librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" + siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" + siterubyver = siteruby + siterubyverarch = "$siterubyver/#{c['arch']}" + end + parameterize = lambda {|path| + path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') + } + + if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } + makeprog = arg.sub(/'/, '').split(/=/, 2)[1] + else + makeprog = 'make' + end + + [ + ExecItem.new('installdirs', 'std/site/home', + 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ + {|val, table| + case val + when 'std' + table['rbdir'] = '$librubyver' + table['sodir'] = '$librubyverarch' + when 'site' + table['rbdir'] = '$siterubyver' + table['sodir'] = '$siterubyverarch' + when 'home' + setup_rb_error '$HOME was not set' unless ENV['HOME'] + table['prefix'] = ENV['HOME'] + table['rbdir'] = '$libdir/ruby' + table['sodir'] = '$libdir/ruby' + end + }, + PathItem.new('prefix', 'path', c['prefix'], + 'path prefix of target environment'), + PathItem.new('bindir', 'path', parameterize.call(c['bindir']), + 'the directory for commands'), + PathItem.new('libdir', 'path', parameterize.call(c['libdir']), + 'the directory for libraries'), + PathItem.new('datadir', 'path', parameterize.call(c['datadir']), + 'the directory for shared data'), + PathItem.new('mandir', 'path', parameterize.call(c['mandir']), + 'the directory for man pages'), + PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), + 'the directory for system configuration files'), + PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), + 'the directory for local state data'), + PathItem.new('libruby', 'path', libruby, + 'the directory for ruby libraries'), + PathItem.new('librubyver', 'path', librubyver, + 'the directory for standard ruby libraries'), + PathItem.new('librubyverarch', 'path', librubyverarch, + 'the directory for standard ruby extensions'), + PathItem.new('siteruby', 'path', siteruby, + 'the directory for version-independent aux ruby libraries'), + PathItem.new('siterubyver', 'path', siterubyver, + 'the directory for aux ruby libraries'), + PathItem.new('siterubyverarch', 'path', siterubyverarch, + 'the directory for aux ruby binaries'), + PathItem.new('rbdir', 'path', '$siterubyver', + 'the directory for ruby scripts'), + PathItem.new('sodir', 'path', '$siterubyverarch', + 'the directory for ruby extentions'), + PathItem.new('rubypath', 'path', rubypath, + 'the path to set to #! line'), + ProgramItem.new('rubyprog', 'name', rubypath, + 'the ruby program using for installation'), + ProgramItem.new('makeprog', 'name', makeprog, + 'the make program to compile ruby extentions'), + SelectItem.new('shebang', 'all/ruby/never', 'ruby', + 'shebang line (#!) editing mode'), + BoolItem.new('without-ext', 'yes/no', 'no', + 'does not compile/install ruby extentions') + ] + end + private :standard_entries + + def load_multipackage_entries + multipackage_entries().each do |ent| + add ent + end + end + + def multipackage_entries + [ + PackageSelectionItem.new('with', 'name,name...', '', 'ALL', + 'package names that you want to install'), + PackageSelectionItem.new('without', 'name,name...', '', 'NONE', + 'package names that you do not want to install') + ] + end + private :multipackage_entries + + ALIASES = { + 'std-ruby' => 'librubyver', + 'stdruby' => 'librubyver', + 'rubylibdir' => 'librubyver', + 'archdir' => 'librubyverarch', + 'site-ruby-common' => 'siteruby', # For backward compatibility + 'site-ruby' => 'siterubyver', # For backward compatibility + 'bin-dir' => 'bindir', + 'bin-dir' => 'bindir', + 'rb-dir' => 'rbdir', + 'so-dir' => 'sodir', + 'data-dir' => 'datadir', + 'ruby-path' => 'rubypath', + 'ruby-prog' => 'rubyprog', + 'ruby' => 'rubyprog', + 'make-prog' => 'makeprog', + 'make' => 'makeprog' + } + + def fixup + ALIASES.each do |ali, name| + @table[ali] = @table[name] + end + @items.freeze + @table.freeze + @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ + end + + def parse_opt(opt) + m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" + m.to_a[1,2] + end + + def dllext + @rbconfig['DLEXT'] + end + + def value_config?(name) + lookup(name).value? + end + + class Item + def initialize(name, template, default, desc) + @name = name.freeze + @template = template + @value = default + @default = default + @description = desc + end + + attr_reader :name + attr_reader :description + + attr_accessor :default + alias help_default default + + def help_opt + "--#{@name}=#{@template}" + end + + def value? + true + end + + def value + @value + end + + def resolve(table) + @value.gsub(%r<\$([^/]+)>) { table[$1] } + end + + def set(val) + @value = check(val) + end + + private + + def check(val) + setup_rb_error "config: --#{name} requires argument" unless val + val + end + end + + class BoolItem < Item + def config_type + 'bool' + end + + def help_opt + "--#{@name}" + end + + private + + def check(val) + return 'yes' unless val + case val + when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' + when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' + else + setup_rb_error "config: --#{@name} accepts only yes/no for argument" + end + end + end + + class PathItem < Item + def config_type + 'path' + end + + private + + def check(path) + setup_rb_error "config: --#{@name} requires argument" unless path + path[0,1] == '$' ? path : File.expand_path(path) + end + end + + class ProgramItem < Item + def config_type + 'program' + end + end + + class SelectItem < Item + def initialize(name, selection, default, desc) + super + @ok = selection.split('/') + end + + def config_type + 'select' + end + + private + + def check(val) + unless @ok.include?(val.strip) + setup_rb_error "config: use --#{@name}=#{@template} (#{val})" + end + val.strip + end + end + + class ExecItem < Item + def initialize(name, selection, desc, &block) + super name, selection, nil, desc + @ok = selection.split('/') + @action = block + end + + def config_type + 'exec' + end + + def value? + false + end + + def resolve(table) + setup_rb_error "$#{name()} wrongly used as option value" + end + + undef set + + def evaluate(val, table) + v = val.strip.downcase + unless @ok.include?(v) + setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" + end + @action.call v, table + end + end + + class PackageSelectionItem < Item + def initialize(name, template, default, help_default, desc) + super name, template, default, desc + @help_default = help_default + end + + attr_reader :help_default + + def config_type + 'package' + end + + private + + def check(val) + unless File.dir?("packages/#{val}") + setup_rb_error "config: no such package: #{val}" + end + val + end + end + + class MetaConfigEnvironment + def initialize(config, installer) + @config = config + @installer = installer + end + + def config_names + @config.names + end + + def config?(name) + @config.key?(name) + end + + def bool_config?(name) + @config.lookup(name).config_type == 'bool' + end + + def path_config?(name) + @config.lookup(name).config_type == 'path' + end + + def value_config?(name) + @config.lookup(name).config_type != 'exec' + end + + def add_config(item) + @config.add item + end + + def add_bool_config(name, default, desc) + @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) + end + + def add_path_config(name, default, desc) + @config.add PathItem.new(name, 'path', default, desc) + end + + def set_config_default(name, default) + @config.lookup(name).default = default + end + + def remove_config(name) + @config.remove(name) + end + + # For only multipackage + def packages + raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer + @installer.packages + end + + # For only multipackage + def declare_packages(list) + raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer + @installer.packages = list + end + end + +end # class ConfigTable + + +# This module requires: #verbose?, #no_harm? +module FileOperations + + def mkdir_p(dirname, prefix = nil) + dirname = prefix + File.expand_path(dirname) if prefix + $stderr.puts "mkdir -p #{dirname}" if verbose? + return if no_harm? + + # Does not check '/', it's too abnormal. + dirs = File.expand_path(dirname).split(%r<(?=/)>) + if /\A[a-z]:\z/i =~ dirs[0] + disk = dirs.shift + dirs[0] = disk + dirs[0] + end + dirs.each_index do |idx| + path = dirs[0..idx].join('') + Dir.mkdir path unless File.dir?(path) + end + end + + def rm_f(path) + $stderr.puts "rm -f #{path}" if verbose? + return if no_harm? + force_remove_file path + end + + def rm_rf(path) + $stderr.puts "rm -rf #{path}" if verbose? + return if no_harm? + remove_tree path + end + + def remove_tree(path) + if File.symlink?(path) + remove_file path + elsif File.dir?(path) + remove_tree0 path + else + force_remove_file path + end + end + + def remove_tree0(path) + Dir.foreach(path) do |ent| + next if ent == '.' + next if ent == '..' + entpath = "#{path}/#{ent}" + if File.symlink?(entpath) + remove_file entpath + elsif File.dir?(entpath) + remove_tree0 entpath + else + force_remove_file entpath + end + end + begin + Dir.rmdir path + rescue Errno::ENOTEMPTY + # directory may not be empty + end + end + + def move_file(src, dest) + force_remove_file dest + begin + File.rename src, dest + rescue + File.open(dest, 'wb') {|f| + f.write File.binread(src) + } + File.chmod File.stat(src).mode, dest + File.unlink src + end + end + + def force_remove_file(path) + begin + remove_file path + rescue + end + end + + def remove_file(path) + File.chmod 0777, path + File.unlink path + end + + def install(from, dest, mode, prefix = nil) + $stderr.puts "install #{from} #{dest}" if verbose? + return if no_harm? + + realdest = prefix ? prefix + File.expand_path(dest) : dest + realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) + str = File.binread(from) + if diff?(str, realdest) + verbose_off { + rm_f realdest if File.exist?(realdest) + } + File.open(realdest, 'wb') {|f| + f.write str + } + File.chmod mode, realdest + + File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| + if prefix + f.puts realdest.sub(prefix, '') + else + f.puts realdest + end + } + end + end + + def diff?(new_content, path) + return true unless File.exist?(path) + new_content != File.binread(path) + end + + def command(*args) + $stderr.puts args.join(' ') if verbose? + system(*args) or raise RuntimeError, + "system(#{args.map{|a| a.inspect }.join(' ')}) failed" + end + + def ruby(*args) + command config('rubyprog'), *args + end + + def make(task = nil) + command(*[config('makeprog'), task].compact) + end + + def extdir?(dir) + File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") + end + + def files_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.file?("#{dir}/#{ent}") } + } + end + + DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) + + def directories_of(dir) + Dir.open(dir) {|d| + return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT + } + end + +end + + +# This module requires: #srcdir_root, #objdir_root, #relpath +module HookScriptAPI + + def get_config(key) + @config[key] + end + + alias config get_config + + # obsolete: use metaconfig to change configuration + def set_config(key, val) + @config[key] = val + end + + # + # srcdir/objdir (works only in the package directory) + # + + def curr_srcdir + "#{srcdir_root()}/#{relpath()}" + end + + def curr_objdir + "#{objdir_root()}/#{relpath()}" + end + + def srcfile(path) + "#{curr_srcdir()}/#{path}" + end + + def srcexist?(path) + File.exist?(srcfile(path)) + end + + def srcdirectory?(path) + File.dir?(srcfile(path)) + end + + def srcfile?(path) + File.file?(srcfile(path)) + end + + def srcentries(path = '.') + Dir.open("#{curr_srcdir()}/#{path}") {|d| + return d.to_a - %w(. ..) + } + end + + def srcfiles(path = '.') + srcentries(path).select {|fname| + File.file?(File.join(curr_srcdir(), path, fname)) + } + end + + def srcdirectories(path = '.') + srcentries(path).select {|fname| + File.dir?(File.join(curr_srcdir(), path, fname)) + } + end + +end + + +class ToplevelInstaller + + Version = '3.4.1' + Copyright = 'Copyright (c) 2000-2005 Minero Aoki' + + TASKS = [ + [ 'all', 'do config, setup, then install' ], + [ 'config', 'saves your configurations' ], + [ 'show', 'shows current configuration' ], + [ 'setup', 'compiles ruby extentions and others' ], + [ 'install', 'installs files' ], + [ 'test', 'run all tests in test/' ], + [ 'clean', "does `make clean' for each extention" ], + [ 'distclean',"does `make distclean' for each extention" ] + ] + + def ToplevelInstaller.invoke + config = ConfigTable.new(load_rbconfig()) + config.load_standard_entries + config.load_multipackage_entries if multipackage? + config.fixup + klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) + klass.new(File.dirname($0), config).invoke + end + + def ToplevelInstaller.multipackage? + File.dir?(File.dirname($0) + '/packages') + end + + def ToplevelInstaller.load_rbconfig + if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } + ARGV.delete(arg) + load File.expand_path(arg.split(/=/, 2)[1]) + $".push 'rbconfig.rb' + else + require 'rbconfig' + end + ::Config::CONFIG + end + + def initialize(ardir_root, config) + @ardir = File.expand_path(ardir_root) + @config = config + # cache + @valid_task_re = nil + end + + def config(key) + @config[key] + end + + def inspect + "#<#{self.class} #{__id__()}>" + end + + def invoke + run_metaconfigs + case task = parsearg_global() + when nil, 'all' + parsearg_config + init_installers + exec_config + exec_setup + exec_install + else + case task + when 'config', 'test' + ; + when 'clean', 'distclean' + @config.load_savefile if File.exist?(@config.savefile) + else + @config.load_savefile + end + __send__ "parsearg_#{task}" + init_installers + __send__ "exec_#{task}" + end + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig" + end + + def init_installers + @installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + # + # Hook Script API bases + # + + def srcdir_root + @ardir + end + + def objdir_root + '.' + end + + def relpath + '.' + end + + # + # Option Parsing + # + + def parsearg_global + while arg = ARGV.shift + case arg + when /\A\w+\z/ + setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) + return arg + when '-q', '--quiet' + @config.verbose = false + when '--verbose' + @config.verbose = true + when '--help' + print_usage $stdout + exit 0 + when '--version' + puts "#{File.basename($0)} version #{Version}" + exit 0 + when '--copyright' + puts Copyright + exit 0 + else + setup_rb_error "unknown global option '#{arg}'" + end + end + nil + end + + def valid_task?(t) + valid_task_re() =~ t + end + + def valid_task_re + @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ + end + + def parsearg_no_options + unless ARGV.empty? + task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) + setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" + end + end + + alias parsearg_show parsearg_no_options + alias parsearg_setup parsearg_no_options + alias parsearg_test parsearg_no_options + alias parsearg_clean parsearg_no_options + alias parsearg_distclean parsearg_no_options + + def parsearg_config + evalopt = [] + set = [] + @config.config_opt = [] + while i = ARGV.shift + if /\A--?\z/ =~ i + @config.config_opt = ARGV.dup + break + end + name, value = *@config.parse_opt(i) + if @config.value_config?(name) + @config[name] = value + else + evalopt.push [name, value] + end + set.push name + end + evalopt.each do |name, value| + @config.lookup(name).evaluate value, @config + end + # Check if configuration is valid + set.each do |n| + @config[n] if @config.value_config?(n) + end + end + + def parsearg_install + @config.no_harm = false + @config.install_prefix = '' + while a = ARGV.shift + case a + when '--no-harm' + @config.no_harm = true + when /\A--prefix=/ + path = a.split(/=/, 2)[1] + path = File.expand_path(path) unless path[0,1] == '/' + @config.install_prefix = path + else + setup_rb_error "install: unknown option #{a}" + end + end + end + + def print_usage(out) + out.puts 'Typical Installation Procedure:' + out.puts " $ ruby #{File.basename $0} config" + out.puts " $ ruby #{File.basename $0} setup" + out.puts " # ruby #{File.basename $0} install (may require root privilege)" + out.puts + out.puts 'Detailed Usage:' + out.puts " ruby #{File.basename $0} <global option>" + out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" + + fmt = " %-24s %s\n" + out.puts + out.puts 'Global options:' + out.printf fmt, '-q,--quiet', 'suppress message outputs' + out.printf fmt, ' --verbose', 'output messages verbosely' + out.printf fmt, ' --help', 'print this message' + out.printf fmt, ' --version', 'print version and quit' + out.printf fmt, ' --copyright', 'print copyright and quit' + out.puts + out.puts 'Tasks:' + TASKS.each do |name, desc| + out.printf fmt, name, desc + end + + fmt = " %-24s %s [%s]\n" + out.puts + out.puts 'Options for CONFIG or ALL:' + @config.each do |item| + out.printf fmt, item.help_opt, item.description, item.help_default + end + out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" + out.puts + out.puts 'Options for INSTALL:' + out.printf fmt, '--no-harm', 'only display what to do if given', 'off' + out.printf fmt, '--prefix=path', 'install path prefix', '' + out.puts + end + + # + # Task Handlers + # + + def exec_config + @installer.exec_config + @config.save # must be final + end + + def exec_setup + @installer.exec_setup + end + + def exec_install + @installer.exec_install + end + + def exec_test + @installer.exec_test + end + + def exec_show + @config.each do |i| + printf "%-20s %s\n", i.name, i.value if i.value? + end + end + + def exec_clean + @installer.exec_clean + end + + def exec_distclean + @installer.exec_distclean + end + +end # class ToplevelInstaller + + +class ToplevelInstallerMulti < ToplevelInstaller + + include FileOperations + + def initialize(ardir_root, config) + super + @packages = directories_of("#{@ardir}/packages") + raise 'no package exists' if @packages.empty? + @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) + end + + def run_metaconfigs + @config.load_script "#{@ardir}/metaconfig", self + @packages.each do |name| + @config.load_script "#{@ardir}/packages/#{name}/metaconfig" + end + end + + attr_reader :packages + + def packages=(list) + raise 'package list is empty' if list.empty? + list.each do |name| + raise "directory packages/#{name} does not exist"\ + unless File.dir?("#{@ardir}/packages/#{name}") + end + @packages = list + end + + def init_installers + @installers = {} + @packages.each do |pack| + @installers[pack] = Installer.new(@config, + "#{@ardir}/packages/#{pack}", + "packages/#{pack}") + end + with = extract_selection(config('with')) + without = extract_selection(config('without')) + @selected = @installers.keys.select {|name| + (with.empty? or with.include?(name)) \ + and not without.include?(name) + } + end + + def extract_selection(list) + a = list.split(/,/) + a.each do |name| + setup_rb_error "no such package: #{name}" unless @installers.key?(name) + end + a + end + + def print_usage(f) + super + f.puts 'Inluded packages:' + f.puts ' ' + @packages.sort.join(' ') + f.puts + end + + # + # Task Handlers + # + + def exec_config + run_hook 'pre-config' + each_selected_installers {|inst| inst.exec_config } + run_hook 'post-config' + @config.save # must be final + end + + def exec_setup + run_hook 'pre-setup' + each_selected_installers {|inst| inst.exec_setup } + run_hook 'post-setup' + end + + def exec_install + run_hook 'pre-install' + each_selected_installers {|inst| inst.exec_install } + run_hook 'post-install' + end + + def exec_test + run_hook 'pre-test' + each_selected_installers {|inst| inst.exec_test } + run_hook 'post-test' + end + + def exec_clean + rm_f @config.savefile + run_hook 'pre-clean' + each_selected_installers {|inst| inst.exec_clean } + run_hook 'post-clean' + end + + def exec_distclean + rm_f @config.savefile + run_hook 'pre-distclean' + each_selected_installers {|inst| inst.exec_distclean } + run_hook 'post-distclean' + end + + # + # lib + # + + def each_selected_installers + Dir.mkdir 'packages' unless File.dir?('packages') + @selected.each do |pack| + $stderr.puts "Processing the package `#{pack}' ..." if verbose? + Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") + Dir.chdir "packages/#{pack}" + yield @installers[pack] + Dir.chdir '../..' + end + end + + def run_hook(id) + @root_installer.run_hook id + end + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + +end # class ToplevelInstallerMulti + + +class Installer + + FILETYPES = %w( bin lib ext data conf man ) + + include FileOperations + include HookScriptAPI + + def initialize(config, srcroot, objroot) + @config = config + @srcdir = File.expand_path(srcroot) + @objdir = File.expand_path(objroot) + @currdir = '.' + end + + def inspect + "#<#{self.class} #{File.basename(@srcdir)}>" + end + + def noop(rel) + end + + # + # Hook Script API base methods + # + + def srcdir_root + @srcdir + end + + def objdir_root + @objdir + end + + def relpath + @currdir + end + + # + # Config Access + # + + # module FileOperations requires this + def verbose? + @config.verbose? + end + + # module FileOperations requires this + def no_harm? + @config.no_harm? + end + + def verbose_off + begin + save, @config.verbose = @config.verbose?, false + yield + ensure + @config.verbose = save + end + end + + # + # TASK config + # + + def exec_config + exec_task_traverse 'config' + end + + alias config_dir_bin noop + alias config_dir_lib noop + + def config_dir_ext(rel) + extconf if extdir?(curr_srcdir()) + end + + alias config_dir_data noop + alias config_dir_conf noop + alias config_dir_man noop + + def extconf + ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt + end + + # + # TASK setup + # + + def exec_setup + exec_task_traverse 'setup' + end + + def setup_dir_bin(rel) + files_of(curr_srcdir()).each do |fname| + update_shebang_line "#{curr_srcdir()}/#{fname}" + end + end + + alias setup_dir_lib noop + + def setup_dir_ext(rel) + make if extdir?(curr_srcdir()) + end + + alias setup_dir_data noop + alias setup_dir_conf noop + alias setup_dir_man noop + + def update_shebang_line(path) + return if no_harm? + return if config('shebang') == 'never' + old = Shebang.load(path) + if old + $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 + new = new_shebang(old) + return if new.to_s == old.to_s + else + return unless config('shebang') == 'all' + new = Shebang.new(config('rubypath')) + end + $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? + open_atomic_writer(path) {|output| + File.open(path, 'rb') {|f| + f.gets if old # discard + output.puts new.to_s + output.print f.read + } + } + end + + def new_shebang(old) + if /\Aruby/ =~ File.basename(old.cmd) + Shebang.new(config('rubypath'), old.args) + elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' + Shebang.new(config('rubypath'), old.args[1..-1]) + else + return old unless config('shebang') == 'all' + Shebang.new(config('rubypath')) + end + end + + def open_atomic_writer(path, &block) + tmpfile = File.basename(path) + '.tmp' + begin + File.open(tmpfile, 'wb', &block) + File.rename tmpfile, File.basename(path) + ensure + File.unlink tmpfile if File.exist?(tmpfile) + end + end + + class Shebang + def Shebang.load(path) + line = nil + File.open(path) {|f| + line = f.gets + } + return nil unless /\A#!/ =~ line + parse(line) + end + + def Shebang.parse(line) + cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') + new(cmd, args) + end + + def initialize(cmd, args = []) + @cmd = cmd + @args = args + end + + attr_reader :cmd + attr_reader :args + + def to_s + "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") + end + end + + # + # TASK install + # + + def exec_install + rm_f 'InstalledFiles' + exec_task_traverse 'install' + end + + def install_dir_bin(rel) + install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 + end + + def install_dir_lib(rel) + install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 + end + + def install_dir_ext(rel) + return unless extdir?(curr_srcdir()) + install_files rubyextentions('.'), + "#{config('sodir')}/#{File.dirname(rel)}", + 0555 + end + + def install_dir_data(rel) + install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 + end + + def install_dir_conf(rel) + # FIXME: should not remove current config files + # (rename previous file to .old/.org) + install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 + end + + def install_dir_man(rel) + install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 + end + + def install_files(list, dest, mode) + mkdir_p dest, @config.install_prefix + list.each do |fname| + install fname, dest, mode, @config.install_prefix + end + end + + def libfiles + glob_reject(%w(*.y *.output), targetfiles()) + end + + def rubyextentions(dir) + ents = glob_select("*.#{@config.dllext}", targetfiles()) + if ents.empty? + setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" + end + ents + end + + def targetfiles + mapdir(existfiles() - hookfiles()) + end + + def mapdir(ents) + ents.map {|ent| + if File.exist?(ent) + then ent # objdir + else "#{curr_srcdir()}/#{ent}" # srcdir + end + } + end + + # picked up many entries from cvs-1.11.1/src/ignore.c + JUNK_FILES = %w( + core RCSLOG tags TAGS .make.state + .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb + *~ *.old *.bak *.BAK *.orig *.rej _$* *$ + + *.org *.in .* + ) + + def existfiles + glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) + end + + def hookfiles + %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| + %w( config setup install clean ).map {|t| sprintf(fmt, t) } + }.flatten + end + + def glob_select(pat, ents) + re = globs2re([pat]) + ents.select {|ent| re =~ ent } + end + + def glob_reject(pats, ents) + re = globs2re(pats) + ents.reject {|ent| re =~ ent } + end + + GLOB2REGEX = { + '.' => '\.', + '$' => '\$', + '#' => '\#', + '*' => '.*' + } + + def globs2re(pats) + /\A(?:#{ + pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') + })\z/ + end + + # + # TASK test + # + + TESTDIR = 'test' + + def exec_test + unless File.directory?('test') + $stderr.puts 'no test in this package' if verbose? + return + end + $stderr.puts 'Running tests...' if verbose? + begin + require 'test/unit' + rescue LoadError + setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' + end + runner = Test::Unit::AutoRunner.new(true) + runner.to_run << TESTDIR + runner.run + end + + # + # TASK clean + # + + def exec_clean + exec_task_traverse 'clean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias clean_dir_bin noop + alias clean_dir_lib noop + alias clean_dir_data noop + alias clean_dir_conf noop + alias clean_dir_man noop + + def clean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'clean' if File.file?('Makefile') + end + + # + # TASK distclean + # + + def exec_distclean + exec_task_traverse 'distclean' + rm_f @config.savefile + rm_f 'InstalledFiles' + end + + alias distclean_dir_bin noop + alias distclean_dir_lib noop + + def distclean_dir_ext(rel) + return unless extdir?(curr_srcdir()) + make 'distclean' if File.file?('Makefile') + end + + alias distclean_dir_data noop + alias distclean_dir_conf noop + alias distclean_dir_man noop + + # + # Traversing + # + + def exec_task_traverse(task) + run_hook "pre-#{task}" + FILETYPES.each do |type| + if type == 'ext' and config('without-ext') == 'yes' + $stderr.puts 'skipping ext/* by user option' if verbose? + next + end + traverse task, type, "#{task}_dir_#{type}" + end + run_hook "post-#{task}" + end + + def traverse(task, rel, mid) + dive_into(rel) { + run_hook "pre-#{task}" + __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') + directories_of(curr_srcdir()).each do |d| + traverse task, "#{rel}/#{d}", mid + end + run_hook "post-#{task}" + } + end + + def dive_into(rel) + return unless File.dir?("#{@srcdir}/#{rel}") + + dir = File.basename(rel) + Dir.mkdir dir unless File.dir?(dir) + prevdir = Dir.pwd + Dir.chdir dir + $stderr.puts '---> ' + rel if verbose? + @currdir = rel + yield + Dir.chdir prevdir + $stderr.puts '<--- ' + rel if verbose? + @currdir = File.dirname(rel) + end + + def run_hook(id) + path = [ "#{curr_srcdir()}/#{id}", + "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } + return unless path + begin + instance_eval File.read(path), path, 1 + rescue + raise if $DEBUG + setup_rb_error "hook #{path} failed:\n" + $!.message + end + end + +end # class Installer + + +class SetupError < StandardError; end + +def setup_rb_error(msg) + raise SetupError, msg +end + +if $0 == __FILE__ + begin + ToplevelInstaller.invoke + rescue SetupError + raise if $DEBUG + $stderr.puts $!.message + $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." + exit 1 + end +end diff --git a/test/subdir/result.xsl b/test/subdir/result.xsl new file mode 100644 index 0000000..49abfbd --- /dev/null +++ b/test/subdir/result.xsl @@ -0,0 +1,3 @@ +<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> + <xsl:template name="result">PASS</xsl:template> +</xsl:stylesheet> diff --git a/test/subdir/test.xsl b/test/subdir/test.xsl new file mode 100644 index 0000000..35f567e --- /dev/null +++ b/test/subdir/test.xsl @@ -0,0 +1,8 @@ +<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> + <xsl:import href="result.xsl"/> + <xsl:output omit-xml-declaration="yes"/> + + <xsl:template match="/"> + <xsl:call-template name="result"/> + </xsl:template> +</xsl:stylesheet> diff --git a/test/t.xml b/test/t.xml new file mode 100644 index 0000000..3ab643c --- /dev/null +++ b/test/t.xml @@ -0,0 +1,2 @@ +<?xml version="1.0" encoding="UTF-8"?> +<test>This is a test file</test> diff --git a/test/t.xsl b/test/t.xsl new file mode 100644 index 0000000..fd4e724 --- /dev/null +++ b/test/t.xsl @@ -0,0 +1,6 @@ +<?xml version="1.0" ?> +<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> + <xsl:template match="/"> + <xsl:apply-templates /> + </xsl:template> +</xsl:stylesheet> diff --git a/test/test.rb b/test/test.rb new file mode 100644 index 0000000..bc126e6 --- /dev/null +++ b/test/test.rb @@ -0,0 +1,196 @@ +#!ruby + +require "test/unit" + +require "rubygems" +require "xml/xslt" + +EXT_FUNC_XSL =<<END +<xsl:stylesheet + xmlns:xsl="http://www.w3.org/1999/XSL/Transform" + xmlns:ext="http://necronomicorp.com/nil" + version="1.0"> + +<xsl:template match="/"> + <xsl:value-of select="ext:foo()"/> +</xsl:template> + +</xsl:stylesheet> +END + +class XsltTest < Test::Unit::TestCase + def setup + @xslt = XML::XSLT.new( ) + + @testOut = "<?xml version=\"1.0\"?>\nThis is a test file\n" + + @errors = [] + XML::XSLT.registerErrorHandler { |s| @errors << s } + end + + def test_instance + assert_instance_of( XML::XSLT, @xslt ) + end + + def test_from_file + @xslt.xml = "t.xml" + @xslt.xsl = "t.xsl" + + out = @xslt.serve + assert_equal( @testOut, out ) + assert_equal( [], @errors ) + end + + def test_from_data + @xslt.xml = File.read( "t.xml" ) + @xslt.xsl = File.read( "t.xsl" ) + + out = @xslt.serve + assert_equal( @testOut, out ) + assert_equal( [], @errors ) + end + + def test_from_simple + begin + require "xml/simple" + + @xslt.xml = XML::Simple.open( "t.xml" ) + @xslt.xsl = XML::Simple.open( "t.xsl" ) + + out = @xslt.serve() + assert_equal( @testOut, out ) + assert_equal( [], @errors ) + rescue LoadError => e + # just skip it + end + end + + def test_from_smart + begin + require "xml/smart" + + @xslt.xml = XML::Smart.open( "t.xml" ) + @xslt.xsl = XML::Smart.open( "t.xsl" ) + + out = @xslt.serve() + assert_equal( @testOut, out ) + assert_equal( [], @errors ) + rescue LoadError => e + # just skip it + end + end + + def test_from_rexml + require 'rexml/document' + @xslt.xml = REXML::Document.new File.read( "t.xml" ) + @xslt.xsl = REXML::Document.new File.read( "t.xsl" ) + + out = @xslt.serve() + assert_equal( [], @errors ) + assert_equal( @testOut, out ) + end + + def test_error_1 + assert_raises(XML::XSLT::ParsingError) do + @xslt.xsl = "nil" + end + + errors = ["Entity: line 1: ", + "parser ", + "error : ", + "Start tag expected, '<' not found\n", + "nil\n", + "^\n"] + + assert_equal( errors, @errors ) + end + + def test_error_2 + assert_raises(XML::XSLT::ParsingError) do + @xslt.xml = "nil" + end + + errors = ["Entity: line 1: ", + "parser ", + "error : ", + "Start tag expected, '<' not found\n", + "nil\n", + "^\n"] + + assert_equal( errors, @errors ) + end + +# this test fails (any reason that it *should* raise an error?) +=begin + def test_error_3 + assert_raises(XML::XSLT::ParsingError) do + @xslt.xml = "t.xsl" + end + end +=end + + def test_transformation_error + @xslt.xml = "<test/>" + # substitute so that the function is guaranteed to not be registered + @xslt.xsl = EXT_FUNC_XSL.sub( /foo/, "bar") + + assert_raises(XML::XSLT::TransformationError) do + @xslt.serve + end + + errors = ["xmlXPathCompOpEval: function bar not found\n", + "Unregistered function\n", + "xmlXPathCompiledEval: evaluation failed\n", + "runtime error: element value-of\n", + "xsltValueOf: text copy failed\n"] + assert_equal(errors, @errors) + end + + def test_external_function + @xslt.xml = "<test/>" + @xslt.xsl = EXT_FUNC_XSL + + XML::XSLT.registerExtFunc("http://necronomicorp.com/nil", "foo") do + "success!" + end + + assert_equal("<?xml version=\"1.0\"?>\nsuccess!\n", @xslt.serve()) + assert_equal([], @errors) + end + + def test_base_uri_1 + @xslt.xml = "<test/>" + xsl = "subdir/test.xsl" + + # the base URI of a loaded XSL file should be the URI of that file + assert_nothing_raised( XML::XSLT::ParsingError ) do + @xslt.xsl = xsl + end + + assert_equal( [], @errors ) + end + + def test_base_uri_2 + @xslt.xml = "<test/>" + xsl = File.read("subdir/test.xsl") + + # a file loaded from memory has no base URI, so this should fail + assert_raises( XML::XSLT::ParsingError ) do + @xslt.xsl = xsl + end + + errors = ["I/O ", + "warning : ", + "failed to load external entity \"result.xsl\"\n", + "compilation error: element import\n", + "xsl:import : unable to load result.xsl\n"] + + assert_equal( errors, @errors ) + end + + def test_alias + assert_nothing_raised do + XML::XSLT.register_ext_func("http://necronomicorp.com/nil", "nil") {} + end + end +end
LightGuard/seam-git-migration
0bd599ceee4c7c338d1bf44dbe9bea0340907942
First draft of groovy script (for real this time)
diff --git a/seam_git_migration.groovy b/seam_git_migration.groovy old mode 100644 new mode 100755 index 47ac498..198b04c --- a/seam_git_migration.groovy +++ b/seam_git_migration.groovy @@ -1,83 +1,179 @@ +#!/usr/bin/env groovy + // Go grab Groosh so we can do standard shell commands (http://groovy.codehaus.org/Groosh) @Grapes([ - @Grab(group='org.codehaus.groovy.modules', module='groosh', version='[0.3.5,)'), + @Grab(group='org.codehaus.groovy.modules', module='groosh', version='0.3.6'), @GrabConfig(systemClassLoader=true) ]) -import static groosh.Groosh.groosh - -def shell = groosh() - -def phase1_dir = 'import-phase1' -shell.mkdir(phase1_dir) -def phase2_dir = 'import-phase2' -shell.mkdir(phase2_dir) - -shell.cd(phase1_dir) +import groosh.Groosh +Groosh.withGroosh(this) // Groosh sends out put to an output stream, but XmlSlurper needs an input stream, so using Piped streams and another thread to grab all the modules def _in = new PipedInputStream() def out = new PipedOutputStream(_in) +// git repositories seeded from svn +def phase1_dir = new File('test-import-phase1') +// fresh git clones of migrated svn repositories +def phase2_dir = new File('test-import-phase2') + +// perhaps commandline arguments? +def phase1 = true +def phase2 = true + Thread.start { - shell.svn('list', '--xml', 'http://anonsvn.jboss.org/repos/seam/modules/').toStream(out) + svn('list', '--xml', 'http://anonsvn.jboss.org/repos/seam/modules/').toStream(out) +} + +def modules = new XmlSlurper().parse(_in).list.entry.name.collect { it.text() } +def others = ['parent', 'dist', 'examples'] + +// testing overrides +//modules = ['faces'] +//others = ['parent'] + +if (phase1) { + + phase1_dir.mkdir() + cd(phase1_dir) + + + modules.each { m -> + clone_svn_repo(m, '/modules', m == 'wicket' ? false : true) + } + + others.each { o -> + clone_svn_repo(o, '/', o == 'parent' ? true : false) + } + + cd('..') + +} + +if (phase2) { + phase2_dir.mkdir() + cd(phase2_dir) + + modules.each { m -> + clone_git_repo("../$phase1_dir", m) + } + + others.each { o -> + clone_git_repo("../$phase1_dir", o) + } + + update_scm_urls(phase2_dir) +} + +def clone_svn_repo(name, context, pull_tags) { + def svn_uri = "http://anonsvn.jboss.org/repos/seam$context/$name" + def trunk = 'trunk' + if (name == 'parent') { + trunk += '/parent' + } + if (pull_tags) { + git('svn', 'clone', svn_uri, '--no-metadata', '--no-minimize-url', "--trunk=$trunk", '--tags=tags', '--authors-file=../../svn.authors') >> stdout + } + else { + git('svn', 'clone', svn_uri, '--no-metadata', '--no-minimize-url', "--trunk=$trunk", '--authors-file=../../svn.authors') >> stdout + } + if (pull_tags) { + fix_tags(name) + } + cd(name) + //shell.git('reflog', 'expire', '--all', '--expire=now') + git('gc') >> stdout + //shell.git('prune') + //shell.git('fsck', '--full') + cd('..') } -def modules = XmlSlurper().parse(_in).list.entry.name.collect { it.text() } -['parent', 'dist'].each { modules << it} - -modules.each { - - shell.mkdir('-p', it) - shell.cd(it) -/* - if (it == 'wicket') - git_clone(false) - else - git_clone() - convert_tags() - git_clean() -*/ - shell.cd("../${phase2_dir}") -/* - git_clone_push(it) // TODO: add conditions -*/ +def clone_git_repo(root, repo) { + git('clone', "$root/$repo").waitForExit() + def github_module = repo + if (repo == 'remoting') { + github_module = 'js-remoting' + } + else if (repo == 'xml') { + github_module = 'xml-config' + } + cd(repo) + git('remote', 'add', 'github', "[email protected]:seam/${github_module}.git").waitForExit() + git('remote', '-v') >> stdout + //git('push', 'github', 'master') + cd('..') } -def git_clone(includeTags = true ) -{ - def args = ['svn', 'clone', "http://anonsvn.jboss.org/repos/seam/modules/${it}", '--no-metadata', '--no-minimize-url', '--trunk', '--tags', '--authors-file=../../svn.authors'] +def fix_tags(repo) { + cd(repo) + git('for-each-ref', '--format=%(refname)', 'refs/remotes/tags/*').eachLine { tag_ref -> + def tag = tag_ref.minus('refs/remotes/tags/') + def tree = parse_rev("$tag_ref:", false) + def parent_ref = tag_ref + while (parse_rev("$parent_ref^:", true) == tree) { + parent_ref = "$parent_ref^" + } + def parent = parse_rev(parent_ref, false) + def merge = git('merge-base', 'refs/remotes/trunk', parent).text.trim() + def target_ref + if (merge == parent) { + target_ref = parent + println "$tag references master branch" + } + else { + target_ref = tag_ref + println "$tag has diverged from the master branch" + } + + println "$tag revision = $target_ref" + // TODO be sure to unset these before the push + def env = groosh.getCurrentEnvironment() + env.put('GIT_COMMITTER_NAME', log_meta(tag_ref, '%an')) + env.put('GIT_COMMITTER_EMAIL', log_meta(tag_ref, '%ae')) + env.put('GIT_COMMITTER_DATE', log_meta(tag_ref, '%ai')) + pipe_meta(tag_ref, '%s') | git('tag', '-a', '-F', '-', tag, target_ref) + git('update-ref', '-d', tag_ref) + } + cd('..') +} - if (!includeTags) - args - '--tags' - - shell.git(args).waitForExit() +def parse_rev(ref, verify) { + if (verify) { + return git('rev-parse', '--quiet', '--verify', ref).text.trim() + } + return git('rev-parse', ref).text.trim() } -def git_clean() -{ - shell.git('reflog', 'expire', '--all', '--expire=now') - shell.git('gc', '--aggressive') - shell.git('prune') - shell.git('fsck', '--full') +def log_meta(tag_ref, symbol) { + return pipe_meta(tag_ref, symbol).text.trim() } -def convert_tags() { - shell.git('for-each-ref', "--format='%(refname)'", "refs/remotes/tags").eachLine { - tag = it - 'refs/remots/' - tree = shell.git('rev-parse', it).text - - // TODO: finish fix_tags from old script - } -} - -def git_clone_push(module, newName = moduleName) -{ - shell.git('clone', "../${phase1_dir}/${module}", newName) - shell.cd(module) - shell.git('remote', 'add', 'github', "[email protected]:seam/${newName}.git") - shell.git('remote', '-v') - shell.git('push', '--mirror', 'github', 'master') +def pipe_meta(tag_ref, symbol) { + return git('log', '-1', "--pretty=\"format:$symbol\"", tag_ref) } -// vim:ts=4:sw=4:sts=4 +def modifyFile(file, Closure processText) { + def text = file.text + file.write(processText(text)) +} + +def update_scm_urls(rootDir) { + rootDir.eachFileRecurse({ f -> + if (f.file && f.name ==~ /^(readme.txt|pom\.xml$)/) { + modifyFile(f, { text -> + text = (text =~ /http:\/\/anonsvn\.jboss\.org\/repos\/(weld|seam\/modules)\/([a-z]+)(\/[a-z]*)*/).replaceAll('git://github.com/seam/$2.git') + text = (text =~ /https:\/\/svn\.jboss\.org\/repos\/(weld|seam\/modules)\/([a-z]+)(\/[a-z]*)*/).replaceAll('[email protected]:seam/$2.git') + text = text.replaceAll(/github\.com(:|\/)seam\/remoting/, 'github.com$1seam/js-remoting') + text = text.replaceAll(/github\.com(:|\/)seam\/xml/, 'github.com$1seam/xml-config') + text = (text =~ /http:\/\/fisheye\.jboss\.org\/browse\/(([Ss]eam\/)+modules|weld)\/([a-z]+)(\/[a-z]*)*/).replaceAll('http://github.com/seam/$3') + text = (text =~ /http:\/\/anonsvn\.jboss\.org\/repos\/seam\/([a-z]+\/)*(parent|examples|dist)(\/trunk(\/[a-z\-]*)?)?/).replaceAll('git://github.com/seam/$2.git') + text = (text =~ /https:\/\/svn\.jboss\.org\/repos\/seam\/([a-z]+\/)*(parent|examples|dist)(\/trunk(\/[a-z\-]*)?)?/).replaceAll('[email protected]:seam/$2.git') + text = text.replaceAll(/http:\/\/fisheye\.jboss\.org\/browse\/[Ss]eam(\/[a-z\-]*)*/, "http://github.com/seam") + text = text.replaceAll("http://anonsvn.jboss.org/repos/seam", "http://github.com/seam") + return text + }) + } + }) + // TODO commit modified files +}
LightGuard/seam-git-migration
b4e45bffb185a5ffd8a2e742f54641da35754a90
initial import of worklog (todo list)
diff --git a/WORKLOG b/WORKLOG new file mode 100644 index 0000000..3cd1349 --- /dev/null +++ b/WORKLOG @@ -0,0 +1,7 @@ +TODO: +---- +- commit changes to files with updated scm urls +- fork mail module from cody +- fork sidekick from lincoln +- grab scheduling from sandbox +- grab spreadsheets from sandbox?
LightGuard/seam-git-migration
544e386bc7b10d0c9b0b1765eb0587546949e65f
first draft of sh to groovy translation of script
diff --git a/seam-svn2git-migration.sh b/seam-svn2git-migration.sh new file mode 100755 index 0000000..3073aef --- /dev/null +++ b/seam-svn2git-migration.sh @@ -0,0 +1,153 @@ +#!/bin/bash + +# Program locations +xmlstarlet=/usr/bin/xmlstarlet +git=/usr/bin/git + +phase1_dir=import-phase1 +phase2_dir=import-phase2 +get_modules=$(svn list --xml http://anonsvn.jboss.org/repos/seam/modules/ | xmlstarlet sel -T -t -m "//name" -c . -n) +get_parent=1 +get_examples=1 +get_dist=1 + +fix_tags() +{ + # Convert svn remote tags to lightweight git tags + $git for-each-ref --format='%(refname)' refs/remotes/tags/* | while read tag_ref; do + tag=${tag_ref#refs/remotes/tags/} + tree=$( $git rev-parse "$tag_ref": ) + + # find the oldest ancestor for which the tree is the same + parent_ref="$tag_ref"; + while [ $( $git rev-parse --quiet --verify "$parent_ref"^: ) = "$tree" ]; do + parent_ref="$parent_ref"^ + done + parent=$( $git rev-parse "$parent_ref" ); + + # if this ancestor is in trunk then we can just tag it + # otherwise the tag has diverged from trunk and it's actually more like a + # branch than a tag + merge=$( $git merge-base "refs/remotes/trunk" $parent ); + if [ "$merge" = "$parent" ]; then + target_ref=$parent + else + echo "tag has diverged: $tag" + target_ref="$tag_ref" + fi + target_ref=$parent + + tag_name=$( $git log -1 --pretty="format:%an" "$tag_ref" ) + tag_email=$( $git log -1 --pretty="format:%ae" "$tag_ref" ) + tag_date=$( $git log -1 --pretty="format:%ai" "$tag_ref" ) + $git log -1 --pretty='format:%s' "$tag_ref" | GIT_COMMITTER_NAME="$tag_name" GIT_COMMITTER_EMAIL="$tag_email" GIT_COMMITTER_DATE="$tag_date" $git tag -a -F - "$tag" "$target_ref" + + $git update-ref -d "$tag_ref" + done +} + +mkdir -p $phase1_dir +cd $phase1_dir + +# Partial execution override +#get_modules=() +#get_parent=0 +#get_dist=0 +#get_examples=0 + +if [[ $get_parent -eq 1 ]]; then + # The parent needs to be handled as a special case because its tags are in a non-standard relative location + mkdir -p parent + cd parent + # Don't use -s as we want to drop any branches + $git svn init http://anonsvn.jboss.org/repos/seam/build --no-metadata --no-minimize-url --trunk=trunk/parent --tags=tags + $git config svn.authorsfile ../../svn.authors + $git svn fetch + fix_tags + $git gc + cd .. +fi + +if [[ $get_dist -eq 1 ]]; then + mkdir -p dist + cd dist + # Don't use -s as we want to drop any branches + $git svn init http://anonsvn.jboss.org/repos/seam/dist --no-metadata --no-minimize-url --trunk=trunk + $git config svn.authorsfile ../../svn.authors + $git svn fetch + $git gc + cd .. +fi + +if [[ $get_examples -eq 1 ]]; then + mkdir -p examples + cd examples + # Don't use -s as we want to drop any branches + $git svn init http://anonsvn.jboss.org/repos/seam/examples --no-metadata --no-minimize-url --trunk=trunk + $git config svn.authorsfile ../../svn.authors + $git svn fetch + $git gc + cd .. +fi + +for module in ${get_modules[@]}; do + mkdir -p $module + cd $module + # Don't use -s as we want to drop any branches + if [ "$module" = "wicket" ]; then + # Skip wicket tags (since they are not descendants of the trunk) + $git svn init http://anonsvn.jboss.org/repos/seam/modules/$module --no-metadata --no-minimize-url --trunk=trunk + else + $git svn init http://anonsvn.jboss.org/repos/seam/modules/$module --no-metadata --no-minimize-url --trunk=trunk --tags=tags + fi + $git config svn.authorsfile ../../svn.authors + $git svn fetch + fix_tags + $git gc + cd .. +done + +cd .. + +mkdir -p $phase2_dir +cd $phase2_dir + +if [[ $get_parent -eq 1 ]]; then + $git clone ../$phase1_dir/parent + cd parent + $git remote add github [email protected]:seam/parent.git + $git remote -v + cd .. +fi + +if [[ $get_dist -eq 1 ]]; then + $git clone ../$phase1_dir/dist + cd dist + $git remote add github [email protected]:seam/dist.git + $git remote -v + cd .. +fi + +if [[ $get_examples -eq 1 ]]; then + $git clone ../$phase1_dir/examples + cd examples + $git remote add github [email protected]:seam/examples.git + $git remote -v + cd .. +fi + +for module in ${get_modules[@]}; do + $git clone ../$phase1_dir/$module + if [ "$module" = "remoting" ]; then + github_module="js-remoting" + elif [ "$module" = "xml" ]; then + github_module="xml-config" + else + github_module="$module" + fi + cd $module + $git remote add github [email protected]:seam/$github_module.git + $git remote -v + #$git push github master + cd .. +done
LightGuard/seam-git-migration
33d16f73c9bd4a16ed11f5471b141cb44fc4bf0f
Continuing with script port
diff --git a/seam_git_migration.groovy b/seam_git_migration.groovy index 0b30949..47ac498 100644 --- a/seam_git_migration.groovy +++ b/seam_git_migration.groovy @@ -1,48 +1,83 @@ // Go grab Groosh so we can do standard shell commands (http://groovy.codehaus.org/Groosh) @Grapes([ @Grab(group='org.codehaus.groovy.modules', module='groosh', version='[0.3.5,)'), @GrabConfig(systemClassLoader=true) ]) import static groosh.Groosh.groosh def shell = groosh() def phase1_dir = 'import-phase1' shell.mkdir(phase1_dir) def phase2_dir = 'import-phase2' shell.mkdir(phase2_dir) shell.cd(phase1_dir) // Groosh sends out put to an output stream, but XmlSlurper needs an input stream, so using Piped streams and another thread to grab all the modules def _in = new PipedInputStream() def out = new PipedOutputStream(_in) Thread.start { shell.svn('list', '--xml', 'http://anonsvn.jboss.org/repos/seam/modules/').toStream(out) } -new XmlSlurper().parse(_in).list.entry.name.collect { it.text() }.each { +def modules = XmlSlurper().parse(_in).list.entry.name.collect { it.text() } +['parent', 'dist'].each { modules << it} + +modules.each { shell.mkdir('-p', it) shell.cd(it) /* if (it == 'wicket') - shell.git('svn', 'clone', "http://anonsvn.jboss.org/repos/seam/modules/${it}", '--no-metadata', '--no-minimize-url', '--trunk', '--tags', '--authors-file=../../svn.authors').waitForExit() + git_clone(false) else - shell.git('svn', 'clone', "http://anonsvn.jboss.org/repos/seam/modules/${it}", '--no-metadata', '--no-minimize-url', '--trunk', '--authors-file=../../svn.authors').waitForExit() -*/ - fix_tags() + git_clone() + convert_tags() + git_clean() +*/ + shell.cd("../${phase2_dir}") /* + git_clone_push(it) // TODO: add conditions +*/ +} + +def git_clone(includeTags = true ) +{ + def args = ['svn', 'clone', "http://anonsvn.jboss.org/repos/seam/modules/${it}", '--no-metadata', '--no-minimize-url', '--trunk', '--tags', '--authors-file=../../svn.authors'] + + if (!includeTags) + args - '--tags' + + shell.git(args).waitForExit() +} + +def git_clean() +{ shell.git('reflog', 'expire', '--all', '--expire=now') shell.git('gc', '--aggressive') shell.git('prune') shell.git('fsck', '--full') -*/ - shell.cd('..') } -def fix_tags() { +def convert_tags() { + shell.git('for-each-ref', "--format='%(refname)'", "refs/remotes/tags").eachLine { + tag = it - 'refs/remots/' + tree = shell.git('rev-parse', it).text + + // TODO: finish fix_tags from old script + } +} + +def git_clone_push(module, newName = moduleName) +{ + shell.git('clone', "../${phase1_dir}/${module}", newName) + shell.cd(module) + shell.git('remote', 'add', 'github', "[email protected]:seam/${newName}.git") + shell.git('remote', '-v') + shell.git('push', '--mirror', 'github', 'master') +} -} \ No newline at end of file +// vim:ts=4:sw=4:sts=4
LightGuard/seam-git-migration
71487c1a2e4c6db825666fc5337ce57309165135
Adding .gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c6ebdd6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +import-phase1 +import-phase2
itxiaozi/zzror
43e3291015c50b7d0ef8a7fafd0be4d46809c482
add ce-shi-zhong-wen.txt
diff --git a/articles/2010-10-13-ce-shi-zhong-wen.txt b/articles/2010-10-13-ce-shi-zhong-wen.txt new file mode 100644 index 0000000..c7bce56 --- /dev/null +++ b/articles/2010-10-13-ce-shi-zhong-wen.txt @@ -0,0 +1,7 @@ +--- +title: "\xE6\xB5\x8B\xE8\xAF\x95\xE4\xB8\xAD\xE6\x96\x87" +slug: ce-shi-zhong-wen +date: 13/10/2010 + +测试中文,参考 +
itxiaozi/zzror
c5f974afc73d5cdd6ddb5f87d96b73b969778046
edit Rakefile
diff --git a/Rakefile b/Rakefile index 755a103..567b906 100644 --- a/Rakefile +++ b/Rakefile @@ -1,42 +1,42 @@ require 'toto' @config = Toto::Config::Defaults task :default => :new desc "Create a new article." task :new do title = ask('Title: ') slug = title.empty?? nil : title.strip.slugize - article = {'title' => title, 'date' => Time.now.strftime("%d/%m/%Y")}.to_yaml + article = {'title' => title, 'slug' => slug,'date' => Time.now.strftime("%d/%m/%Y")}.to_yaml article << "\n" article << "Once upon a time...\n\n" path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}#{'-' + slug if slug}.#{@config[:ext]}" unless File.exist? path File.open(path, "w") do |file| file.write article end toto "an article was created for you at #{path}." else toto "I can't create the article, #{path} already exists." end end desc "Publish my blog." task :publish do toto "publishing your article(s)..." `git push heroku master` end def toto msg puts "\n toto ~ #{msg}\n\n" end def ask message print message STDIN.gets.chomp end diff --git a/articles/2010-10-13-toto-heroku.txt b/articles/2010-10-13-toto-heroku.txt index d296508..169067f 100644 --- a/articles/2010-10-13-toto-heroku.txt +++ b/articles/2010-10-13-toto-heroku.txt @@ -1,5 +1,6 @@ +slug:toto-heroku title: 搭建toto+heroku轻量级博客系统 author: 我不累,真的不累 date: 2010/10/13 记录搭建toto+heroku轻量级博客系统过程,备忘。
itxiaozi/zzror
115b60bc059f7661f078c2f2e6b94f8a67e66332
edit 2010-10-13-toto-heroku.txt
diff --git a/articles/2010-10-13-toto-heroku.txt b/articles/2010-10-13-toto-heroku.txt index 1b40635..d296508 100644 --- a/articles/2010-10-13-toto-heroku.txt +++ b/articles/2010-10-13-toto-heroku.txt @@ -1,12 +1,5 @@ title: 搭建toto+heroku轻量级博客系统 author: 我不累,真的不累 date: 2010/10/13 记录搭建toto+heroku轻量级博客系统过程,备忘。 - - gem install heroku - git clone git://github.com/cloudhead/dorothy.git zzror - cd zzror - heroku create - -
itxiaozi/zzror
2be5cabc90601a9613ff3186ec0ca3c2c29751b8
edit 2010-10-13-toto-heroku.txt
diff --git a/articles/2010-10-13-toto-heroku.txt b/articles/2010-10-13-toto-heroku.txt index c1df116..1b40635 100644 --- a/articles/2010-10-13-toto-heroku.txt +++ b/articles/2010-10-13-toto-heroku.txt @@ -1,30 +1,12 @@ title: 搭建toto+heroku轻量级博客系统 author: 我不累,真的不累 date: 2010/10/13 记录搭建toto+heroku轻量级博客系统过程,备忘。 gem install heroku git clone git://github.com/cloudhead/dorothy.git zzror cd zzror heroku create -heroku create会返回一个类似 http://xxx.heroku.com 的网址,在文件config.ru中的Toto::Server.new block中追加set :url, 'http://xxx.heroku.com' - - git commit -am "Added URL" - git push heroku master - -如果还没有ssh-key,可以用` ssh-keygen -C [email protected] -t rsa` 命令来生成一个。 - -在heroku中修改应用名字xxx为zzror,修改后执行下面操作: - - git remote rm heroku - git remote add heroku [email protected]:zzror.git - -接着修改config.ru中的url,修改后执行 - - git commit -am "Modified URL" - git push heroku master - -
itxiaozi/zzror
cd2c37069f4ce083fa913d6b0c9a8386206f52a3
edit 2010-10-13-toto-heroku.txt
diff --git a/articles/2010-10-13-toto-heroku.txt b/articles/2010-10-13-toto-heroku.txt index 7ee01d8..c1df116 100644 --- a/articles/2010-10-13-toto-heroku.txt +++ b/articles/2010-10-13-toto-heroku.txt @@ -1,28 +1,30 @@ title: 搭建toto+heroku轻量级博客系统 author: 我不累,真的不累 date: 2010/10/13 记录搭建toto+heroku轻量级博客系统过程,备忘。 gem install heroku git clone git://github.com/cloudhead/dorothy.git zzror cd zzror heroku create - # heroku create会返回一个类似 http://xxx.heroku.com 的网址,在文件config.ru中的Toto::Server.new block中追加 - # set :url, 'http://xxx.heroku.com' + + +heroku create会返回一个类似 http://xxx.heroku.com 的网址,在文件config.ru中的Toto::Server.new block中追加set :url, 'http://xxx.heroku.com' + git commit -am "Added URL" git push heroku master -如果还没有ssh-key,可以用 ssh-keygen -C '[email protected]' -t rsa 命令来生成一个。 +如果还没有ssh-key,可以用` ssh-keygen -C [email protected] -t rsa` 命令来生成一个。 在heroku中修改应用名字xxx为zzror,修改后执行下面操作: git remote rm heroku git remote add heroku [email protected]:zzror.git 接着修改config.ru中的url,修改后执行 git commit -am "Modified URL" git push heroku master -[toto文档](http://github.com/cloudhead/toto) +
itxiaozi/zzror
9d31764929e48a88b38c2d598474a302fc85efc0
edit 2010-10-13-toto-heroku.txt
diff --git a/articles/2010-10-13-toto-heroku.txt b/articles/2010-10-13-toto-heroku.txt index ab951f8..7ee01d8 100644 --- a/articles/2010-10-13-toto-heroku.txt +++ b/articles/2010-10-13-toto-heroku.txt @@ -1,28 +1,28 @@ title: 搭建toto+heroku轻量级博客系统 author: 我不累,真的不累 date: 2010/10/13 记录搭建toto+heroku轻量级博客系统过程,备忘。 -gem install heroku -git clone git://github.com/cloudhead/dorothy.git zzror -cd zzror -heroku create -# heroku create会返回一个类似 http://xxx.heroku.com 的网址,在文件config.ru中的Toto::Server.new block中追加 -# set :url, 'http://xxx.heroku.com' -git commit -am "Added URL" -git push heroku master + gem install heroku + git clone git://github.com/cloudhead/dorothy.git zzror + cd zzror + heroku create + # heroku create会返回一个类似 http://xxx.heroku.com 的网址,在文件config.ru中的Toto::Server.new block中追加 + # set :url, 'http://xxx.heroku.com' + git commit -am "Added URL" + git push heroku master 如果还没有ssh-key,可以用 ssh-keygen -C '[email protected]' -t rsa 命令来生成一个。 在heroku中修改应用名字xxx为zzror,修改后执行下面操作: -git remote rm heroku -git remote add heroku [email protected]:zzror.git + git remote rm heroku + git remote add heroku [email protected]:zzror.git 接着修改config.ru中的url,修改后执行 -git commit -am "Modified URL" -git push heroku master + git commit -am "Modified URL" + git push heroku master -toto文档http://github.com/cloudhead/toto +[toto文档](http://github.com/cloudhead/toto)
itxiaozi/zzror
3f97e4a379452d4260e682a956f878a0f15b5891
add 2010-10-13-test.txt
diff --git a/articles/2010-10-13-test.txt b/articles/2010-10-13-test.txt new file mode 100644 index 0000000..742f34b --- /dev/null +++ b/articles/2010-10-13-test.txt @@ -0,0 +1,18 @@ +title: test +author: test +date: 2010/10/13 + +Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, +who was a farmer, and Aunt Em, who was the farmer's wife. + +Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, +who was a farmer, and Aunt Em, who was the farmer's wife. + +Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, +who was a farmer, and Aunt Em, who was the farmer's wife. + +Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, +who was a farmer, and Aunt Em, who was the farmer's wife. + +Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, +who was a farmer, and Aunt Em, who was the farmer's wife.
itxiaozi/zzror
075a14f82006cf04de535745e3a6254252dbc3eb
Modified config.ru
diff --git a/config.ru b/config.ru index 47eaed1..6c74323 100644 --- a/config.ru +++ b/config.ru @@ -1,36 +1,36 @@ require 'toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::CommonLogger if ENV['RACK_ENV'] == 'development' use Rack::ShowExceptions end # # Create and configure a toto instance # toto = Toto::Server.new do # # Add your settings here # set [:setting], [value] # - # set :author, ENV['USER'] # blog author - # set :title, Dir.pwd.split('/').last # site title - # set :root, "index" # page to load on / - # set :date, lambda {|now| now.strftime("%d/%m/%Y") } # date format for articles - # set :markdown, :smart # use markdown + smart-mode - # set :disqus, false # disqus id, or false - # set :summary, :max => 150, :delim => /~/ # length of article summary and delimiter - # set :ext, 'txt' # file extension for articles - # set :cache, 28800 # cache duration, in seconds + set :author, ENV['USER'] # blog author + set :title, Dir.pwd.split('/').last # site title + set :root, "index" # page to load on / + set :date, lambda {|now| now.strftime("%d/%m/%Y") } # date format for articles + set :markdown, :smart # use markdown + smart-mode + set :disqus, false # disqus id, or false + set :summary, :max => 150, :delim => /~/ # length of article summary and delimiter + set :ext, 'txt' # file extension for articles + set :cache, 28800 # cache duration, in seconds set :url, 'http://zzror.heroku.com/' set :date, lambda {|now| now.strftime("%B #{now.day.ordinal} %Y") } end run toto
itxiaozi/zzror
61972b554441be95be78869bfbb1d06e3d68576c
2010-10-13-toto-heroku
diff --git a/articles/2010-10-13-toto-heroku.txt b/articles/2010-10-13-toto-heroku.txt new file mode 100644 index 0000000..ab951f8 --- /dev/null +++ b/articles/2010-10-13-toto-heroku.txt @@ -0,0 +1,28 @@ +title: 搭建toto+heroku轻量级博客系统 +author: 我不累,真的不累 +date: 2010/10/13 + +记录搭建toto+heroku轻量级博客系统过程,备忘。 + +gem install heroku +git clone git://github.com/cloudhead/dorothy.git zzror +cd zzror +heroku create +# heroku create会返回一个类似 http://xxx.heroku.com 的网址,在文件config.ru中的Toto::Server.new block中追加 +# set :url, 'http://xxx.heroku.com' +git commit -am "Added URL" +git push heroku master + +如果还没有ssh-key,可以用 ssh-keygen -C '[email protected]' -t rsa 命令来生成一个。 + +在heroku中修改应用名字xxx为zzror,修改后执行下面操作: + +git remote rm heroku +git remote add heroku [email protected]:zzror.git + +接着修改config.ru中的url,修改后执行 + +git commit -am "Modified URL" +git push heroku master + +toto文档http://github.com/cloudhead/toto
itxiaozi/zzror
a4d8779444f763125a213273c5554a28437007cc
Modified URL
diff --git a/config.ru b/config.ru index 9604186..47eaed1 100644 --- a/config.ru +++ b/config.ru @@ -1,36 +1,36 @@ require 'toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::CommonLogger if ENV['RACK_ENV'] == 'development' use Rack::ShowExceptions end # # Create and configure a toto instance # toto = Toto::Server.new do # # Add your settings here # set [:setting], [value] # # set :author, ENV['USER'] # blog author # set :title, Dir.pwd.split('/').last # site title # set :root, "index" # page to load on / # set :date, lambda {|now| now.strftime("%d/%m/%Y") } # date format for articles # set :markdown, :smart # use markdown + smart-mode # set :disqus, false # disqus id, or false # set :summary, :max => 150, :delim => /~/ # length of article summary and delimiter # set :ext, 'txt' # file extension for articles # set :cache, 28800 # cache duration, in seconds - set :url, 'http://radiant-sunrise-28.heroku.com/' + set :url, 'http://zzror.heroku.com/' set :date, lambda {|now| now.strftime("%B #{now.day.ordinal} %Y") } end run toto
itxiaozi/zzror
c1942357ab543ae290e1d3c0cd342419c740d6c8
Added URL
diff --git a/config.ru b/config.ru index 74b411e..9604186 100644 --- a/config.ru +++ b/config.ru @@ -1,35 +1,36 @@ require 'toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::CommonLogger if ENV['RACK_ENV'] == 'development' use Rack::ShowExceptions end # # Create and configure a toto instance # toto = Toto::Server.new do # # Add your settings here # set [:setting], [value] # # set :author, ENV['USER'] # blog author # set :title, Dir.pwd.split('/').last # site title # set :root, "index" # page to load on / # set :date, lambda {|now| now.strftime("%d/%m/%Y") } # date format for articles # set :markdown, :smart # use markdown + smart-mode # set :disqus, false # disqus id, or false # set :summary, :max => 150, :delim => /~/ # length of article summary and delimiter # set :ext, 'txt' # file extension for articles # set :cache, 28800 # cache duration, in seconds + set :url, 'http://radiant-sunrise-28.heroku.com/' set :date, lambda {|now| now.strftime("%B #{now.day.ordinal} %Y") } end run toto
itxiaozi/zzror
6b9b23fff87de67ea58991dd495972fc9f02b75d
source/version unnecessary in .gems
diff --git a/.gems b/.gems index 2e9445a..c092e46 100644 --- a/.gems +++ b/.gems @@ -1,4 +1,4 @@ -builder --source=http://gemcutter.org -rdiscount --source=http://gemcutter.org -toto --source=http://gemcutter.org --version=">= 0.2.8" +builder +rdiscount +toto
itxiaozi/zzror
e03125c52fb86b3105f8e938cc8c5ece9f49d21b
forgot to add index.builder
diff --git a/templates/index.builder b/templates/index.builder new file mode 100644 index 0000000..d58098d --- /dev/null +++ b/templates/index.builder @@ -0,0 +1,21 @@ +xml.instruct! +xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do + xml.title @config[:title] + xml.id @config[:url] + xml.updated articles.first[:date].iso8601 unless articles.empty? + xml.author { xml.name @config[:author] } + + articles.reverse[0...10].each do |article| + xml.entry do + xml.title article.title + xml.link "rel" => "alternate", "href" => article.url + xml.id article.url + xml.published article[:date].iso8601 + xml.updated article[:date].iso8601 + xml.author { xml.name @config[:author] } + xml.summary article.summary, "type" => "html" + xml.content article.body, "type" => "html" + end + end +end +
itxiaozi/zzror
40b1f667e2b333c7fd701d1c726b3a2d0cbbc300
only show last 10 articles in the feed
diff --git a/templates/feed.builder b/templates/feed.builder index 1398017..d58098d 100644 --- a/templates/feed.builder +++ b/templates/feed.builder @@ -1,21 +1,21 @@ xml.instruct! xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do xml.title @config[:title] xml.id @config[:url] xml.updated articles.first[:date].iso8601 unless articles.empty? xml.author { xml.name @config[:author] } - articles.each do |article| + articles.reverse[0...10].each do |article| xml.entry do xml.title article.title xml.link "rel" => "alternate", "href" => article.url xml.id article.url xml.published article[:date].iso8601 xml.updated article[:date].iso8601 xml.author { xml.name @config[:author] } xml.summary article.summary, "type" => "html" xml.content article.body, "type" => "html" end end end
itxiaozi/zzror
991c6486da39565fe2dd52ac567ec1028dcfa953
dont say anything, if no archived articles
diff --git a/templates/pages/archives.rhtml b/templates/pages/archives.rhtml index 008f8eb..c41fcbd 100644 --- a/templates/pages/archives.rhtml +++ b/templates/pages/archives.rhtml @@ -1,13 +1,11 @@ <h1><%= @path %></h1> <ul> <% if archives.length > 0 %> <% for entry in archives %> <li> <a href="<%= entry.path %>"><%= entry.title %></a> </li> <% end %> - <% else %> - There are no articles for this date. <% end %> </ul>
itxiaozi/zzror
c26bb0401138b2eabb1bc881bb160b44653726ef
Changed the layout to work witch accented letters (UTF8) like 'è'
diff --git a/templates/layout.rhtml b/templates/layout.rhtml index 57e0988..8db4be3 100644 --- a/templates/layout.rhtml +++ b/templates/layout.rhtml @@ -1,17 +1,18 @@ <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="/css/main.css"> <link rel="alternate" type="application/atom+xml" title="<%= title %> - feed" href="/index.xml" /> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title><%= title %></title> </head> <body> <section> <%= yield %> </section> <footer> powered by <a href="http://cloudhead.io/toto">toto</a> </footer> </body> </html>
itxiaozi/zzror
a959d9ac2edbecdf6c929c4b2095f20a916068d3
don't use default author from @config, let it default when the server runs, to take advantage of user settings. Closes #16
diff --git a/Rakefile b/Rakefile index f5e9016..755a103 100644 --- a/Rakefile +++ b/Rakefile @@ -1,42 +1,42 @@ require 'toto' @config = Toto::Config::Defaults task :default => :new desc "Create a new article." task :new do title = ask('Title: ') slug = title.empty?? nil : title.strip.slugize - article = {'title' => title, 'date' => Time.now.strftime("%d/%m/%Y"), 'author' => @config[:author]}.to_yaml + article = {'title' => title, 'date' => Time.now.strftime("%d/%m/%Y")}.to_yaml article << "\n" article << "Once upon a time...\n\n" path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}#{'-' + slug if slug}.#{@config[:ext]}" unless File.exist? path File.open(path, "w") do |file| file.write article end toto "an article was created for you at #{path}." else toto "I can't create the article, #{path} already exists." end end desc "Publish my blog." task :publish do - toto "Publishing your article(s)..." + toto "publishing your article(s)..." `git push heroku master` end def toto msg puts "\n toto ~ #{msg}\n\n" end def ask message print message STDIN.gets.chomp end
itxiaozi/zzror
83b11d65f945f5ee77985911731f093aa54d6419
require latest version of toto
diff --git a/.gems b/.gems index 9791a02..2e9445a 100644 --- a/.gems +++ b/.gems @@ -1,4 +1,4 @@ builder --source=http://gemcutter.org rdiscount --source=http://gemcutter.org -toto --source=http://gemcutter.org --version=">= 0.2.5" +toto --source=http://gemcutter.org --version=">= 0.2.8"
itxiaozi/zzror
f17bc50d50c16973ccb050cdf3a18e39edcd06a2
fixed README
diff --git a/README b/README index e69de29..fac817a 100644 --- a/README +++ b/README @@ -0,0 +1,4 @@ +dorothy +======= + +A wonderful template for [toto](http://cloudhead.io/toto), the blogging engine.
itxiaozi/zzror
836ec5bed19d92967986e9f950b3c2916533d66b
Added the defaults as examples in config.ru
diff --git a/config.ru b/config.ru index dead700..74b411e 100644 --- a/config.ru +++ b/config.ru @@ -1,21 +1,35 @@ + require 'toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::CommonLogger if ENV['RACK_ENV'] == 'development' use Rack::ShowExceptions end -# Run application +# +# Create and configure a toto instance +# toto = Toto::Server.new do # # Add your settings here # set [:setting], [value] - # + # + # set :author, ENV['USER'] # blog author + # set :title, Dir.pwd.split('/').last # site title + # set :root, "index" # page to load on / + # set :date, lambda {|now| now.strftime("%d/%m/%Y") } # date format for articles + # set :markdown, :smart # use markdown + smart-mode + # set :disqus, false # disqus id, or false + # set :summary, :max => 150, :delim => /~/ # length of article summary and delimiter + # set :ext, 'txt' # file extension for articles + # set :cache, 28800 # cache duration, in seconds + set :date, lambda {|now| now.strftime("%B #{now.day.ordinal} %Y") } end run toto +
itxiaozi/zzror
15d95de72cb6918b71da11c9555002fb1de9f646
rake new asks for the title of the new article
diff --git a/Rakefile b/Rakefile index 79cf2db..f5e9016 100644 --- a/Rakefile +++ b/Rakefile @@ -1,37 +1,42 @@ require 'toto' @config = Toto::Config::Defaults -desc "Run 'rake new[\"My Article Title\"]' to create a new article." -task :new, [:title] do |t, args| - if args.title.nil? - toto "Please provide an article title with 'rake new[\"My Article Title\"]'" - exit - end - title = args.title.strip.downcase.gsub(/ /, '-') +task :default => :new + +desc "Create a new article." +task :new do + title = ask('Title: ') + slug = title.empty?? nil : title.strip.slugize + article = {'title' => title, 'date' => Time.now.strftime("%d/%m/%Y"), 'author' => @config[:author]}.to_yaml article << "\n" article << "Once upon a time...\n\n" - path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}-#{title}.#{@config[:ext]}" + path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}#{'-' + slug if slug}.#{@config[:ext]}" unless File.exist? path File.open(path, "w") do |file| file.write article end toto "an article was created for you at #{path}." else toto "I can't create the article, #{path} already exists." end end desc "Publish my blog." task :publish do - toto "publishing your article(s)..." + toto "Publishing your article(s)..." `git push heroku master` end def toto msg puts "\n toto ~ #{msg}\n\n" end +def ask message + print message + STDIN.gets.chomp +end +
itxiaozi/zzror
3fbb1b06bd088d1167dd6f5de95884443fc0df4a
Teach 'rake new' how to take a title arg which is now required.
diff --git a/Rakefile b/Rakefile index caa07bc..79cf2db 100644 --- a/Rakefile +++ b/Rakefile @@ -1,34 +1,37 @@ require 'toto' @config = Toto::Config::Defaults -task :default => :new - -desc "Create a new article from the template." -task :new do - article = {'title' => nil, 'date' => Time.now.strftime("%d/%m/%Y"), 'author' => @config[:author]}.to_yaml +desc "Run 'rake new[\"My Article Title\"]' to create a new article." +task :new, [:title] do |t, args| + if args.title.nil? + toto "Please provide an article title with 'rake new[\"My Article Title\"]'" + exit + end + title = args.title.strip.downcase.gsub(/ /, '-') + article = {'title' => title, 'date' => Time.now.strftime("%d/%m/%Y"), 'author' => @config[:author]}.to_yaml article << "\n" article << "Once upon a time...\n\n" - path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}.#{@config[:ext]}" + path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}-#{title}.#{@config[:ext]}" unless File.exist? path File.open(path, "w") do |file| file.write article end toto "an article was created for you at #{path}." else toto "I can't create the article, #{path} already exists." end end desc "Publish my blog." task :publish do toto "publishing your article(s)..." `git push heroku master` end def toto msg puts "\n toto ~ #{msg}\n\n" end
itxiaozi/zzror
dcd17f16c95e5c77694566a6ab3c8519e1667f74
New heroku repo's are pushed with 'git push heroku master' by default.
diff --git a/Rakefile b/Rakefile index 286561a..caa07bc 100644 --- a/Rakefile +++ b/Rakefile @@ -1,34 +1,34 @@ require 'toto' @config = Toto::Config::Defaults task :default => :new desc "Create a new article from the template." task :new do article = {'title' => nil, 'date' => Time.now.strftime("%d/%m/%Y"), 'author' => @config[:author]}.to_yaml article << "\n" article << "Once upon a time...\n\n" path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}.#{@config[:ext]}" unless File.exist? path File.open(path, "w") do |file| file.write article end toto "an article was created for you at #{path}." else toto "I can't create the article, #{path} already exists." end end desc "Publish my blog." task :publish do toto "publishing your article(s)..." - `git push origin master` + `git push heroku master` end def toto msg puts "\n toto ~ #{msg}\n\n" end
itxiaozi/zzror
71d5edc44776d80c9d7894a1ef79dfc795b053ec
Added descriptions to Rakefile so 'rake -T' works.
diff --git a/Rakefile b/Rakefile index 715fe95..286561a 100644 --- a/Rakefile +++ b/Rakefile @@ -1,32 +1,34 @@ require 'toto' @config = Toto::Config::Defaults task :default => :new +desc "Create a new article from the template." task :new do article = {'title' => nil, 'date' => Time.now.strftime("%d/%m/%Y"), 'author' => @config[:author]}.to_yaml article << "\n" article << "Once upon a time...\n\n" path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}.#{@config[:ext]}" unless File.exist? path File.open(path, "w") do |file| file.write article end toto "an article was created for you at #{path}." else toto "I can't create the article, #{path} already exists." end end +desc "Publish my blog." task :publish do toto "publishing your article(s)..." `git push origin master` end def toto msg puts "\n toto ~ #{msg}\n\n" end
itxiaozi/zzror
0cd08faed625079f8fc534ba7ba37b8d51406bb9
only use ShowExceptions in dev
diff --git a/config.ru b/config.ru index a3c10b6..dead700 100644 --- a/config.ru +++ b/config.ru @@ -1,18 +1,21 @@ require 'toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' -use Rack::ShowExceptions use Rack::CommonLogger +if ENV['RACK_ENV'] == 'development' + use Rack::ShowExceptions +end + # Run application toto = Toto::Server.new do # # Add your settings here # set [:setting], [value] # set :date, lambda {|now| now.strftime("%B #{now.day.ordinal} %Y") } end run toto
itxiaozi/zzror
e8dd6da91d4f2e70638ff59aa1b8c1ff324c4e8d
replaced all article urls with article paths so it works locally
diff --git a/templates/pages/archives.rhtml b/templates/pages/archives.rhtml index f9b869b..008f8eb 100644 --- a/templates/pages/archives.rhtml +++ b/templates/pages/archives.rhtml @@ -1,13 +1,13 @@ <h1><%= @path %></h1> <ul> <% if archives.length > 0 %> <% for entry in archives %> <li> - <a href="<%= entry.url %>"><%= entry.title %></a> + <a href="<%= entry.path %>"><%= entry.title %></a> </li> <% end %> <% else %> There are no articles for this date. <% end %> </ul> diff --git a/templates/pages/index.rhtml b/templates/pages/index.rhtml index 1d50b9b..20df228 100644 --- a/templates/pages/index.rhtml +++ b/templates/pages/index.rhtml @@ -1,20 +1,20 @@ <section id="articles"> <% for article in articles[0...3] %> <article class="post"> <header> - <h1><a href="<%= article.url %>"><%= article.title %></a></h1> + <h1><a href="<%= article.path %>"><%= article.title %></a></h1> <span class="date"><%= article.date %></span> </header> <section class="content"> <%= article.summary %> </section> - <div class="more"><a href="<%= article.url %>">read on &raquo;</a></div> + <div class="more"><a href="<%= article.path %>">read on &raquo;</a></div> </article> <% end %> </section> <section id="archives"> <%= archives[3..-1] %> </section>
itxiaozi/zzror
3a2205b9b23b059e14cab2fca351726f5bda2ce9
changed toto version and url
diff --git a/.gems b/.gems index afde131..9791a02 100644 --- a/.gems +++ b/.gems @@ -1,4 +1,4 @@ builder --source=http://gemcutter.org rdiscount --source=http://gemcutter.org -toto --source=http://gemcutter.org --version=">= 0.1.2" +toto --source=http://gemcutter.org --version=">= 0.2.5" diff --git a/templates/layout.rhtml b/templates/layout.rhtml index 9161d84..57e0988 100644 --- a/templates/layout.rhtml +++ b/templates/layout.rhtml @@ -1,17 +1,17 @@ <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="/css/main.css"> <link rel="alternate" type="application/atom+xml" title="<%= title %> - feed" href="/index.xml" /> <title><%= title %></title> </head> <body> <section> <%= yield %> </section> <footer> - powered by <a href="http://github.com/cloudhead/toto">toto</a> + powered by <a href="http://cloudhead.io/toto">toto</a> </footer> </body> </html>
itxiaozi/zzror
7d052995ec0d015fb05b54334f0acde245c7cdf1
overall improvement to the templates
diff --git a/public/css/main.css b/public/css/main.css index db468c6..34a7f78 100644 --- a/public/css/main.css +++ b/public/css/main.css @@ -1,87 +1,110 @@ html { margin: 20px } body { margin: 0 auto; font-family: 'Baskerville', Georgia, Times, serif; font-size: 20px; line-height: 30px; padding: 15px; width: 720px; } header, footer, section, article { display: block; } #content { } #by { font-style: italic; margin-right: 5px; font-size: 28px; } #caption { position: absolute; font-size: 24px; margin: -135px 0 0 70px; } #path { color: #b53131; } .date { font-style: italic; - margin-left: 5px; + float: right; + line-height: 43px; + margin-right: 30px; } a { color: #b83000; } +h1 a { + color: black; + text-decoration: none; +} +a:hover { + text-decoration: underline; +} body > header > h1 { border-left: 30px solid black; padding-left: 30px; font-size: 201px; margin: 100px 0 15px 0; font-weight: normal; } .post header { margin-bottom: 10px; } .post .body p:first-child { margin-top: 0; } .post .body p:last-child { margin-bottom: 0; } .post { margin-bottom: 30px; } .post:last-child { margin-bottom: 10px; } .post p { margin: 10px 0; } +.post .more { + margin-top: -10px; + margin-right: 30px; + font-style: italic; + text-align: right; +} +.more a { + text-decoration: none; +} +.more a:hover { text-decoration: underline } body > header { display: block; padding-top: 30px; line-height: 180px; margin-bottom: 20px; } h1, h2, h3, h4 { display: inline; margin: 0; font-weight: 600; } +ul, li { + list-style-type: none; +} code { font-family: 'Anonymous Pro', 'Bitstream Vera Sans', 'Monaco', Courier, mono; } pre { padding: 20px; } blockquote { font-style: italic; } body > footer { - text-align: right; + text-align: left; + margin-left: 10px; font-style: italic; font-size: 18px; color: #888; } diff --git a/templates/pages/archives.rhtml b/templates/pages/archives.rhtml index 87ea134..f9b869b 100644 --- a/templates/pages/archives.rhtml +++ b/templates/pages/archives.rhtml @@ -1,13 +1,13 @@ +<h1><%= @path %></h1> <ul> - <% for entry in archives %> - <li> - <header> - <%= entry.title %> - </header> - <span class="date"> - <%= entry.date %> - </span> - </li> + <% if archives.length > 0 %> + <% for entry in archives %> + <li> + <a href="<%= entry.url %>"><%= entry.title %></a> + </li> + <% end %> + <% else %> + There are no articles for this date. <% end %> </ul> diff --git a/templates/pages/index.rhtml b/templates/pages/index.rhtml index f398b16..1d50b9b 100644 --- a/templates/pages/index.rhtml +++ b/templates/pages/index.rhtml @@ -1,10 +1,20 @@ <section id="articles"> <% for article in articles[0...3] %> - <%= article %> + <article class="post"> + <header> + <h1><a href="<%= article.url %>"><%= article.title %></a></h1> + <span class="date"><%= article.date %></span> + </header> + + <section class="content"> + <%= article.summary %> + </section> + <div class="more"><a href="<%= article.url %>">read on &raquo;</a></div> + </article> <% end %> </section> <section id="archives"> <%= archives[3..-1] %> </section>
itxiaozi/zzror
f0c2bd83bef9d1c7cc21e861732d649a2d865152
fixed css, and added footer
diff --git a/public/css/main.css b/public/css/main.css index f2c8b77..db468c6 100644 --- a/public/css/main.css +++ b/public/css/main.css @@ -1,74 +1,87 @@ +html { margin: 20px } body { + margin: 0 auto; font-family: 'Baskerville', Georgia, Times, serif; - font-size: 32px; - line-height: 48px; + font-size: 20px; + line-height: 30px; padding: 15px; + width: 720px; } header, footer, section, article { display: block; } #content { } #by { - font-style: italic; -margin-right: 5px; + font-style: italic; + margin-right: 5px; font-size: 28px; } #caption { position: absolute; font-size: 24px; margin: -135px 0 0 70px; } #path { color: #b53131; } -#io { - color: black; -} .date { font-style: italic; - margin-left: 15px; + margin-left: 5px; } a { color: #b83000; } body > header > h1 { border-left: 30px solid black; padding-left: 30px; font-size: 201px; margin: 100px 0 15px 0; font-weight: normal; } .post header { margin-bottom: 10px; } .post .body p:first-child { margin-top: 0; } .post .body p:last-child { margin-bottom: 0; } .post { - margin-bottom: 60px; + margin-bottom: 30px; +} +.post:last-child { + margin-bottom: 10px; +} +.post p { + margin: 10px 0; } body > header { display: block; padding-top: 30px; line-height: 180px; margin-bottom: 20px; } h1, h2, h3, h4 { display: inline; margin: 0; font-weight: 600; } code { font-family: 'Anonymous Pro', 'Bitstream Vera Sans', 'Monaco', Courier, mono; } pre { padding: 20px; } blockquote { font-style: italic; -} \ No newline at end of file +} + +body > footer { + text-align: right; + font-style: italic; + font-size: 18px; + color: #888; +} diff --git a/templates/layout.rhtml b/templates/layout.rhtml index c77943d..9161d84 100644 --- a/templates/layout.rhtml +++ b/templates/layout.rhtml @@ -1,14 +1,17 @@ <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="/css/main.css"> <link rel="alternate" type="application/atom+xml" title="<%= title %> - feed" href="/index.xml" /> <title><%= title %></title> </head> <body> <section> <%= yield %> </section> + <footer> + powered by <a href="http://github.com/cloudhead/toto">toto</a> + </footer> </body> </html> diff --git a/templates/pages/article.rhtml b/templates/pages/article.rhtml index 8dc2b6b..e778d7b 100644 --- a/templates/pages/article.rhtml +++ b/templates/pages/article.rhtml @@ -1,20 +1,20 @@ <article class="post"> <header> <h1><%= title %></h1> - <span><%= date %></span> + <span class="date"><%= date %></span> </header> <section class="content"> <%= body %> </section> <section class="comments"> <% if @config[:disqus] %> <div id="disqus_thread"></div> <script type="text/javascript" src="http://disqus.com/forums/<%= @config[:disqus] %>/embed.js"> </script> <noscript><a href="http://<%= @config[:disqus] %>.disqus.com/?url=ref">View the discussion thread.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a> <% end %> </section> </article>
itxiaozi/zzror
59849b497b23ddcf86c2952702e31252f4e749d2
cleanup
diff --git a/Rakefile b/Rakefile index ef5862a..715fe95 100644 --- a/Rakefile +++ b/Rakefile @@ -1,36 +1,32 @@ -require '../toto/lib/toto' +require 'toto' @config = Toto::Config::Defaults -task :default => :init - -task :init do - -end +task :default => :new task :new do article = {'title' => nil, 'date' => Time.now.strftime("%d/%m/%Y"), 'author' => @config[:author]}.to_yaml article << "\n" article << "Once upon a time...\n\n" path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}.#{@config[:ext]}" unless File.exist? path File.open(path, "w") do |file| file.write article end toto "an article was created for you at #{path}." else toto "I can't create the article, #{path} already exists." end end task :publish do toto "publishing your article(s)..." `git push origin master` end def toto msg puts "\n toto ~ #{msg}\n\n" end diff --git a/articles/2009-11-24.txt b/articles/2009-11-24.txt deleted file mode 100644 index 645a3eb..0000000 --- a/articles/2009-11-24.txt +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: Muah -date: 24/11/2009 -author: cloudhead - -muahahah -
itxiaozi/zzror
a95914e0acd349f55abd398eef206be56ee93988
.gems dependency update
diff --git a/.gems b/.gems index e9e0788..afde131 100644 --- a/.gems +++ b/.gems @@ -1,4 +1,4 @@ builder --source=http://gemcutter.org rdiscount --source=http://gemcutter.org -toto --source=http://gemcutter.org --version=">= 0.1.1" +toto --source=http://gemcutter.org --version=">= 0.1.2"
itxiaozi/zzror
e1b0dd681a2c2782b3e126766ea5edb0fe6add28
fixed html
diff --git a/templates/layout.rhtml b/templates/layout.rhtml index b20707b..c77943d 100644 --- a/templates/layout.rhtml +++ b/templates/layout.rhtml @@ -1,14 +1,14 @@ -<doctype html> -<head> - <link rel="stylesheet" type="text/css" href="/css/main.css"> - <link rel="alternate" type="application/atom+xml" title="<%= title %> - feed" href="/index.xml" /> - <title><%= title %></title> -</head> +<!doctype html> <html> + <head> + <link rel="stylesheet" type="text/css" href="/css/main.css"> + <link rel="alternate" type="application/atom+xml" title="<%= title %> - feed" href="/index.xml" /> + <title><%= title %></title> + </head> <body> <section> <%= yield %> </section> </body> </html>
itxiaozi/zzror
3e11cfe4437c325983080ae61948dc5c5d0b61e3
new aritcle
diff --git a/articles/2009-11-24.txt b/articles/2009-11-24.txt new file mode 100644 index 0000000..645a3eb --- /dev/null +++ b/articles/2009-11-24.txt @@ -0,0 +1,7 @@ +--- +title: Muah +date: 24/11/2009 +author: cloudhead + +muahahah +
itxiaozi/zzror
efda79442ea257c1cacfc178bed0c8a1e8305d71
toto requirement
diff --git a/.gems b/.gems index 891a893..e9e0788 100644 --- a/.gems +++ b/.gems @@ -1,4 +1,4 @@ builder --source=http://gemcutter.org rdiscount --source=http://gemcutter.org -toto --source=http://gemcutter.org +toto --source=http://gemcutter.org --version=">= 0.1.1"
itxiaozi/zzror
80556e348143b75f8f5c5dd5b35e9cc663c31de7
toto is now a gem
diff --git a/config.ru b/config.ru index 7fc5773..a3c10b6 100644 --- a/config.ru +++ b/config.ru @@ -1,19 +1,18 @@ -$:.unshift "../toto/lib" require 'toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::ShowExceptions use Rack::CommonLogger # Run application toto = Toto::Server.new do # # Add your settings here # set [:setting], [value] # set :date, lambda {|now| now.strftime("%B #{now.day.ordinal} %Y") } end run toto
itxiaozi/zzror
2970c8f3eec195d80f6deff6429ef2ae6ebd7c25
.gems file for heroku
diff --git a/.gems b/.gems new file mode 100644 index 0000000..891a893 --- /dev/null +++ b/.gems @@ -0,0 +1,4 @@ +builder --source=http://gemcutter.org +rdiscount --source=http://gemcutter.org +toto --source=http://gemcutter.org +
itxiaozi/zzror
d7e61b4d1213de1a657c69cb9de14496c229f256
added feed to index
diff --git a/templates/layout.rhtml b/templates/layout.rhtml index 123a9a0..b20707b 100644 --- a/templates/layout.rhtml +++ b/templates/layout.rhtml @@ -1,13 +1,14 @@ <doctype html> <head> <link rel="stylesheet" type="text/css" href="/css/main.css"> + <link rel="alternate" type="application/atom+xml" title="<%= title %> - feed" href="/index.xml" /> <title><%= title %></title> </head> <html> <body> <section> <%= yield %> </section> </body> </html>
itxiaozi/zzror
f19c1867f6976db95dd3618baac77b6369453f9d
added Rakefile, for common tasks, and renamed server.ru to config, for portability
diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..ef5862a --- /dev/null +++ b/Rakefile @@ -0,0 +1,36 @@ +require '../toto/lib/toto' + +@config = Toto::Config::Defaults + +task :default => :init + +task :init do + +end + +task :new do + article = {'title' => nil, 'date' => Time.now.strftime("%d/%m/%Y"), 'author' => @config[:author]}.to_yaml + article << "\n" + article << "Once upon a time...\n\n" + + path = "#{Toto::Paths[:articles]}/#{Time.now.strftime("%Y-%m-%d")}.#{@config[:ext]}" + + unless File.exist? path + File.open(path, "w") do |file| + file.write article + end + toto "an article was created for you at #{path}." + else + toto "I can't create the article, #{path} already exists." + end +end + +task :publish do + toto "publishing your article(s)..." + `git push origin master` +end + +def toto msg + puts "\n toto ~ #{msg}\n\n" +end + diff --git a/server.ru b/config.ru similarity index 100% rename from server.ru rename to config.ru
itxiaozi/zzror
e2afd30cc512aca5cd727042b8a32f2c74367cfa
moved some files around
diff --git a/server.ru b/server.ru index e796992..c28afb7 100644 --- a/server.ru +++ b/server.ru @@ -1,15 +1,16 @@ -require '../toto/lib/toto' +$:.unshift "../toto/lib" +require 'toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::ShowExceptions use Rack::CommonLogger # Run application run Toto::Server.new do # # Add your settings here # set [:setting], [value] # set :time, lambda {|now| now.strftime("%B #{now.day.ordinal} %Y") } end diff --git a/templates/index.rhtml b/templates/layout.rhtml similarity index 100% rename from templates/index.rhtml rename to templates/layout.rhtml diff --git a/templates/pages/home.rhtml b/templates/pages/index.rhtml similarity index 100% rename from templates/pages/home.rhtml rename to templates/pages/index.rhtml
itxiaozi/zzror
d878d2b2da58f71710f3b5405d06d32a96a1462f
config
diff --git a/server.ru b/server.ru index bc8c0b2..e796992 100644 --- a/server.ru +++ b/server.ru @@ -1,9 +1,15 @@ require '../toto/lib/toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::ShowExceptions -use Rack::CommonLogger +use Rack::CommonLogger # Run application -run Toto::Server.new +run Toto::Server.new do + # + # Add your settings here + # set [:setting], [value] + # + set :time, lambda {|now| now.strftime("%B #{now.day.ordinal} %Y") } +end
itxiaozi/zzror
bf7e0f77b76b200049194707b294fd15b0e1f788
much changes
diff --git a/config/skeleton.yml b/config/skeleton.yml deleted file mode 100644 index e69de29..0000000 diff --git a/public/css/main.css b/public/css/main.css new file mode 100644 index 0000000..f2c8b77 --- /dev/null +++ b/public/css/main.css @@ -0,0 +1,74 @@ +body { + font-family: 'Baskerville', Georgia, Times, serif; + font-size: 32px; + line-height: 48px; + padding: 15px; + +} +header, footer, section, article { + display: block; +} +#content { +} +#by { + font-style: italic; +margin-right: 5px; + font-size: 28px; +} +#caption { + position: absolute; + font-size: 24px; + margin: -135px 0 0 70px; +} +#path { + color: #b53131; +} +#io { + color: black; +} +.date { + font-style: italic; + margin-left: 15px; +} +a { + color: #b83000; +} +body > header > h1 { + border-left: 30px solid black; + padding-left: 30px; + font-size: 201px; + margin: 100px 0 15px 0; + font-weight: normal; +} +.post header { + margin-bottom: 10px; +} +.post .body p:first-child { + margin-top: 0; +} +.post .body p:last-child { + margin-bottom: 0; +} +.post { + margin-bottom: 60px; +} +body > header { + display: block; + padding-top: 30px; + line-height: 180px; + margin-bottom: 20px; +} +h1, h2, h3, h4 { + display: inline; + margin: 0; + font-weight: 600; +} +code { + font-family: 'Anonymous Pro', 'Bitstream Vera Sans', 'Monaco', Courier, mono; +} +pre { + padding: 20px; +} +blockquote { + font-style: italic; +} \ No newline at end of file diff --git a/public/css/skeleton.css b/public/css/skeleton.css deleted file mode 100644 index e69de29..0000000 diff --git a/config/toto.ru b/server.ru similarity index 87% rename from config/toto.ru rename to server.ru index 010363f..bc8c0b2 100644 --- a/config/toto.ru +++ b/server.ru @@ -1,9 +1,9 @@ -require 'lib/toto' +require '../toto/lib/toto' # Rack config use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::ShowExceptions use Rack::CommonLogger # Run application run Toto::Server.new diff --git a/templates/article.rhtml b/templates/article.rhtml index cfdea60..5fb55e2 100644 --- a/templates/article.rhtml +++ b/templates/article.rhtml @@ -1,9 +1,20 @@ <article> <header> <h1><%= title %></h1> <span><%= date %></span> </header> + <section class="content"> - <%= content %> + <%= body %> + </section> + + <section class="comments"> + <% if Site[:disqus] %> + <div id="disqus_thread"></div> + <script type="text/javascript" src="http://disqus.com/forums/<%= Site[:disqus] %>/embed.js"> </script> + <noscript><a href="http://<%= Site[:disqus] %>.disqus.com/?url=ref">View the discussion thread.</a></noscript> + <a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a> + <% end %> </section> </article> + diff --git a/templates/feed.builder b/templates/feed.builder new file mode 100644 index 0000000..1398017 --- /dev/null +++ b/templates/feed.builder @@ -0,0 +1,21 @@ +xml.instruct! +xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do + xml.title @config[:title] + xml.id @config[:url] + xml.updated articles.first[:date].iso8601 unless articles.empty? + xml.author { xml.name @config[:author] } + + articles.each do |article| + xml.entry do + xml.title article.title + xml.link "rel" => "alternate", "href" => article.url + xml.id article.url + xml.published article[:date].iso8601 + xml.updated article[:date].iso8601 + xml.author { xml.name @config[:author] } + xml.summary article.summary, "type" => "html" + xml.content article.body, "type" => "html" + end + end +end + diff --git a/templates/feed.xml b/templates/feed.xml deleted file mode 100644 index e69de29..0000000 diff --git a/templates/index.rhtml b/templates/index.rhtml index c0870e8..2c3b0c7 100644 --- a/templates/index.rhtml +++ b/templates/index.rhtml @@ -1,11 +1,12 @@ <doctype html> <head> <title><%= title %></title> </head> <html> <body> <section> <%= yield %> </section> </body> </html> + diff --git a/templates/pages/archives.rhtml b/templates/pages/archives.rhtml new file mode 100644 index 0000000..87ea134 --- /dev/null +++ b/templates/pages/archives.rhtml @@ -0,0 +1,13 @@ +<ul> + <% for entry in archives %> + <li> + <header> + <%= entry.title %> + </header> + <span class="date"> + <%= entry.date %> + </span> + </li> + <% end %> +</ul> + diff --git a/templates/pages/home.rhtml b/templates/pages/home.rhtml index ed9c619..f398b16 100644 --- a/templates/pages/home.rhtml +++ b/templates/pages/home.rhtml @@ -1,3 +1,10 @@ -<% for article in articles %> - <%= article %> -<% end %> +<section id="articles"> + <% for article in articles[0...3] %> + <%= article %> + <% end %> +</section> + +<section id="archives"> + <%= archives[3..-1] %> +</section> + diff --git a/templates/resources/article.rhtml b/templates/resources/article.rhtml deleted file mode 100644 index cfdea60..0000000 --- a/templates/resources/article.rhtml +++ /dev/null @@ -1,9 +0,0 @@ -<article> - <header> - <h1><%= title %></h1> - <span><%= date %></span> - </header> - <section class="content"> - <%= content %> - </section> -</article>
itxiaozi/zzror
ac3b53ef0147f48afee83075a7dbe079f2852ba3
renamed .html to .rhtml
diff --git a/templates/article.rhtml b/templates/article.rhtml new file mode 100644 index 0000000..cfdea60 --- /dev/null +++ b/templates/article.rhtml @@ -0,0 +1,9 @@ +<article> + <header> + <h1><%= title %></h1> + <span><%= date %></span> + </header> + <section class="content"> + <%= content %> + </section> +</article> diff --git a/templates/feed.xml b/templates/feed.xml new file mode 100644 index 0000000..e69de29 diff --git a/templates/index.rhtml b/templates/index.rhtml new file mode 100644 index 0000000..c0870e8 --- /dev/null +++ b/templates/index.rhtml @@ -0,0 +1,11 @@ +<doctype html> +<head> + <title><%= title %></title> +</head> +<html> + <body> + <section> + <%= yield %> + </section> + </body> +</html> diff --git a/templates/pages/about.rhtml b/templates/pages/about.rhtml new file mode 100644 index 0000000..e69de29 diff --git a/templates/pages/home.rhtml b/templates/pages/home.rhtml new file mode 100644 index 0000000..ed9c619 --- /dev/null +++ b/templates/pages/home.rhtml @@ -0,0 +1,3 @@ +<% for article in articles %> + <%= article %> +<% end %> diff --git a/templates/resources/article.rhtml b/templates/resources/article.rhtml new file mode 100644 index 0000000..cfdea60 --- /dev/null +++ b/templates/resources/article.rhtml @@ -0,0 +1,9 @@ +<article> + <header> + <h1><%= title %></h1> + <span><%= date %></span> + </header> + <section class="content"> + <%= content %> + </section> +</article>
itxiaozi/zzror
6b7652e65c44db7a82bc8c0c122999e0ad1adfbf
fix home template
diff --git a/templates/pages/home.html b/templates/pages/home.html index b6b5ddc..9f4e1da 100644 --- a/templates/pages/home.html +++ b/templates/pages/home.html @@ -1 +1,4 @@ -<%= @articles %> +Articles: +<% for article in @articles %> + <%= article %> +<% end %>
itxiaozi/zzror
bf1286741dbed7c12515cfb9f698b43be019ac18
fixed html structure of layout
diff --git a/templates/layout.html b/templates/layout.html index 7c3f106..218b7a4 100644 --- a/templates/layout.html +++ b/templates/layout.html @@ -1,11 +1,11 @@ <doctype html> +<head> + <title><%= @title %></title> +</head> <html> - <head> - <title><%= @title %></title> - </head> <body> <section> <%= yield %> </section> </body> </html>
itxiaozi/zzror
5b24e5c90b28ba84d2e8eb4f7b9952274fc02e89
created skeleton article | moved article template to resources/
diff --git a/articles/skeleton.txt b/articles/skeleton.txt new file mode 100644 index 0000000..e1ff41a --- /dev/null +++ b/articles/skeleton.txt @@ -0,0 +1,7 @@ +title: The Wonderful Wizard of Oz +author: Lyman Frank Baum +date: 1900/05/17 + +Dorothy lived in the midst of the great Kansas prairies, with Uncle Henry, +who was a farmer, and Aunt Em, who was the farmer's wife. + diff --git a/templates/article.html b/templates/article.html deleted file mode 100644 index f500572..0000000 --- a/templates/article.html +++ /dev/null @@ -1,9 +0,0 @@ -<article> - <header> - <h1><%= article.title %></h1> - <span><%= article.date %></span> - </header> - <section class="content"> - <%= article.content %> - </section> -</article> diff --git a/templates/resources/article.html b/templates/resources/article.html new file mode 100644 index 0000000..cfdea60 --- /dev/null +++ b/templates/resources/article.html @@ -0,0 +1,9 @@ +<article> + <header> + <h1><%= title %></h1> + <span><%= date %></span> + </header> + <section class="content"> + <%= content %> + </section> +</article>
itxiaozi/zzror
48729057a14cc045dd0f0acc47bf348cb37baab3
added favicon to static reqs
diff --git a/config/toto.ru b/config/toto.ru index 34d2826..010363f 100644 --- a/config/toto.ru +++ b/config/toto.ru @@ -1,9 +1,9 @@ require 'lib/toto' # Rack config -use Rack::Static, :urls => ['/css', '/js', '/images'], :root => 'public' +use Rack::Static, :urls => ['/css', '/js', '/images', '/favicon.ico'], :root => 'public' use Rack::ShowExceptions use Rack::CommonLogger # Run application run Toto::Server.new
itxiaozi/zzror
081ac795ff6a363e40afa7c384b1d8c8403c5d28
fix templates
diff --git a/templates/article.html b/templates/article.html index d6d9715..f500572 100644 --- a/templates/article.html +++ b/templates/article.html @@ -1,9 +1,9 @@ <article> <header> - <h1>{{title}}</h1> - <span>{{date}}</span> + <h1><%= article.title %></h1> + <span><%= article.date %></span> </header> <section class="content"> - {{content}} + <%= article.content %> </section> </article> diff --git a/templates/pages/home.html b/templates/pages/home.html index 2282623..b6b5ddc 100644 --- a/templates/pages/home.html +++ b/templates/pages/home.html @@ -1,11 +1 @@ -<% for article in @articles do %> - <article> - <header> - <h1><%= article.title %></h1> - <span><%= article.date %></span> - </header> - <section class="content"> - <%= article.content %> - </section> - </article> -<% end %> +<%= @articles %>
itxiaozi/zzror
a14ad1b6c98d624860c5c19bd5dec59dc50e5e6b
init config files
diff --git a/config/skeleton.yml b/config/skeleton.yml new file mode 100644 index 0000000..e69de29 diff --git a/config/toto.ru b/config/toto.ru new file mode 100644 index 0000000..34d2826 --- /dev/null +++ b/config/toto.ru @@ -0,0 +1,9 @@ +require 'lib/toto' + +# Rack config +use Rack::Static, :urls => ['/css', '/js', '/images'], :root => 'public' +use Rack::ShowExceptions +use Rack::CommonLogger + +# Run application +run Toto::Server.new
chrippa/hashfs
98719b33925b8a669406fef9c0bc15eb8d845037
Add grouping by sets.
diff --git a/src/hashfs/db.c b/src/hashfs/db.c index 3257577..237e425 100644 --- a/src/hashfs/db.c +++ b/src/hashfs/db.c @@ -1,371 +1,400 @@ #include <glib.h> #include <string.h> #include <stdio.h> #include "hashfs.h" #define HASHFS_QUERY_PATTERN "([A-Za-z\\:]+)\\.(\\w+)\\((.*?)\\)" #define LENGTH(x) sizeof(x)/sizeof(x[0]) static hashfs_db_t *db; typedef struct { gint op; gchar *name; } hashfs_db_query_cond_t; static hashfs_db_query_cond_t query_cond[] = { { TDBQCSTREQ, "Equals" }, { TDBQCSTRINC, "Contains" }, { TDBQCSTRBW, "BeginsWith" }, { TDBQCSTREQ, "EndsWith" }, { TDBQCSTRAND, "IncludeAll" }, { TDBQCSTROR, "Include" }, { TDBQCSTRRX, "Regexp" }, }; gboolean hashfs_db_init (gboolean readonly) { gchar *path; gint flags; gboolean rval; g_return_val_if_fail(db == NULL, FALSE); path = g_build_filename(g_get_user_config_dir(), "hashfs", "metadata.tct", NULL); flags = readonly ? TDBOREADER | TDBONOLCK : TDBOWRITER | TDBOCREAT; db = g_new0(hashfs_db_t, 1); db->tdb = tctdbnew(); db->path = path; db->flags = flags; if (!tctdbopen(db->tdb, path, flags)) { HASHFS_DEBUG("Unable to open DB: %s", hashfs_db_error()); rval = FALSE; } else { HASHFS_DEBUG("Successfully opened DB"); rval = TRUE; } return rval; } static void hashfs_db_reload (void) { tctdbclose(db->tdb); tctdbopen(db->tdb, db->path, db->flags); } void hashfs_db_destroy (void) { g_return_if_fail(db != NULL); if (!tctdbclose(db->tdb)) { HASHFS_DEBUG("Unable to close DB: %s", hashfs_db_error()); } else { HASHFS_DEBUG("Successfully closed DB"); } tctdbdel(db->tdb); g_free(db->path); free(db); } gboolean hashfs_db_tran_begin (void) { HASHFS_DEBUG("Starting transsaction"); return (gboolean) tctdbtranbegin(db->tdb); } gboolean hashfs_db_tran_commit (void) { HASHFS_DEBUG("Comitting transsaction"); return (gboolean) tctdbtrancommit(db->tdb); } gboolean hashfs_db_tran_abort (void) { HASHFS_DEBUG("Aborting transsaction"); return (gboolean) tctdbtranabort(db->tdb); } gchar * hashfs_db_error (void) { gint ecode = tctdbecode(db->tdb); return (gchar *) tctdberrmsg(ecode); } hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type) { gchar *pkey, *md5; md5 = hashfs_md5_str(id); if (!g_strcmp0(prefix, "set")) pkey = g_strdup_printf("%s:%s:%s:%s", prefix, source, type, md5); else pkey = g_strdup_printf("%s:%s", prefix, md5); g_free(md5); return hashfs_db_entry_new_from_key(pkey); } hashfs_db_entry_t * hashfs_db_entry_new_from_key (const gchar *pkey) { hashfs_db_entry_t *entry; TCMAP *curdata; entry = g_new0(hashfs_db_entry_t, 1); entry->pkey = g_strdup(pkey); hashfs_db_reload(); curdata = tctdbget(db->tdb, pkey, strlen(pkey)); if (curdata != NULL) entry->data = curdata; else entry->data = tcmapnew(); HASHFS_DEBUG("Created entry with pkey: %s", pkey); return entry; } void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value) { g_return_if_fail(entry != NULL); g_return_if_fail(entry->data != NULL); tcmapput2(entry->data, key, value); } gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out) { const gchar *val; val = tcmapget2(entry->data, key); if (val == NULL) return FALSE; *out = val; return TRUE; } static gboolean eval_cb (const GMatchInfo *info, GString *res, gpointer data) { const gchar *tmp; gchar *match; match = g_match_info_fetch(info, 1); if (hashfs_db_entry_lookup(data, match, &tmp)) g_string_append(res, tmp); g_free(match); return FALSE; } gchar * hashfs_db_entry_format (hashfs_db_entry_t *entry, const gchar *format) { GRegex *regex; GMatchInfo *match; GError *error = NULL; gchar *rval; regex = g_regex_new("\\$(\\w+)", 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } rval = g_regex_replace_eval(regex, format, -1, 0, 0, eval_cb, entry, NULL); g_regex_unref(regex); return rval; } const gchar * hashfs_db_entry_pkey (hashfs_db_entry_t *entry) { return entry->pkey; } gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry) { g_return_val_if_fail(entry != NULL, FALSE); g_return_val_if_fail(entry->pkey != NULL, FALSE); g_return_val_if_fail(entry->data != NULL, FALSE); return (gboolean) tctdbputcat(db->tdb, entry->pkey, strlen(entry->pkey), entry->data); } void hashfs_db_entry_destroy (hashfs_db_entry_t *entry) { g_return_if_fail (entry != NULL); if (entry->data) tcmapdel(entry->data); if (entry->pkey) g_free(entry->pkey); g_free(entry); } static gint hashfs_db_query_op (gchar *name) { for (gint i = 0; i < LENGTH(query_cond); i++) { if (g_strcmp0(name, query_cond[i].name) == 0) return query_cond[i].op; } return -1; } hashfs_db_query_t * hashfs_db_query_new (const gchar *querystr) { GRegex *regex; GMatchInfo *match; GError *error = NULL; hashfs_db_query_t *query; query = g_new0(hashfs_db_query_t, 1); query->query = tctdbqrynew(db->tdb); regex = g_regex_new(HASHFS_QUERY_PATTERN, 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } g_regex_match(regex, querystr, 0, &match); while (g_match_info_matches(match)) { gchar *key = g_match_info_fetch(match, 1); gchar *func = g_match_info_fetch(match, 2); gchar *val = g_match_info_fetch(match, 3); gint op; op = hashfs_db_query_op(func); HASHFS_DEBUG("Adding query condition: %s.%s(%s)", key, func, val); if (op >= 0) { if (!g_strcmp0(key, "pkey")) tctdbqryaddcond(query->query, "", op, val); else tctdbqryaddcond(query->query, key, op, val); } g_free(key); g_free(func); g_free(val); g_match_info_next(match, NULL); } g_match_info_free(match); g_regex_unref(regex); return query; } void hashfs_db_query_set_limit (hashfs_db_query_t *query, gint limit, gint skip) { tctdbqrysetlimit(query->query, limit, skip); } void hashfs_db_query_set_order (hashfs_db_query_t *query, gchar *key, gint mode) { tctdbqrysetorder(query->query, key, mode); } hashfs_db_result_t * hashfs_db_query_result (hashfs_db_query_t *query) { hashfs_db_result_t *result; hashfs_db_reload(); result = g_new0(hashfs_db_result_t, 1); result->list = tctdbqrysearch(query->query); return result; } +hashfs_db_result_t * +hashfs_db_query_group (hashfs_db_query_t *query, const gchar *groupby) +{ + hashfs_db_result_t *newres, *origres; + + origres = hashfs_db_query_result(query); + newres = g_new0(hashfs_db_result_t, 1); + newres->list = tclistnew(); + + for (gint i = 0; i < hashfs_db_result_num(origres); i++) { + hashfs_db_entry_t *entry; + const gchar *val; + + entry = hashfs_db_result_get_entry(origres, i); + + if (hashfs_db_entry_lookup(entry, groupby, &val)) { + if (tclistlsearch(newres->list, val, strlen(val)) < 0) { + tclistpush2(newres->list, val); + } + } + + hashfs_db_entry_destroy(entry); + } + + hashfs_db_result_destroy(origres); + + return newres; +} + void hashfs_db_query_destroy (hashfs_db_query_t *query) { if (query->query) tctdbqrydel(query->query); g_free(query); } gint hashfs_db_result_num (hashfs_db_result_t *result) { return (gint) tclistnum(result->list); } hashfs_db_entry_t * hashfs_db_result_get_entry (hashfs_db_result_t *result, gint index) { const gchar *key; gint len; key = tclistval(result->list, index, &len); return hashfs_db_entry_new_from_key(key); } void hashfs_db_result_destroy (hashfs_db_result_t *result) { if (result->list) tclistdel(result->list); g_free(result); } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index 2e002f0..3628425 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,212 +1,213 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include <tcutil.h> #include <tctdb.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_db_St; struct hashfs_db_entry_St; struct hashfs_db_result_St; struct hashfs_db_query_St; struct hashfs_file_St; struct hashfs_set_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_db_St hashfs_db_t; typedef struct hashfs_db_entry_St hashfs_db_entry_t; typedef struct hashfs_db_result_St hashfs_db_result_t; typedef struct hashfs_db_query_St hashfs_db_query_t; typedef struct hashfs_file_St hashfs_file_t; typedef struct hashfs_set_St hashfs_set_t; struct hashfs_backend_St { gpointer data; GList *globs; GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; struct hashfs_db_St { TCTDB *tdb; gchar *path; gint flags; }; struct hashfs_db_entry_St { TCMAP *data; gchar *pkey; }; struct hashfs_db_result_St { TCLIST *list; }; struct hashfs_db_query_St { TDBQRY *query; }; struct hashfs_file_St { gchar *filename; gint64 size; GList *sets; hashfs_backend_t *backend; hashfs_db_entry_t *entry; /* Hashes */ gchar *ed2k; gchar *md5; }; struct hashfs_set_St { gchar name[256]; hashfs_db_entry_t *entry; }; /* Config */ GKeyFile * hashfs_config_keyfile (void); void hashfs_config_init (void); void hashfs_config_destroy (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); /* Database */ gboolean hashfs_db_init (gboolean readonly); void hashfs_db_destroy (void); gchar * hashfs_db_error (void); gboolean hashfs_db_tran_abort (void); gboolean hashfs_db_tran_begin (void); gboolean hashfs_db_tran_commit (void); /* Database entry */ hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type); hashfs_db_entry_t * hashfs_db_entry_new_from_key (const gchar *key); gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out); gchar * hashfs_db_entry_format (hashfs_db_entry_t *entry, const gchar *format); const gchar * hashfs_db_entry_pkey (hashfs_db_entry_t *entry); void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value); gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry); void hashfs_db_entry_destroy (hashfs_db_entry_t *entry); /* Database query */ hashfs_db_query_t * hashfs_db_query_new (const gchar *querystr); hashfs_db_result_t * hashfs_db_query_result (hashfs_db_query_t *query); +hashfs_db_result_t * hashfs_db_query_group (hashfs_db_query_t *query, const gchar *groupby); void hashfs_db_query_set_limit (hashfs_db_query_t *query, gint limit, gint skip); void hashfs_db_query_set_order (hashfs_db_query_t *query, gchar *key, gint mode); void hashfs_db_query_destroy (hashfs_db_query_t *query); /* Database result list */ gint hashfs_db_result_num (hashfs_db_result_t *result); hashfs_db_entry_t * hashfs_db_result_get_entry (hashfs_db_result_t *result, gint index); void hashfs_db_result_destroy (hashfs_db_result_t *result); /* Set */ hashfs_set_t * hashfs_set_new (const gchar *name, const gchar *source, const gchar *type); gboolean hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, const gchar **out); void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, const gchar *value); void hashfs_set_destroy (hashfs_set_t *set); /* File */ hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend); gboolean hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_hash_md5 (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value); hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type); void hashfs_file_destroy (hashfs_file_t *file); /* Backend manager */ hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); void hashfs_backends_load (const gchar *path); void hashfs_backends_destroy (void); /* Backend */ hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); void hashfs_backend_glob_set (hashfs_backend_t *backend, ...); gboolean hashfs_backend_glob_try (hashfs_backend_t *backend, const gchar *filename); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, const gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); /* Utils */ gchar * hashfs_current_time (void); gchar * hashfs_basename (const gchar *name); gchar * hashfs_md5_str (const gchar *str); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ gchar *log_time = hashfs_current_time(); \ printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ gchar *log_time = hashfs_current_time(); \ FILE *fd = g_fopen(log_path, "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ g_free(log_path); \ g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif diff --git a/src/hashfs/hashfsmount.c b/src/hashfs/hashfsmount.c index 6a36c42..4e4bde1 100644 --- a/src/hashfs/hashfsmount.c +++ b/src/hashfs/hashfsmount.c @@ -1,505 +1,518 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <unistd.h> #define FUSE_USE_VERSION 26 #include <fuse.h> #include "hashfs.h" GHashTable *mounts; static void hashfs_mounts_add (const gchar *path, const gchar *schema); static gchar * hashfs_mounts_get (const gchar *path); static gboolean hashfs_mounts_exists (const gchar *path); static void hashfs_mounts_init (void); static void hashfs_mounts_destroy (void); -static void hashfs_fuse_listdir (const gchar *squery, const gchar *format, - gpointer buf, fuse_fill_dir_t filler); static void test_query (gchar *querystr) { hashfs_db_query_t *query; hashfs_db_result_t *result; query = hashfs_db_query_new(querystr); - result = hashfs_db_query_result(query); +// result = hashfs_db_query_result(query); + result = hashfs_db_query_group(query, "group"); printf("num results: %d\n", hashfs_db_result_num(result)); for (gint i = 0; i < hashfs_db_result_num(result); i++) { hashfs_db_entry_t *entry; - gchar *tmp; entry = hashfs_db_result_get_entry(result, i); - tmp = hashfs_db_entry_format(entry, "$basename,$path"); - printf("%s\n", tmp); - - g_free(tmp); + printf("result: %s\n", hashfs_db_entry_pkey(entry)); hashfs_db_entry_destroy(entry); } hashfs_db_query_destroy(query); hashfs_db_result_destroy(result); } static void free_entry_list (GList *entries) { GList *item; g_return_if_fail(entries != NULL); for (item = g_list_first(entries); item; item = g_list_next(item)) { hashfs_db_entry_destroy(item->data); } g_list_free(entries); } static GHashTable * parse_schema (gchar *schema) { GRegex *regex; GMatchInfo *match; GError *error = NULL; GHashTable *hash; hash = g_hash_table_new(g_str_hash, g_str_equal); regex = g_regex_new("(\\w+)=\"(.*?)\"", 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } g_regex_match(regex, schema, 0, &match); while (g_match_info_matches(match)) { gchar *key = g_match_info_fetch(match, 1); gchar *val = g_match_info_fetch(match, 2); g_hash_table_insert(hash, key, val); g_match_info_next(match, NULL); } g_match_info_free(match); g_regex_unref(regex); return hash; } static hashfs_db_entry_t * -resolve_path (gchar *squery, gchar *sdisplay, gchar *path) +resolve_path (gchar *squery, gchar *groupby, gchar *sdisplay, gchar *path) { hashfs_db_query_t *query; hashfs_db_result_t *result; hashfs_db_entry_t *entry; query = hashfs_db_query_new(squery); - result = hashfs_db_query_result(query); + if (groupby != NULL) + result = hashfs_db_query_group(query, groupby); + else + result = hashfs_db_query_result(query); entry = NULL; + printf("resolve_path, q=%s, num_results=%d\n", squery, hashfs_db_result_num(result)); + for (gint i = 0; i < hashfs_db_result_num(result); i++) { gchar *display; entry = hashfs_db_result_get_entry(result, i); display = hashfs_db_entry_format(entry, sdisplay); if (g_strcmp0(path, display) == 0) { g_free(display); break; } g_free(display); hashfs_db_entry_destroy(entry); entry = NULL; } hashfs_db_query_destroy(query); hashfs_db_result_destroy(result); return entry; } static gboolean eval_cb (const GMatchInfo *info, GString *res, gpointer data) { gchar *var; gchar *n; gchar *key; gint nth; var = g_match_info_fetch(info, 1); n = g_match_info_fetch(info, 2); key = g_match_info_fetch(info, 3); nth = atoi(n); if (g_strcmp0(var, "prev") == 0) { - GList *item = g_list_nth_prev(data, nth - 1); + GList *last = g_list_last(data); + GList *item = g_list_nth_prev(last, nth - 1); if (item) { const gchar *val; hashfs_db_entry_t *entry = item->data; if (g_strcmp0(key, "pkey") == 0) { val = hashfs_db_entry_pkey(entry); g_string_append(res, val); } else { if (hashfs_db_entry_lookup(entry, key, &val)) g_string_append(res, val); } } } g_free(var); g_free(n); g_free(key); return FALSE; } static gchar * prepare_query (gchar *query, GList *entries) { GRegex *regex; GMatchInfo *match; GError *error = NULL; gchar *rval; regex = g_regex_new("\\$(\\w+)\\[(\\d+)\\]\\.(\\w+)", 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } rval = g_regex_replace_eval(regex, query, -1, 0, 0, eval_cb, entries, NULL); g_regex_unref(regex); return rval; } static GList * resolve_paths (const gchar *path) { gchar **sschema, **spath; gchar *schema; GList *entries; spath = g_strsplit(path, "/", 0); schema = hashfs_mounts_get(spath[1]); sschema = g_strsplit(schema, "/", 0); entries = NULL; for (gint i = 2; i < g_strv_length(spath); i++) { GHashTable *hash = parse_schema(sschema[i]); gchar *q = g_hash_table_lookup(hash, "q"); gchar *d = g_hash_table_lookup(hash, "d"); + gchar *g = g_hash_table_lookup(hash, "g"); gchar *query = prepare_query(q, entries); - hashfs_db_entry_t *entry = resolve_path(query, d, spath[i]); + hashfs_db_entry_t *entry = resolve_path(query, g, d, spath[i]); if (entry) { entries = g_list_append(entries, entry); } else { if (entries) free_entry_list(entries); entries = NULL; } g_free(q); g_free(d); g_free(query); g_hash_table_unref(hash); } g_strfreev(sschema); g_strfreev(spath); return entries; } static void hashfs_mounts_add (const gchar *path, const gchar *schema) { g_hash_table_insert(mounts, g_strdup(path), g_strdup_printf("/%s/%s", path, schema)); } static gchar * hashfs_mounts_get (const gchar *path) { return g_hash_table_lookup(mounts, path); } static gboolean hashfs_mounts_exists (const gchar *path) { gchar *val; val = hashfs_mounts_get(path); if (val) return TRUE; return FALSE; } static void hashfs_mounts_init (void) { if (!mounts) mounts = g_hash_table_new(g_str_hash, g_str_equal); } static void hashfs_mounts_destroy (void) { if (mounts) g_hash_table_unref(mounts); } static gint hashfs_fuse_listattrs (const gchar *path, struct stat *stats) { GList *entries; gint rval; entries = resolve_paths(path); if (entries) { GList *item = g_list_last(entries); hashfs_db_entry_t *entry = item->data; const gchar *pkey; pkey = hashfs_db_entry_pkey(entry); if (g_strrstr(pkey, "set:")) { stats->st_mode = S_IFDIR | 0755; stats->st_nlink = 2; } else { struct stat realstats; const gchar *realpath; if (hashfs_db_entry_lookup(entry, "path", &realpath)) { stat(realpath, &realstats); stats->st_mode = S_IFREG | 0444; stats->st_nlink = 1; stats->st_size = realstats.st_size; } } rval = 0; free_entry_list(entries); } else { rval = -ENOENT; } return rval; } static gint hashfs_fuse_getattr (const gchar *path, struct stat *stats) { gint res; printf("getattr: %s\n", path); memset(stats, 0, sizeof(struct stat)); res = 0; if (g_strcmp0(path, "/") == 0 || hashfs_mounts_exists(path + 1)) { stats->st_mode = S_IFDIR | 0555; stats->st_nlink = 2; } else { res = hashfs_fuse_listattrs(path, stats); } return res; } static void -hashfs_fuse_listdir (const gchar *squery, const gchar *format, - gpointer buf, fuse_fill_dir_t filler) +hashfs_fuse_listdir (const gchar *squery, const gchar *groupby, + const gchar *format, gpointer buf, + fuse_fill_dir_t filler) { hashfs_db_query_t *query; hashfs_db_result_t *result; query = hashfs_db_query_new(squery); - result = hashfs_db_query_result(query); + + if (groupby != NULL) + result = hashfs_db_query_group(query, groupby); + else + result = hashfs_db_query_result(query); printf("listdir, num results: %d, q=%s, d=%s\n", hashfs_db_result_num(result), squery, format); for (gint i = 0; i < hashfs_db_result_num(result); i++) { hashfs_db_entry_t *entry; gchar *formatted; entry = hashfs_db_result_get_entry(result, i); formatted = hashfs_db_entry_format(entry, format); filler(buf, formatted, NULL, 0); g_free(formatted); hashfs_db_entry_destroy(entry); } hashfs_db_query_destroy(query); hashfs_db_result_destroy(result); } static gint hashfs_fuse_readdir (const gchar *path, gpointer buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { printf("readdir: %s\n", path); filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); if (g_strcmp0(path, "/") == 0) { GList *keys, *item; keys = g_hash_table_get_keys(mounts); for (item = g_list_first(keys); item; item = g_list_next(item)) { gchar *key = item->data; filler(buf, key, NULL, 0); } g_list_free(keys); } else { gchar **sschema, **spath; gchar *schema; GList *entries; spath = g_strsplit(path, "/", 0); schema = hashfs_mounts_get(spath[1]); sschema = g_strsplit(schema, "/", 0); entries = NULL; for (gint i = 1; i < g_strv_length(spath); i++) { GHashTable *hash = parse_schema(sschema[i+1]); gchar *q = g_hash_table_lookup(hash, "q"); gchar *d = g_hash_table_lookup(hash, "d"); + gchar *g = g_hash_table_lookup(hash, "g"); gchar *query = prepare_query(q, entries); if ((i + 1) == g_strv_length(spath)) { - hashfs_fuse_listdir(query, d, buf, filler); + hashfs_fuse_listdir(query, g, d, buf, filler); break; } - hashfs_db_entry_t *entry = resolve_path(query, d, spath[i+1]); + hashfs_db_entry_t *entry = resolve_path(query, g, d, spath[i+1]); if (entry) entries = g_list_append(entries, entry); g_free(q); g_free(d); g_free(query); g_hash_table_unref(hash); } g_strfreev(sschema); g_strfreev(spath); if (entries) free_entry_list(entries); } return 0; } static gint hashfs_fuse_open (const gchar *path, struct fuse_file_info *fi) { GList *entries, *item; gint rval = 0; const gchar *realpath; hashfs_db_entry_t *entry; printf("open: %s\n", path); entries = resolve_paths(path); if (!entries) return -ENOENT; if ((fi->flags & 3) != O_RDONLY) return -EACCES; item = g_list_last(entries); entry = item->data; if (hashfs_db_entry_lookup(entry, "path", &realpath)) { fi->fh = open(realpath, fi->flags); } free_entry_list(entries); return 0; } static gint hashfs_fuse_read (const gchar *path, gchar *buf, size_t size, off_t offset, struct fuse_file_info *fi) { gint rval; printf("read %s %d %d\n", path, size, offset); lseek(fi->fh, offset, SEEK_SET); return read(fi->fh, buf, size); } static gint hashfs_fuse_release (const gchar *path, struct fuse_file_info *fi) { printf("close %s\n", path); return close(fi->fh); } static struct fuse_operations hashfs_fuse_operations = { .getattr = hashfs_fuse_getattr, .readdir = hashfs_fuse_readdir, .open = hashfs_fuse_open, .read = hashfs_fuse_read, .release = hashfs_fuse_release, }; gint main (gint argc, gchar **argv) { gint rval; hashfs_config_init(); hashfs_db_init(TRUE); hashfs_mounts_init(); - hashfs_mounts_add("by-name", "(q=\"pkey.BeginsWith(set:anidb:anime)\", d=\"$romaji [$eps]\")/(q=\"pkey.BeginsWith(file:), anime.Equals($prev[1].pkey)\", d=\"$anime_romaji - $ep_number [$group_name].$ext\")"); - hashfs_mounts_add("by-group", "(q=\"pkey.BeginsWith(set:anidb:group)\", d=\"$name\")/(q=\"pkey.BeginsWith(file:), group.Equals($prev[1].pkey)\", d=\"$basename\")"); + hashfs_mounts_add("by-name", "q=\"pkey.BeginsWith(set:anidb:anime)\", d=\"$romaji [$eps]\"/" + "q=\"pkey.BeginsWith(file:), anime.Equals($prev[1].pkey)\", d=\"$anime_romaji - $ep_number [$group_name].$ext\""); + hashfs_mounts_add("by-group", "q=\"pkey.BeginsWith(set:anidb:group)\", d=\"$name\")/" + "q=\"pkey.BeginsWith(file:), group.Equals($prev[1].pkey)\", g=\"anime\", d=\"$romaji\")/" + "q=\"pkey.BeginsWith(file:), group.Equals($prev[2].pkey), anime.Equals($prev[1].pkey)\", d=\"$anime_romaji - $ep_number [$group_name].$ext\""); + rval = fuse_main(argc, argv, &hashfs_fuse_operations, NULL); + hashfs_config_destroy(); hashfs_db_destroy(); hashfs_mounts_destroy(); return rval; }
chrippa/hashfs
608141c7a23eda34bba60c4a2ed62920b23e963e
Fix some database locking issues.
diff --git a/src/hashfs/config.c b/src/hashfs/config.c index 249dbad..0cf3b2b 100644 --- a/src/hashfs/config.c +++ b/src/hashfs/config.c @@ -1,102 +1,102 @@ #include <glib.h> #include "hashfs.h" static GKeyFile *config; static gchar * hashfs_config_build_path (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key) { if (g_key_file_has_group(config, group)) { return g_key_file_has_key(config, group, key, NULL); } return FALSE; } void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out) { *out = g_key_file_get_string(config, group, key, NULL); } void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value) { g_key_file_set_string(config, group, key, value); } GKeyFile * hashfs_config_keyfile (void) { return config; } void -hashfs_config_load (void) +hashfs_config_init (void) { GError *error = NULL; gchar *configfile; config = g_key_file_new(); configfile = hashfs_config_build_path(); g_key_file_load_from_file(config, configfile, G_KEY_FILE_NONE, &error); if (error) { /* Don't error when file doesn't exist or is empty */ if (error->code != 4 && error->code != 1) { HASHFS_ERROR("Unable to load config file (%s): %d %s", configfile, error->message); } g_error_free(error); } g_free(configfile); } void -hashfs_config_save (void) +hashfs_config_destroy (void) { gchar *configfile, *data; FILE *file; configfile = hashfs_config_build_path(); data = g_key_file_to_data(config, NULL, NULL); file = g_fopen(configfile, "w"); fputs(data, file); fclose(file); g_free(configfile); g_free(data); g_key_file_free(config); } static gchar * hashfs_config_build_path (void) { gchar *configdir, *configfile; const gchar *userconfigdir; userconfigdir = g_get_user_config_dir(); configdir = g_build_filename(userconfigdir, "hashfs", NULL); configfile = g_build_filename(configdir, "hashfs.conf", NULL); if (g_file_test(configdir, G_FILE_TEST_EXISTS)) { if (!g_file_test(configdir, G_FILE_TEST_IS_DIR)) HASHFS_ERROR("Config directory already exists but is not a directory (%s)", configdir); } else { if (g_mkdir_with_parents(configdir, 0755) < 0) { HASHFS_ERROR("Unable to create config directory (%s)", configdir); } } g_free(configdir); return configfile; } diff --git a/src/hashfs/db.c b/src/hashfs/db.c index 6407e54..3257577 100644 --- a/src/hashfs/db.c +++ b/src/hashfs/db.c @@ -1,358 +1,371 @@ #include <glib.h> #include <string.h> #include <stdio.h> #include "hashfs.h" #define HASHFS_QUERY_PATTERN "([A-Za-z\\:]+)\\.(\\w+)\\((.*?)\\)" #define LENGTH(x) sizeof(x)/sizeof(x[0]) static hashfs_db_t *db; typedef struct { gint op; gchar *name; } hashfs_db_query_cond_t; static hashfs_db_query_cond_t query_cond[] = { { TDBQCSTREQ, "Equals" }, { TDBQCSTRINC, "Contains" }, { TDBQCSTRBW, "BeginsWith" }, { TDBQCSTREQ, "EndsWith" }, { TDBQCSTRAND, "IncludeAll" }, { TDBQCSTROR, "Include" }, { TDBQCSTRRX, "Regexp" }, }; gboolean -hashfs_db_open (void) +hashfs_db_init (gboolean readonly) { gchar *path; + gint flags; gboolean rval; g_return_val_if_fail(db == NULL, FALSE); + path = g_build_filename(g_get_user_config_dir(), "hashfs", "metadata.tct", NULL); + flags = readonly ? TDBOREADER | TDBONOLCK : TDBOWRITER | TDBOCREAT; + db = g_new0(hashfs_db_t, 1); db->tdb = tctdbnew(); + db->path = path; + db->flags = flags; - path = g_build_filename(g_get_user_config_dir(), "hashfs", "metadata.tct", NULL); - - if (!tctdbopen(db->tdb, path, TDBOWRITER | TDBOCREAT)) { + if (!tctdbopen(db->tdb, path, flags)) { HASHFS_DEBUG("Unable to open DB: %s", hashfs_db_error()); rval = FALSE; } else { HASHFS_DEBUG("Successfully opened DB"); rval = TRUE; } - g_free(path); - return rval; } +static void +hashfs_db_reload (void) +{ + tctdbclose(db->tdb); + tctdbopen(db->tdb, db->path, db->flags); +} + void -hashfs_db_close (void) +hashfs_db_destroy (void) { g_return_if_fail(db != NULL); if (!tctdbclose(db->tdb)) { HASHFS_DEBUG("Unable to close DB: %s", hashfs_db_error()); } else { HASHFS_DEBUG("Successfully closed DB"); } tctdbdel(db->tdb); + g_free(db->path); free(db); } gboolean hashfs_db_tran_begin (void) { HASHFS_DEBUG("Starting transsaction"); return (gboolean) tctdbtranbegin(db->tdb); } gboolean hashfs_db_tran_commit (void) { HASHFS_DEBUG("Comitting transsaction"); return (gboolean) tctdbtrancommit(db->tdb); } gboolean hashfs_db_tran_abort (void) { HASHFS_DEBUG("Aborting transsaction"); return (gboolean) tctdbtranabort(db->tdb); } gchar * hashfs_db_error (void) { gint ecode = tctdbecode(db->tdb); return (gchar *) tctdberrmsg(ecode); } hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type) { gchar *pkey, *md5; md5 = hashfs_md5_str(id); if (!g_strcmp0(prefix, "set")) pkey = g_strdup_printf("%s:%s:%s:%s", prefix, source, type, md5); else pkey = g_strdup_printf("%s:%s", prefix, md5); g_free(md5); return hashfs_db_entry_new_from_key(pkey); } hashfs_db_entry_t * hashfs_db_entry_new_from_key (const gchar *pkey) { hashfs_db_entry_t *entry; TCMAP *curdata; entry = g_new0(hashfs_db_entry_t, 1); entry->pkey = g_strdup(pkey); + hashfs_db_reload(); curdata = tctdbget(db->tdb, pkey, strlen(pkey)); if (curdata != NULL) entry->data = curdata; else entry->data = tcmapnew(); HASHFS_DEBUG("Created entry with pkey: %s", pkey); return entry; } void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value) { g_return_if_fail(entry != NULL); g_return_if_fail(entry->data != NULL); tcmapput2(entry->data, key, value); } gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out) { const gchar *val; val = tcmapget2(entry->data, key); if (val == NULL) return FALSE; *out = val; return TRUE; } static gboolean eval_cb (const GMatchInfo *info, GString *res, gpointer data) { const gchar *tmp; gchar *match; match = g_match_info_fetch(info, 1); if (hashfs_db_entry_lookup(data, match, &tmp)) g_string_append(res, tmp); g_free(match); return FALSE; } gchar * hashfs_db_entry_format (hashfs_db_entry_t *entry, const gchar *format) { GRegex *regex; GMatchInfo *match; GError *error = NULL; gchar *rval; regex = g_regex_new("\\$(\\w+)", 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } rval = g_regex_replace_eval(regex, format, -1, 0, 0, eval_cb, entry, NULL); g_regex_unref(regex); return rval; } const gchar * hashfs_db_entry_pkey (hashfs_db_entry_t *entry) { return entry->pkey; } gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry) { g_return_val_if_fail(entry != NULL, FALSE); g_return_val_if_fail(entry->pkey != NULL, FALSE); g_return_val_if_fail(entry->data != NULL, FALSE); return (gboolean) tctdbputcat(db->tdb, entry->pkey, strlen(entry->pkey), entry->data); } void hashfs_db_entry_destroy (hashfs_db_entry_t *entry) { g_return_if_fail (entry != NULL); if (entry->data) tcmapdel(entry->data); if (entry->pkey) g_free(entry->pkey); g_free(entry); } static gint hashfs_db_query_op (gchar *name) { for (gint i = 0; i < LENGTH(query_cond); i++) { if (g_strcmp0(name, query_cond[i].name) == 0) return query_cond[i].op; } return -1; } hashfs_db_query_t * hashfs_db_query_new (const gchar *querystr) { GRegex *regex; GMatchInfo *match; GError *error = NULL; hashfs_db_query_t *query; query = g_new0(hashfs_db_query_t, 1); query->query = tctdbqrynew(db->tdb); regex = g_regex_new(HASHFS_QUERY_PATTERN, 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } g_regex_match(regex, querystr, 0, &match); while (g_match_info_matches(match)) { gchar *key = g_match_info_fetch(match, 1); gchar *func = g_match_info_fetch(match, 2); gchar *val = g_match_info_fetch(match, 3); gint op; op = hashfs_db_query_op(func); HASHFS_DEBUG("Adding query condition: %s.%s(%s)", key, func, val); if (op >= 0) { if (!g_strcmp0(key, "pkey")) tctdbqryaddcond(query->query, "", op, val); else tctdbqryaddcond(query->query, key, op, val); } g_free(key); g_free(func); g_free(val); g_match_info_next(match, NULL); } g_match_info_free(match); g_regex_unref(regex); return query; } void hashfs_db_query_set_limit (hashfs_db_query_t *query, gint limit, gint skip) { tctdbqrysetlimit(query->query, limit, skip); } void hashfs_db_query_set_order (hashfs_db_query_t *query, gchar *key, gint mode) { tctdbqrysetorder(query->query, key, mode); } hashfs_db_result_t * hashfs_db_query_result (hashfs_db_query_t *query) { hashfs_db_result_t *result; + hashfs_db_reload(); + result = g_new0(hashfs_db_result_t, 1); result->list = tctdbqrysearch(query->query); return result; } void hashfs_db_query_destroy (hashfs_db_query_t *query) { if (query->query) tctdbqrydel(query->query); g_free(query); } gint hashfs_db_result_num (hashfs_db_result_t *result) { return (gint) tclistnum(result->list); } hashfs_db_entry_t * hashfs_db_result_get_entry (hashfs_db_result_t *result, gint index) { const gchar *key; gint len; key = tclistval(result->list, index, &len); return hashfs_db_entry_new_from_key(key); } void hashfs_db_result_destroy (hashfs_db_result_t *result) { if (result->list) tclistdel(result->list); g_free(result); } diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index bcfa01e..9109036 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,220 +1,220 @@ #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { if (hashfs_backend_glob_try(backend, path)) { hashfs_file_t *file; HASHFS_LOG("Handling file: %s", hashfs_basename(path)); file = hashfs_file_new(path, backend); hashfs_backend_file(backend, file); hashfs_file_destroy(file); } } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; HASHFS_LOG("Searching directory: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; gchar *val; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { hashfs_config_property_lookup(groups[i], keys[j], &val); printf("%s.%s = %s\n", groups[i], keys[j], val); g_free(val); } g_strfreev(keys); } g_strfreev(groups); } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } g_free(val); g_strfreev(split); } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } g_strfreev(split); } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; - hashfs_config_load(); - hashfs_db_open(); + hashfs_config_init(); + if (!hashfs_db_init(FALSE)) + HASHFS_ERROR("Unable to open database"); if (g_module_supported()) { hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); hashfs_backends_destroy(); - - hashfs_config_save(); - hashfs_db_close(); + hashfs_config_destroy(); + hashfs_db_destroy(); return 0; } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index 6c7186f..2e002f0 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,210 +1,212 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include <tcutil.h> #include <tctdb.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_db_St; struct hashfs_db_entry_St; struct hashfs_db_result_St; struct hashfs_db_query_St; struct hashfs_file_St; struct hashfs_set_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_db_St hashfs_db_t; typedef struct hashfs_db_entry_St hashfs_db_entry_t; typedef struct hashfs_db_result_St hashfs_db_result_t; typedef struct hashfs_db_query_St hashfs_db_query_t; typedef struct hashfs_file_St hashfs_file_t; typedef struct hashfs_set_St hashfs_set_t; struct hashfs_backend_St { gpointer data; GList *globs; GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; struct hashfs_db_St { TCTDB *tdb; + gchar *path; + gint flags; }; struct hashfs_db_entry_St { TCMAP *data; gchar *pkey; }; struct hashfs_db_result_St { TCLIST *list; }; struct hashfs_db_query_St { TDBQRY *query; }; struct hashfs_file_St { gchar *filename; gint64 size; GList *sets; hashfs_backend_t *backend; hashfs_db_entry_t *entry; /* Hashes */ gchar *ed2k; gchar *md5; }; struct hashfs_set_St { gchar name[256]; hashfs_db_entry_t *entry; }; /* Config */ GKeyFile * hashfs_config_keyfile (void); -void hashfs_config_load (void); -void hashfs_config_save (void); +void hashfs_config_init (void); +void hashfs_config_destroy (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); /* Database */ -gboolean hashfs_db_open (void); -void hashfs_db_close (void); +gboolean hashfs_db_init (gboolean readonly); +void hashfs_db_destroy (void); gchar * hashfs_db_error (void); gboolean hashfs_db_tran_abort (void); gboolean hashfs_db_tran_begin (void); gboolean hashfs_db_tran_commit (void); /* Database entry */ hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type); hashfs_db_entry_t * hashfs_db_entry_new_from_key (const gchar *key); gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out); gchar * hashfs_db_entry_format (hashfs_db_entry_t *entry, const gchar *format); const gchar * hashfs_db_entry_pkey (hashfs_db_entry_t *entry); void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value); gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry); void hashfs_db_entry_destroy (hashfs_db_entry_t *entry); /* Database query */ hashfs_db_query_t * hashfs_db_query_new (const gchar *querystr); hashfs_db_result_t * hashfs_db_query_result (hashfs_db_query_t *query); void hashfs_db_query_set_limit (hashfs_db_query_t *query, gint limit, gint skip); void hashfs_db_query_set_order (hashfs_db_query_t *query, gchar *key, gint mode); void hashfs_db_query_destroy (hashfs_db_query_t *query); /* Database result list */ gint hashfs_db_result_num (hashfs_db_result_t *result); hashfs_db_entry_t * hashfs_db_result_get_entry (hashfs_db_result_t *result, gint index); void hashfs_db_result_destroy (hashfs_db_result_t *result); /* Set */ hashfs_set_t * hashfs_set_new (const gchar *name, const gchar *source, const gchar *type); gboolean hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, const gchar **out); void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, const gchar *value); void hashfs_set_destroy (hashfs_set_t *set); /* File */ hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend); gboolean hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_hash_md5 (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value); hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type); void hashfs_file_destroy (hashfs_file_t *file); /* Backend manager */ hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); void hashfs_backends_load (const gchar *path); void hashfs_backends_destroy (void); /* Backend */ hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); void hashfs_backend_glob_set (hashfs_backend_t *backend, ...); gboolean hashfs_backend_glob_try (hashfs_backend_t *backend, const gchar *filename); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, const gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); /* Utils */ gchar * hashfs_current_time (void); gchar * hashfs_basename (const gchar *name); gchar * hashfs_md5_str (const gchar *str); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ gchar *log_time = hashfs_current_time(); \ printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ gchar *log_time = hashfs_current_time(); \ FILE *fd = g_fopen(log_path, "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ g_free(log_path); \ g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif diff --git a/src/hashfs/hashfsmount.c b/src/hashfs/hashfsmount.c index 5543f4d..6a36c42 100644 --- a/src/hashfs/hashfsmount.c +++ b/src/hashfs/hashfsmount.c @@ -1,505 +1,505 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <unistd.h> #define FUSE_USE_VERSION 26 #include <fuse.h> #include "hashfs.h" GHashTable *mounts; static void hashfs_mounts_add (const gchar *path, const gchar *schema); static gchar * hashfs_mounts_get (const gchar *path); static gboolean hashfs_mounts_exists (const gchar *path); -static void hashfs_mounts_load (void); +static void hashfs_mounts_init (void); static void hashfs_mounts_destroy (void); static void hashfs_fuse_listdir (const gchar *squery, const gchar *format, gpointer buf, fuse_fill_dir_t filler); static void test_query (gchar *querystr) { hashfs_db_query_t *query; hashfs_db_result_t *result; query = hashfs_db_query_new(querystr); result = hashfs_db_query_result(query); printf("num results: %d\n", hashfs_db_result_num(result)); for (gint i = 0; i < hashfs_db_result_num(result); i++) { hashfs_db_entry_t *entry; gchar *tmp; entry = hashfs_db_result_get_entry(result, i); tmp = hashfs_db_entry_format(entry, "$basename,$path"); printf("%s\n", tmp); g_free(tmp); hashfs_db_entry_destroy(entry); } hashfs_db_query_destroy(query); hashfs_db_result_destroy(result); } static void free_entry_list (GList *entries) { GList *item; g_return_if_fail(entries != NULL); for (item = g_list_first(entries); item; item = g_list_next(item)) { hashfs_db_entry_destroy(item->data); } g_list_free(entries); } static GHashTable * parse_schema (gchar *schema) { GRegex *regex; GMatchInfo *match; GError *error = NULL; GHashTable *hash; hash = g_hash_table_new(g_str_hash, g_str_equal); regex = g_regex_new("(\\w+)=\"(.*?)\"", 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } g_regex_match(regex, schema, 0, &match); while (g_match_info_matches(match)) { gchar *key = g_match_info_fetch(match, 1); gchar *val = g_match_info_fetch(match, 2); g_hash_table_insert(hash, key, val); g_match_info_next(match, NULL); } g_match_info_free(match); g_regex_unref(regex); return hash; } static hashfs_db_entry_t * resolve_path (gchar *squery, gchar *sdisplay, gchar *path) { hashfs_db_query_t *query; hashfs_db_result_t *result; hashfs_db_entry_t *entry; query = hashfs_db_query_new(squery); result = hashfs_db_query_result(query); entry = NULL; for (gint i = 0; i < hashfs_db_result_num(result); i++) { gchar *display; entry = hashfs_db_result_get_entry(result, i); display = hashfs_db_entry_format(entry, sdisplay); if (g_strcmp0(path, display) == 0) { g_free(display); break; } g_free(display); hashfs_db_entry_destroy(entry); entry = NULL; } hashfs_db_query_destroy(query); hashfs_db_result_destroy(result); return entry; } static gboolean eval_cb (const GMatchInfo *info, GString *res, gpointer data) { gchar *var; gchar *n; gchar *key; gint nth; var = g_match_info_fetch(info, 1); n = g_match_info_fetch(info, 2); key = g_match_info_fetch(info, 3); nth = atoi(n); if (g_strcmp0(var, "prev") == 0) { GList *item = g_list_nth_prev(data, nth - 1); if (item) { const gchar *val; hashfs_db_entry_t *entry = item->data; if (g_strcmp0(key, "pkey") == 0) { val = hashfs_db_entry_pkey(entry); g_string_append(res, val); } else { if (hashfs_db_entry_lookup(entry, key, &val)) g_string_append(res, val); } } } g_free(var); g_free(n); g_free(key); return FALSE; } static gchar * prepare_query (gchar *query, GList *entries) { GRegex *regex; GMatchInfo *match; GError *error = NULL; gchar *rval; regex = g_regex_new("\\$(\\w+)\\[(\\d+)\\]\\.(\\w+)", 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } rval = g_regex_replace_eval(regex, query, -1, 0, 0, eval_cb, entries, NULL); g_regex_unref(regex); return rval; } static GList * resolve_paths (const gchar *path) { gchar **sschema, **spath; gchar *schema; GList *entries; spath = g_strsplit(path, "/", 0); schema = hashfs_mounts_get(spath[1]); sschema = g_strsplit(schema, "/", 0); entries = NULL; for (gint i = 2; i < g_strv_length(spath); i++) { GHashTable *hash = parse_schema(sschema[i]); gchar *q = g_hash_table_lookup(hash, "q"); gchar *d = g_hash_table_lookup(hash, "d"); gchar *query = prepare_query(q, entries); hashfs_db_entry_t *entry = resolve_path(query, d, spath[i]); if (entry) { entries = g_list_append(entries, entry); } else { if (entries) free_entry_list(entries); entries = NULL; } g_free(q); g_free(d); g_free(query); g_hash_table_unref(hash); } g_strfreev(sschema); g_strfreev(spath); return entries; } static void hashfs_mounts_add (const gchar *path, const gchar *schema) { g_hash_table_insert(mounts, g_strdup(path), g_strdup_printf("/%s/%s", path, schema)); } static gchar * hashfs_mounts_get (const gchar *path) { return g_hash_table_lookup(mounts, path); } static gboolean hashfs_mounts_exists (const gchar *path) { gchar *val; val = hashfs_mounts_get(path); if (val) return TRUE; return FALSE; } static void -hashfs_mounts_load (void) +hashfs_mounts_init (void) { if (!mounts) mounts = g_hash_table_new(g_str_hash, g_str_equal); } static void hashfs_mounts_destroy (void) { if (mounts) g_hash_table_unref(mounts); } static gint hashfs_fuse_listattrs (const gchar *path, struct stat *stats) { GList *entries; gint rval; entries = resolve_paths(path); if (entries) { GList *item = g_list_last(entries); hashfs_db_entry_t *entry = item->data; const gchar *pkey; pkey = hashfs_db_entry_pkey(entry); if (g_strrstr(pkey, "set:")) { stats->st_mode = S_IFDIR | 0755; stats->st_nlink = 2; } else { struct stat realstats; const gchar *realpath; if (hashfs_db_entry_lookup(entry, "path", &realpath)) { stat(realpath, &realstats); stats->st_mode = S_IFREG | 0444; stats->st_nlink = 1; stats->st_size = realstats.st_size; } } rval = 0; free_entry_list(entries); } else { rval = -ENOENT; } return rval; } static gint hashfs_fuse_getattr (const gchar *path, struct stat *stats) { gint res; printf("getattr: %s\n", path); memset(stats, 0, sizeof(struct stat)); res = 0; if (g_strcmp0(path, "/") == 0 || hashfs_mounts_exists(path + 1)) { stats->st_mode = S_IFDIR | 0555; stats->st_nlink = 2; } else { res = hashfs_fuse_listattrs(path, stats); } return res; } static void hashfs_fuse_listdir (const gchar *squery, const gchar *format, gpointer buf, fuse_fill_dir_t filler) { hashfs_db_query_t *query; hashfs_db_result_t *result; query = hashfs_db_query_new(squery); result = hashfs_db_query_result(query); printf("listdir, num results: %d, q=%s, d=%s\n", hashfs_db_result_num(result), squery, format); for (gint i = 0; i < hashfs_db_result_num(result); i++) { hashfs_db_entry_t *entry; gchar *formatted; entry = hashfs_db_result_get_entry(result, i); formatted = hashfs_db_entry_format(entry, format); filler(buf, formatted, NULL, 0); g_free(formatted); hashfs_db_entry_destroy(entry); } hashfs_db_query_destroy(query); hashfs_db_result_destroy(result); } static gint hashfs_fuse_readdir (const gchar *path, gpointer buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { printf("readdir: %s\n", path); filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); if (g_strcmp0(path, "/") == 0) { GList *keys, *item; keys = g_hash_table_get_keys(mounts); for (item = g_list_first(keys); item; item = g_list_next(item)) { gchar *key = item->data; filler(buf, key, NULL, 0); } g_list_free(keys); } else { gchar **sschema, **spath; gchar *schema; GList *entries; spath = g_strsplit(path, "/", 0); schema = hashfs_mounts_get(spath[1]); sschema = g_strsplit(schema, "/", 0); entries = NULL; for (gint i = 1; i < g_strv_length(spath); i++) { GHashTable *hash = parse_schema(sschema[i+1]); gchar *q = g_hash_table_lookup(hash, "q"); gchar *d = g_hash_table_lookup(hash, "d"); gchar *query = prepare_query(q, entries); if ((i + 1) == g_strv_length(spath)) { hashfs_fuse_listdir(query, d, buf, filler); break; } hashfs_db_entry_t *entry = resolve_path(query, d, spath[i+1]); if (entry) entries = g_list_append(entries, entry); g_free(q); g_free(d); g_free(query); g_hash_table_unref(hash); } g_strfreev(sschema); g_strfreev(spath); if (entries) free_entry_list(entries); } return 0; } static gint hashfs_fuse_open (const gchar *path, struct fuse_file_info *fi) { GList *entries, *item; gint rval = 0; const gchar *realpath; hashfs_db_entry_t *entry; printf("open: %s\n", path); entries = resolve_paths(path); if (!entries) return -ENOENT; if ((fi->flags & 3) != O_RDONLY) return -EACCES; item = g_list_last(entries); entry = item->data; if (hashfs_db_entry_lookup(entry, "path", &realpath)) { fi->fh = open(realpath, fi->flags); } free_entry_list(entries); return 0; } static gint hashfs_fuse_read (const gchar *path, gchar *buf, size_t size, off_t offset, struct fuse_file_info *fi) { gint rval; printf("read %s %d %d\n", path, size, offset); lseek(fi->fh, offset, SEEK_SET); return read(fi->fh, buf, size); } static gint hashfs_fuse_release (const gchar *path, struct fuse_file_info *fi) { printf("close %s\n", path); return close(fi->fh); } static struct fuse_operations hashfs_fuse_operations = { .getattr = hashfs_fuse_getattr, .readdir = hashfs_fuse_readdir, .open = hashfs_fuse_open, .read = hashfs_fuse_read, .release = hashfs_fuse_release, }; gint main (gint argc, gchar **argv) { gint rval; - hashfs_config_load(); - hashfs_db_open(); - hashfs_mounts_load(); + hashfs_config_init(); + hashfs_db_init(TRUE); - - hashfs_mounts_add("by-name", "(q=\"pkey.BeginsWith(set:anidb:anime)\", d=\"$kanji [$eps]\")/(q=\"pkey.BeginsWith(file:), anime.Equals($prev[1].pkey)\", d=\"$anime_kanji - $ep_number - $ep_kanji [$group_name].$ext\")"); + hashfs_mounts_init(); + hashfs_mounts_add("by-name", "(q=\"pkey.BeginsWith(set:anidb:anime)\", d=\"$romaji [$eps]\")/(q=\"pkey.BeginsWith(file:), anime.Equals($prev[1].pkey)\", d=\"$anime_romaji - $ep_number [$group_name].$ext\")"); hashfs_mounts_add("by-group", "(q=\"pkey.BeginsWith(set:anidb:group)\", d=\"$name\")/(q=\"pkey.BeginsWith(file:), group.Equals($prev[1].pkey)\", d=\"$basename\")"); rval = fuse_main(argc, argv, &hashfs_fuse_operations, NULL); - hashfs_config_save(); - hashfs_db_close(); + hashfs_config_destroy(); + hashfs_db_destroy(); + hashfs_mounts_destroy(); return rval; }
chrippa/hashfs
118dc148fbb2e72b04aefb636e9efc90e418bf87
First working version of hashfsmount using fuse, still WIP.
diff --git a/src/hashfs/db.c b/src/hashfs/db.c index 93d7cf0..6407e54 100644 --- a/src/hashfs/db.c +++ b/src/hashfs/db.c @@ -1,311 +1,358 @@ #include <glib.h> #include <string.h> #include <stdio.h> #include "hashfs.h" #define HASHFS_QUERY_PATTERN "([A-Za-z\\:]+)\\.(\\w+)\\((.*?)\\)" #define LENGTH(x) sizeof(x)/sizeof(x[0]) static hashfs_db_t *db; typedef struct { gint op; gchar *name; } hashfs_db_query_cond_t; static hashfs_db_query_cond_t query_cond[] = { { TDBQCSTREQ, "Equals" }, { TDBQCSTRINC, "Contains" }, { TDBQCSTRBW, "BeginsWith" }, { TDBQCSTREQ, "EndsWith" }, { TDBQCSTRAND, "IncludeAll" }, { TDBQCSTROR, "Include" }, { TDBQCSTRRX, "Regexp" }, }; gboolean hashfs_db_open (void) { gchar *path; gboolean rval; g_return_val_if_fail(db == NULL, FALSE); db = g_new0(hashfs_db_t, 1); db->tdb = tctdbnew(); path = g_build_filename(g_get_user_config_dir(), "hashfs", "metadata.tct", NULL); if (!tctdbopen(db->tdb, path, TDBOWRITER | TDBOCREAT)) { HASHFS_DEBUG("Unable to open DB: %s", hashfs_db_error()); rval = FALSE; } else { HASHFS_DEBUG("Successfully opened DB"); rval = TRUE; } g_free(path); return rval; } void hashfs_db_close (void) { g_return_if_fail(db != NULL); if (!tctdbclose(db->tdb)) { HASHFS_DEBUG("Unable to close DB: %s", hashfs_db_error()); } else { HASHFS_DEBUG("Successfully closed DB"); } tctdbdel(db->tdb); free(db); } gboolean hashfs_db_tran_begin (void) { HASHFS_DEBUG("Starting transsaction"); return (gboolean) tctdbtranbegin(db->tdb); } gboolean hashfs_db_tran_commit (void) { HASHFS_DEBUG("Comitting transsaction"); return (gboolean) tctdbtrancommit(db->tdb); } gboolean hashfs_db_tran_abort (void) { HASHFS_DEBUG("Aborting transsaction"); return (gboolean) tctdbtranabort(db->tdb); } gchar * hashfs_db_error (void) { gint ecode = tctdbecode(db->tdb); return (gchar *) tctdberrmsg(ecode); } hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type) { gchar *pkey, *md5; md5 = hashfs_md5_str(id); if (!g_strcmp0(prefix, "set")) pkey = g_strdup_printf("%s:%s:%s:%s", prefix, source, type, md5); else pkey = g_strdup_printf("%s:%s", prefix, md5); g_free(md5); return hashfs_db_entry_new_from_key(pkey); } hashfs_db_entry_t * hashfs_db_entry_new_from_key (const gchar *pkey) { hashfs_db_entry_t *entry; TCMAP *curdata; entry = g_new0(hashfs_db_entry_t, 1); entry->pkey = g_strdup(pkey); curdata = tctdbget(db->tdb, pkey, strlen(pkey)); if (curdata != NULL) entry->data = curdata; else entry->data = tcmapnew(); HASHFS_DEBUG("Created entry with pkey: %s", pkey); return entry; } void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value) { g_return_if_fail(entry != NULL); g_return_if_fail(entry->data != NULL); tcmapput2(entry->data, key, value); } gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out) { const gchar *val; val = tcmapget2(entry->data, key); if (val == NULL) return FALSE; *out = val; return TRUE; } +static gboolean +eval_cb (const GMatchInfo *info, GString *res, gpointer data) +{ + const gchar *tmp; + gchar *match; + + match = g_match_info_fetch(info, 1); + + if (hashfs_db_entry_lookup(data, match, &tmp)) + g_string_append(res, tmp); + + g_free(match); + + return FALSE; +} + +gchar * +hashfs_db_entry_format (hashfs_db_entry_t *entry, const gchar *format) +{ + GRegex *regex; + GMatchInfo *match; + GError *error = NULL; + gchar *rval; + + regex = g_regex_new("\\$(\\w+)", 0, 0, &error); + + if (error) { + HASHFS_DEBUG("Failed to create regex: %s", error->message); + + g_error_free(error); + + return NULL; + } + + rval = g_regex_replace_eval(regex, format, -1, 0, 0, eval_cb, entry, NULL); + + g_regex_unref(regex); + + return rval; +} + +const gchar * +hashfs_db_entry_pkey (hashfs_db_entry_t *entry) +{ + return entry->pkey; +} + gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry) { g_return_val_if_fail(entry != NULL, FALSE); g_return_val_if_fail(entry->pkey != NULL, FALSE); g_return_val_if_fail(entry->data != NULL, FALSE); return (gboolean) tctdbputcat(db->tdb, entry->pkey, strlen(entry->pkey), entry->data); } void hashfs_db_entry_destroy (hashfs_db_entry_t *entry) { g_return_if_fail (entry != NULL); if (entry->data) tcmapdel(entry->data); if (entry->pkey) g_free(entry->pkey); g_free(entry); } static gint hashfs_db_query_op (gchar *name) { for (gint i = 0; i < LENGTH(query_cond); i++) { if (g_strcmp0(name, query_cond[i].name) == 0) return query_cond[i].op; } return -1; } hashfs_db_query_t * hashfs_db_query_new (const gchar *querystr) { GRegex *regex; GMatchInfo *match; GError *error = NULL; hashfs_db_query_t *query; query = g_new0(hashfs_db_query_t, 1); query->query = tctdbqrynew(db->tdb); regex = g_regex_new(HASHFS_QUERY_PATTERN, 0, 0, &error); if (error) { HASHFS_DEBUG("Failed to create regex: %s", error->message); g_error_free(error); return NULL; } g_regex_match(regex, querystr, 0, &match); while (g_match_info_matches(match)) { gchar *key = g_match_info_fetch(match, 1); gchar *func = g_match_info_fetch(match, 2); gchar *val = g_match_info_fetch(match, 3); gint op; op = hashfs_db_query_op(func); HASHFS_DEBUG("Adding query condition: %s.%s(%s)", key, func, val); if (op >= 0) { if (!g_strcmp0(key, "pkey")) tctdbqryaddcond(query->query, "", op, val); else tctdbqryaddcond(query->query, key, op, val); } g_free(key); g_free(func); g_free(val); g_match_info_next(match, NULL); } g_match_info_free(match); g_regex_unref(regex); return query; } void hashfs_db_query_set_limit (hashfs_db_query_t *query, gint limit, gint skip) { tctdbqrysetlimit(query->query, limit, skip); } void hashfs_db_query_set_order (hashfs_db_query_t *query, gchar *key, gint mode) { tctdbqrysetorder(query->query, key, mode); } hashfs_db_result_t * hashfs_db_query_result (hashfs_db_query_t *query) { hashfs_db_result_t *result; result = g_new0(hashfs_db_result_t, 1); result->list = tctdbqrysearch(query->query); return result; } void hashfs_db_query_destroy (hashfs_db_query_t *query) { if (query->query) tctdbqrydel(query->query); g_free(query); } gint hashfs_db_result_num (hashfs_db_result_t *result) { return (gint) tclistnum(result->list); } hashfs_db_entry_t * hashfs_db_result_get_entry (hashfs_db_result_t *result, gint index) { const gchar *key; gint len; key = tclistval(result->list, index, &len); return hashfs_db_entry_new_from_key(key); } void hashfs_db_result_destroy (hashfs_db_result_t *result) { if (result->list) tclistdel(result->list); g_free(result); } diff --git a/src/hashfs/file.c b/src/hashfs/file.c index c8aec1f..94cd125 100644 --- a/src/hashfs/file.c +++ b/src/hashfs/file.c @@ -1,101 +1,102 @@ #include <glib.h> #include "hashfs.h" hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend) { hashfs_file_t *file; struct stat info; stat(filename, &info); file = g_new0(hashfs_file_t, 1); file->backend = backend; file->entry = hashfs_db_entry_new("file", filename, NULL, NULL); file->filename = g_strdup(filename); file->size = (gint64) info.st_size; file->ed2k = NULL; file->md5 = NULL; hashfs_db_tran_begin(); hashfs_db_entry_set(file->entry, "path", filename); + hashfs_db_entry_set(file->entry, "basename", hashfs_basename(filename)); return file; } gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out) { HASHFS_DEBUG("File (%s) looking up property: %s", hashfs_basename(file->filename), key); return hashfs_db_entry_lookup(file->entry, key, out); } void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value) { HASHFS_DEBUG("File (%s) setting property: %s = %s", hashfs_basename(file->filename), key, value); hashfs_db_entry_set(file->entry, key, value); } hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type) { hashfs_set_t *set; const gchar *source; if (file->backend) source = file->backend->desc->shortname; else source = "unknown"; set = hashfs_set_new(name, source, type); hashfs_db_entry_set(file->entry, type, set->entry->pkey); file->sets = g_list_append(file->sets, set); return set; } void hashfs_file_destroy (hashfs_file_t *file) { HASHFS_DEBUG("File (%s) destroying", hashfs_basename(file->filename)); hashfs_db_tran_commit(); if (file->filename) g_free(file->filename); if (file->ed2k) g_free(file->ed2k); if (file->md5) g_free(file->md5); if (file->sets) { GList *item; hashfs_set_t *set; for (item = g_list_first(file->sets); item; item = g_list_next(item)) { set = item->data; hashfs_set_destroy(set); } g_list_free(file->sets); } if (file->entry) { hashfs_db_entry_put(file->entry); hashfs_db_entry_destroy(file->entry); } g_free(file); } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index ced5439..6c7186f 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,208 +1,210 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include <tcutil.h> #include <tctdb.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_db_St; struct hashfs_db_entry_St; struct hashfs_db_result_St; struct hashfs_db_query_St; struct hashfs_file_St; struct hashfs_set_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_db_St hashfs_db_t; typedef struct hashfs_db_entry_St hashfs_db_entry_t; typedef struct hashfs_db_result_St hashfs_db_result_t; typedef struct hashfs_db_query_St hashfs_db_query_t; typedef struct hashfs_file_St hashfs_file_t; typedef struct hashfs_set_St hashfs_set_t; struct hashfs_backend_St { gpointer data; GList *globs; GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; struct hashfs_db_St { TCTDB *tdb; }; struct hashfs_db_entry_St { TCMAP *data; gchar *pkey; }; struct hashfs_db_result_St { TCLIST *list; }; struct hashfs_db_query_St { TDBQRY *query; }; struct hashfs_file_St { gchar *filename; gint64 size; GList *sets; hashfs_backend_t *backend; hashfs_db_entry_t *entry; /* Hashes */ gchar *ed2k; gchar *md5; }; struct hashfs_set_St { gchar name[256]; hashfs_db_entry_t *entry; }; /* Config */ GKeyFile * hashfs_config_keyfile (void); void hashfs_config_load (void); void hashfs_config_save (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); /* Database */ gboolean hashfs_db_open (void); void hashfs_db_close (void); gchar * hashfs_db_error (void); gboolean hashfs_db_tran_abort (void); gboolean hashfs_db_tran_begin (void); gboolean hashfs_db_tran_commit (void); /* Database entry */ hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type); hashfs_db_entry_t * hashfs_db_entry_new_from_key (const gchar *key); gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out); +gchar * hashfs_db_entry_format (hashfs_db_entry_t *entry, const gchar *format); +const gchar * hashfs_db_entry_pkey (hashfs_db_entry_t *entry); void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value); gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry); void hashfs_db_entry_destroy (hashfs_db_entry_t *entry); /* Database query */ hashfs_db_query_t * hashfs_db_query_new (const gchar *querystr); hashfs_db_result_t * hashfs_db_query_result (hashfs_db_query_t *query); void hashfs_db_query_set_limit (hashfs_db_query_t *query, gint limit, gint skip); void hashfs_db_query_set_order (hashfs_db_query_t *query, gchar *key, gint mode); void hashfs_db_query_destroy (hashfs_db_query_t *query); /* Database result list */ gint hashfs_db_result_num (hashfs_db_result_t *result); hashfs_db_entry_t * hashfs_db_result_get_entry (hashfs_db_result_t *result, gint index); void hashfs_db_result_destroy (hashfs_db_result_t *result); /* Set */ hashfs_set_t * hashfs_set_new (const gchar *name, const gchar *source, const gchar *type); gboolean hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, const gchar **out); void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, const gchar *value); void hashfs_set_destroy (hashfs_set_t *set); /* File */ hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend); gboolean hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_hash_md5 (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value); hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type); void hashfs_file_destroy (hashfs_file_t *file); /* Backend manager */ hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); void hashfs_backends_load (const gchar *path); void hashfs_backends_destroy (void); /* Backend */ hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); void hashfs_backend_glob_set (hashfs_backend_t *backend, ...); gboolean hashfs_backend_glob_try (hashfs_backend_t *backend, const gchar *filename); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, const gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); /* Utils */ gchar * hashfs_current_time (void); gchar * hashfs_basename (const gchar *name); gchar * hashfs_md5_str (const gchar *str); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ gchar *log_time = hashfs_current_time(); \ printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ gchar *log_time = hashfs_current_time(); \ FILE *fd = g_fopen(log_path, "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ g_free(log_path); \ g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif diff --git a/src/hashfs/hashfsmount.c b/src/hashfs/hashfsmount.c index 21dd5af..5543f4d 100644 --- a/src/hashfs/hashfsmount.c +++ b/src/hashfs/hashfsmount.c @@ -1,52 +1,505 @@ #include <stdio.h> +#include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> +#include <sys/types.h> +#include <unistd.h> + +#define FUSE_USE_VERSION 26 #include <fuse.h> #include "hashfs.h" -void test_query (gchar *querystr) +GHashTable *mounts; + +static void hashfs_mounts_add (const gchar *path, const gchar *schema); +static gchar * hashfs_mounts_get (const gchar *path); +static gboolean hashfs_mounts_exists (const gchar *path); +static void hashfs_mounts_load (void); +static void hashfs_mounts_destroy (void); +static void hashfs_fuse_listdir (const gchar *squery, const gchar *format, + gpointer buf, fuse_fill_dir_t filler); + +static void +test_query (gchar *querystr) { hashfs_db_query_t *query; hashfs_db_result_t *result; - query = hashfs_db_query_new(querystr); result = hashfs_db_query_result(query); printf("num results: %d\n", hashfs_db_result_num(result)); for (gint i = 0; i < hashfs_db_result_num(result); i++) { hashfs_db_entry_t *entry; - const gchar *tmp; + gchar *tmp; entry = hashfs_db_result_get_entry(result, i); + tmp = hashfs_db_entry_format(entry, "$basename,$path"); + printf("%s\n", tmp); - if (hashfs_db_entry_lookup(entry, "path", &tmp)) - printf("path = %s\n", tmp); + g_free(tmp); hashfs_db_entry_destroy(entry); } hashfs_db_query_destroy(query); hashfs_db_result_destroy(result); } +static void +free_entry_list (GList *entries) +{ + GList *item; + + g_return_if_fail(entries != NULL); + + for (item = g_list_first(entries); item; item = g_list_next(item)) { + hashfs_db_entry_destroy(item->data); + } + + g_list_free(entries); +} + +static GHashTable * +parse_schema (gchar *schema) +{ + GRegex *regex; + GMatchInfo *match; + GError *error = NULL; + GHashTable *hash; + + hash = g_hash_table_new(g_str_hash, g_str_equal); + regex = g_regex_new("(\\w+)=\"(.*?)\"", 0, 0, &error); + + if (error) { + HASHFS_DEBUG("Failed to create regex: %s", error->message); + + g_error_free(error); + + return NULL; + } + + g_regex_match(regex, schema, 0, &match); + while (g_match_info_matches(match)) { + gchar *key = g_match_info_fetch(match, 1); + gchar *val = g_match_info_fetch(match, 2); + + g_hash_table_insert(hash, key, val); + + g_match_info_next(match, NULL); + } + + g_match_info_free(match); + g_regex_unref(regex); + + return hash; +} + +static hashfs_db_entry_t * +resolve_path (gchar *squery, gchar *sdisplay, gchar *path) +{ + hashfs_db_query_t *query; + hashfs_db_result_t *result; + hashfs_db_entry_t *entry; + + query = hashfs_db_query_new(squery); + result = hashfs_db_query_result(query); + entry = NULL; + + for (gint i = 0; i < hashfs_db_result_num(result); i++) { + gchar *display; + + entry = hashfs_db_result_get_entry(result, i); + display = hashfs_db_entry_format(entry, sdisplay); + + if (g_strcmp0(path, display) == 0) { + g_free(display); + break; + } + + g_free(display); + hashfs_db_entry_destroy(entry); + entry = NULL; + } + + hashfs_db_query_destroy(query); + hashfs_db_result_destroy(result); + + return entry; +} + +static gboolean +eval_cb (const GMatchInfo *info, GString *res, gpointer data) +{ + gchar *var; + gchar *n; + gchar *key; + gint nth; + + var = g_match_info_fetch(info, 1); + n = g_match_info_fetch(info, 2); + key = g_match_info_fetch(info, 3); + nth = atoi(n); + + if (g_strcmp0(var, "prev") == 0) { + GList *item = g_list_nth_prev(data, nth - 1); + + if (item) { + const gchar *val; + hashfs_db_entry_t *entry = item->data; + + if (g_strcmp0(key, "pkey") == 0) { + val = hashfs_db_entry_pkey(entry); + g_string_append(res, val); + } else { + if (hashfs_db_entry_lookup(entry, key, &val)) + g_string_append(res, val); + } + } + } + + g_free(var); + g_free(n); + g_free(key); + + return FALSE; +} + +static gchar * +prepare_query (gchar *query, GList *entries) +{ + GRegex *regex; + GMatchInfo *match; + GError *error = NULL; + gchar *rval; + + regex = g_regex_new("\\$(\\w+)\\[(\\d+)\\]\\.(\\w+)", 0, 0, &error); + + if (error) { + HASHFS_DEBUG("Failed to create regex: %s", error->message); + + g_error_free(error); + + return NULL; + } + + rval = g_regex_replace_eval(regex, query, -1, 0, 0, eval_cb, entries, NULL); + + g_regex_unref(regex); + + return rval; +} + +static GList * +resolve_paths (const gchar *path) +{ + gchar **sschema, **spath; + gchar *schema; + GList *entries; + + spath = g_strsplit(path, "/", 0); + schema = hashfs_mounts_get(spath[1]); + + sschema = g_strsplit(schema, "/", 0); + entries = NULL; + + for (gint i = 2; i < g_strv_length(spath); i++) { + GHashTable *hash = parse_schema(sschema[i]); + gchar *q = g_hash_table_lookup(hash, "q"); + gchar *d = g_hash_table_lookup(hash, "d"); + gchar *query = prepare_query(q, entries); + hashfs_db_entry_t *entry = resolve_path(query, d, spath[i]); + + if (entry) { + entries = g_list_append(entries, entry); + } else { + if (entries) + free_entry_list(entries); + + entries = NULL; + } + + g_free(q); g_free(d); g_free(query); + g_hash_table_unref(hash); + } + + g_strfreev(sschema); + g_strfreev(spath); + + return entries; +} + +static void +hashfs_mounts_add (const gchar *path, const gchar *schema) +{ + g_hash_table_insert(mounts, g_strdup(path), g_strdup_printf("/%s/%s", path, schema)); +} + +static gchar * +hashfs_mounts_get (const gchar *path) +{ + return g_hash_table_lookup(mounts, path); +} + +static gboolean +hashfs_mounts_exists (const gchar *path) +{ + gchar *val; + + val = hashfs_mounts_get(path); + + if (val) + return TRUE; + + return FALSE; +} + +static void +hashfs_mounts_load (void) +{ + if (!mounts) + mounts = g_hash_table_new(g_str_hash, g_str_equal); +} + +static void +hashfs_mounts_destroy (void) +{ + if (mounts) + g_hash_table_unref(mounts); +} + +static gint +hashfs_fuse_listattrs (const gchar *path, struct stat *stats) +{ + GList *entries; + gint rval; + + entries = resolve_paths(path); + + if (entries) { + GList *item = g_list_last(entries); + hashfs_db_entry_t *entry = item->data; + const gchar *pkey; + + pkey = hashfs_db_entry_pkey(entry); + + if (g_strrstr(pkey, "set:")) { + stats->st_mode = S_IFDIR | 0755; + stats->st_nlink = 2; + } else { + struct stat realstats; + const gchar *realpath; + + if (hashfs_db_entry_lookup(entry, "path", &realpath)) { + stat(realpath, &realstats); + + stats->st_mode = S_IFREG | 0444; + stats->st_nlink = 1; + stats->st_size = realstats.st_size; + } + } + + rval = 0; + + free_entry_list(entries); + } else { + rval = -ENOENT; + } + + + return rval; +} + +static gint +hashfs_fuse_getattr (const gchar *path, struct stat *stats) +{ + gint res; + + printf("getattr: %s\n", path); + + memset(stats, 0, sizeof(struct stat)); + res = 0; + + if (g_strcmp0(path, "/") == 0 || hashfs_mounts_exists(path + 1)) { + stats->st_mode = S_IFDIR | 0555; + stats->st_nlink = 2; + } else { + res = hashfs_fuse_listattrs(path, stats); + } + + return res; +} + +static void +hashfs_fuse_listdir (const gchar *squery, const gchar *format, + gpointer buf, fuse_fill_dir_t filler) +{ + hashfs_db_query_t *query; + hashfs_db_result_t *result; + + query = hashfs_db_query_new(squery); + result = hashfs_db_query_result(query); + + printf("listdir, num results: %d, q=%s, d=%s\n", hashfs_db_result_num(result), squery, format); + for (gint i = 0; i < hashfs_db_result_num(result); i++) { + hashfs_db_entry_t *entry; + gchar *formatted; + + entry = hashfs_db_result_get_entry(result, i); + formatted = hashfs_db_entry_format(entry, format); + + filler(buf, formatted, NULL, 0); + + g_free(formatted); + hashfs_db_entry_destroy(entry); + } + + hashfs_db_query_destroy(query); + hashfs_db_result_destroy(result); +} + +static gint +hashfs_fuse_readdir (const gchar *path, gpointer buf, fuse_fill_dir_t filler, + off_t offset, struct fuse_file_info *fi) +{ + printf("readdir: %s\n", path); + + filler(buf, ".", NULL, 0); + filler(buf, "..", NULL, 0); + + if (g_strcmp0(path, "/") == 0) { + GList *keys, *item; + keys = g_hash_table_get_keys(mounts); + + for (item = g_list_first(keys); item; item = g_list_next(item)) { + gchar *key = item->data; + + filler(buf, key, NULL, 0); + } + + g_list_free(keys); + } else { + gchar **sschema, **spath; + gchar *schema; + GList *entries; + + spath = g_strsplit(path, "/", 0); + schema = hashfs_mounts_get(spath[1]); + + sschema = g_strsplit(schema, "/", 0); + entries = NULL; + + for (gint i = 1; i < g_strv_length(spath); i++) { + GHashTable *hash = parse_schema(sschema[i+1]); + gchar *q = g_hash_table_lookup(hash, "q"); + gchar *d = g_hash_table_lookup(hash, "d"); + gchar *query = prepare_query(q, entries); + + if ((i + 1) == g_strv_length(spath)) { + hashfs_fuse_listdir(query, d, buf, filler); + break; + } + + hashfs_db_entry_t *entry = resolve_path(query, d, spath[i+1]); + + if (entry) + entries = g_list_append(entries, entry); + + + g_free(q); g_free(d); g_free(query); + g_hash_table_unref(hash); + } + + g_strfreev(sschema); + g_strfreev(spath); + + if (entries) + free_entry_list(entries); + } + + return 0; +} + +static gint +hashfs_fuse_open (const gchar *path, struct fuse_file_info *fi) +{ + GList *entries, *item; + gint rval = 0; + const gchar *realpath; + hashfs_db_entry_t *entry; + + printf("open: %s\n", path); + + entries = resolve_paths(path); + + if (!entries) + return -ENOENT; + + if ((fi->flags & 3) != O_RDONLY) + return -EACCES; + + item = g_list_last(entries); + entry = item->data; + + if (hashfs_db_entry_lookup(entry, "path", &realpath)) { + fi->fh = open(realpath, fi->flags); + } + + free_entry_list(entries); + + return 0; +} + +static gint +hashfs_fuse_read (const gchar *path, gchar *buf, size_t size, off_t offset, + struct fuse_file_info *fi) +{ + gint rval; + + printf("read %s %d %d\n", path, size, offset); + + lseek(fi->fh, offset, SEEK_SET); + + return read(fi->fh, buf, size); +} + +static gint +hashfs_fuse_release (const gchar *path, struct fuse_file_info *fi) +{ + printf("close %s\n", path); + + return close(fi->fh); +} + +static struct fuse_operations hashfs_fuse_operations = { + .getattr = hashfs_fuse_getattr, + .readdir = hashfs_fuse_readdir, + .open = hashfs_fuse_open, + .read = hashfs_fuse_read, + .release = hashfs_fuse_release, +}; + gint main (gint argc, gchar **argv) { + gint rval; hashfs_config_load(); hashfs_db_open(); + hashfs_mounts_load(); - test_query("pkey.BeginsWith(file:) path.BeginsWith(/tmp)"); - test_query("pkey.BeginsWith(file:) anidb:resolved.Equals(1)"); + + hashfs_mounts_add("by-name", "(q=\"pkey.BeginsWith(set:anidb:anime)\", d=\"$kanji [$eps]\")/(q=\"pkey.BeginsWith(file:), anime.Equals($prev[1].pkey)\", d=\"$anime_kanji - $ep_number - $ep_kanji [$group_name].$ext\")"); + hashfs_mounts_add("by-group", "(q=\"pkey.BeginsWith(set:anidb:group)\", d=\"$name\")/(q=\"pkey.BeginsWith(file:), group.Equals($prev[1].pkey)\", d=\"$basename\")"); + rval = fuse_main(argc, argv, &hashfs_fuse_operations, NULL); hashfs_config_save(); hashfs_db_close(); - return 0; + return rval; }
chrippa/hashfs
1ea395af7327b3cbf849257930eddedffca83f42
Add query stuff to DB API.
diff --git a/src/hashfs/db.c b/src/hashfs/db.c index 6001580..93d7cf0 100644 --- a/src/hashfs/db.c +++ b/src/hashfs/db.c @@ -1,169 +1,311 @@ #include <glib.h> #include <string.h> #include <stdio.h> - #include "hashfs.h" +#define HASHFS_QUERY_PATTERN "([A-Za-z\\:]+)\\.(\\w+)\\((.*?)\\)" +#define LENGTH(x) sizeof(x)/sizeof(x[0]) static hashfs_db_t *db; +typedef struct { + gint op; + gchar *name; +} hashfs_db_query_cond_t; + +static hashfs_db_query_cond_t query_cond[] = { + { TDBQCSTREQ, "Equals" }, + { TDBQCSTRINC, "Contains" }, + { TDBQCSTRBW, "BeginsWith" }, + { TDBQCSTREQ, "EndsWith" }, + { TDBQCSTRAND, "IncludeAll" }, + { TDBQCSTROR, "Include" }, + { TDBQCSTRRX, "Regexp" }, +}; + gboolean hashfs_db_open (void) { gchar *path; gboolean rval; g_return_val_if_fail(db == NULL, FALSE); db = g_new0(hashfs_db_t, 1); db->tdb = tctdbnew(); path = g_build_filename(g_get_user_config_dir(), "hashfs", "metadata.tct", NULL); if (!tctdbopen(db->tdb, path, TDBOWRITER | TDBOCREAT)) { HASHFS_DEBUG("Unable to open DB: %s", hashfs_db_error()); rval = FALSE; } else { HASHFS_DEBUG("Successfully opened DB"); rval = TRUE; } g_free(path); return rval; } void hashfs_db_close (void) { g_return_if_fail(db != NULL); if (!tctdbclose(db->tdb)) { HASHFS_DEBUG("Unable to close DB: %s", hashfs_db_error()); } else { HASHFS_DEBUG("Successfully closed DB"); } tctdbdel(db->tdb); free(db); } gboolean hashfs_db_tran_begin (void) { HASHFS_DEBUG("Starting transsaction"); return (gboolean) tctdbtranbegin(db->tdb); } gboolean hashfs_db_tran_commit (void) { HASHFS_DEBUG("Comitting transsaction"); return (gboolean) tctdbtrancommit(db->tdb); } gboolean hashfs_db_tran_abort (void) { HASHFS_DEBUG("Aborting transsaction"); return (gboolean) tctdbtranabort(db->tdb); } gchar * hashfs_db_error (void) { gint ecode = tctdbecode(db->tdb); return (gchar *) tctdberrmsg(ecode); } hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type) { - hashfs_db_entry_t *entry; gchar *pkey, *md5; - TCMAP *curdata; md5 = hashfs_md5_str(id); - if (!g_strcmp0(prefix, "set")) { + if (!g_strcmp0(prefix, "set")) pkey = g_strdup_printf("%s:%s:%s:%s", prefix, source, type, md5); - } else { + else pkey = g_strdup_printf("%s:%s", prefix, md5); - } + + g_free(md5); + + return hashfs_db_entry_new_from_key(pkey); +} + +hashfs_db_entry_t * +hashfs_db_entry_new_from_key (const gchar *pkey) +{ + hashfs_db_entry_t *entry; + TCMAP *curdata; entry = g_new0(hashfs_db_entry_t, 1); - entry->pkey = pkey; + entry->pkey = g_strdup(pkey); curdata = tctdbget(db->tdb, pkey, strlen(pkey)); if (curdata != NULL) entry->data = curdata; else entry->data = tcmapnew(); HASHFS_DEBUG("Created entry with pkey: %s", pkey); - g_free(md5); - return entry; } void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value) { g_return_if_fail(entry != NULL); g_return_if_fail(entry->data != NULL); tcmapput2(entry->data, key, value); } gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out) { const gchar *val; val = tcmapget2(entry->data, key); if (val == NULL) return FALSE; *out = val; return TRUE; } gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry) { g_return_val_if_fail(entry != NULL, FALSE); g_return_val_if_fail(entry->pkey != NULL, FALSE); g_return_val_if_fail(entry->data != NULL, FALSE); return (gboolean) tctdbputcat(db->tdb, entry->pkey, strlen(entry->pkey), entry->data); } void hashfs_db_entry_destroy (hashfs_db_entry_t *entry) { g_return_if_fail (entry != NULL); if (entry->data) tcmapdel(entry->data); if (entry->pkey) g_free(entry->pkey); g_free(entry); } + +static gint +hashfs_db_query_op (gchar *name) +{ + for (gint i = 0; i < LENGTH(query_cond); i++) { + if (g_strcmp0(name, query_cond[i].name) == 0) + return query_cond[i].op; + } + + return -1; +} + + +hashfs_db_query_t * +hashfs_db_query_new (const gchar *querystr) +{ + GRegex *regex; + GMatchInfo *match; + GError *error = NULL; + hashfs_db_query_t *query; + + query = g_new0(hashfs_db_query_t, 1); + query->query = tctdbqrynew(db->tdb); + + regex = g_regex_new(HASHFS_QUERY_PATTERN, 0, 0, &error); + + if (error) { + HASHFS_DEBUG("Failed to create regex: %s", error->message); + + g_error_free(error); + + return NULL; + } + + g_regex_match(regex, querystr, 0, &match); + while (g_match_info_matches(match)) { + gchar *key = g_match_info_fetch(match, 1); + gchar *func = g_match_info_fetch(match, 2); + gchar *val = g_match_info_fetch(match, 3); + gint op; + + op = hashfs_db_query_op(func); + + HASHFS_DEBUG("Adding query condition: %s.%s(%s)", key, func, val); + + if (op >= 0) { + if (!g_strcmp0(key, "pkey")) + tctdbqryaddcond(query->query, "", op, val); + else + tctdbqryaddcond(query->query, key, op, val); + } + + g_free(key); g_free(func); g_free(val); + g_match_info_next(match, NULL); + } + + g_match_info_free(match); + g_regex_unref(regex); + + return query; +} + +void +hashfs_db_query_set_limit (hashfs_db_query_t *query, gint limit, gint skip) +{ + tctdbqrysetlimit(query->query, limit, skip); +} + +void +hashfs_db_query_set_order (hashfs_db_query_t *query, gchar *key, gint mode) +{ + tctdbqrysetorder(query->query, key, mode); +} + +hashfs_db_result_t * +hashfs_db_query_result (hashfs_db_query_t *query) +{ + hashfs_db_result_t *result; + + result = g_new0(hashfs_db_result_t, 1); + result->list = tctdbqrysearch(query->query); + + return result; +} + +void +hashfs_db_query_destroy (hashfs_db_query_t *query) +{ + if (query->query) + tctdbqrydel(query->query); + + g_free(query); +} + +gint +hashfs_db_result_num (hashfs_db_result_t *result) +{ + return (gint) tclistnum(result->list); +} + +hashfs_db_entry_t * +hashfs_db_result_get_entry (hashfs_db_result_t *result, gint index) +{ + const gchar *key; + gint len; + + key = tclistval(result->list, index, &len); + + return hashfs_db_entry_new_from_key(key); +} + +void +hashfs_db_result_destroy (hashfs_db_result_t *result) +{ + if (result->list) + tclistdel(result->list); + + g_free(result); +} + diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index e341b3c..bcfa01e 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,220 +1,220 @@ #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { if (hashfs_backend_glob_try(backend, path)) { hashfs_file_t *file; - HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); + HASHFS_LOG("Handling file: %s", hashfs_basename(path)); file = hashfs_file_new(path, backend); hashfs_backend_file(backend, file); hashfs_file_destroy(file); } } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; - HASHFS_LOG("Hashing dir: %s", path); + HASHFS_LOG("Searching directory: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; gchar *val; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { hashfs_config_property_lookup(groups[i], keys[j], &val); printf("%s.%s = %s\n", groups[i], keys[j], val); g_free(val); } g_strfreev(keys); } g_strfreev(groups); } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } g_free(val); g_strfreev(split); } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } g_strfreev(split); } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; hashfs_config_load(); hashfs_db_open(); if (g_module_supported()) { hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); hashfs_backends_destroy(); hashfs_config_save(); hashfs_db_close(); return 0; } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index b19ccb6..ced5439 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,178 +1,208 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include <tcutil.h> #include <tctdb.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_db_St; struct hashfs_db_entry_St; +struct hashfs_db_result_St; +struct hashfs_db_query_St; struct hashfs_file_St; struct hashfs_set_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_db_St hashfs_db_t; typedef struct hashfs_db_entry_St hashfs_db_entry_t; +typedef struct hashfs_db_result_St hashfs_db_result_t; +typedef struct hashfs_db_query_St hashfs_db_query_t; typedef struct hashfs_file_St hashfs_file_t; typedef struct hashfs_set_St hashfs_set_t; struct hashfs_backend_St { gpointer data; GList *globs; GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; struct hashfs_db_St { TCTDB *tdb; }; struct hashfs_db_entry_St { TCMAP *data; gchar *pkey; }; +struct hashfs_db_result_St { + TCLIST *list; +}; + +struct hashfs_db_query_St { + TDBQRY *query; +}; + + struct hashfs_file_St { gchar *filename; gint64 size; GList *sets; hashfs_backend_t *backend; hashfs_db_entry_t *entry; /* Hashes */ gchar *ed2k; gchar *md5; }; struct hashfs_set_St { gchar name[256]; hashfs_db_entry_t *entry; }; /* Config */ GKeyFile * hashfs_config_keyfile (void); void hashfs_config_load (void); void hashfs_config_save (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); /* Database */ gboolean hashfs_db_open (void); void hashfs_db_close (void); gchar * hashfs_db_error (void); gboolean hashfs_db_tran_abort (void); gboolean hashfs_db_tran_begin (void); gboolean hashfs_db_tran_commit (void); + /* Database entry */ hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type); +hashfs_db_entry_t * hashfs_db_entry_new_from_key (const gchar *key); gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out); void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value); gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry); void hashfs_db_entry_destroy (hashfs_db_entry_t *entry); + +/* Database query */ +hashfs_db_query_t * hashfs_db_query_new (const gchar *querystr); +hashfs_db_result_t * hashfs_db_query_result (hashfs_db_query_t *query); +void hashfs_db_query_set_limit (hashfs_db_query_t *query, gint limit, gint skip); +void hashfs_db_query_set_order (hashfs_db_query_t *query, gchar *key, gint mode); +void hashfs_db_query_destroy (hashfs_db_query_t *query); + + +/* Database result list */ +gint hashfs_db_result_num (hashfs_db_result_t *result); +hashfs_db_entry_t * hashfs_db_result_get_entry (hashfs_db_result_t *result, gint index); +void hashfs_db_result_destroy (hashfs_db_result_t *result); + + /* Set */ hashfs_set_t * hashfs_set_new (const gchar *name, const gchar *source, const gchar *type); gboolean hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, const gchar **out); void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, const gchar *value); void hashfs_set_destroy (hashfs_set_t *set); /* File */ hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend); gboolean hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_hash_md5 (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value); hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type); void hashfs_file_destroy (hashfs_file_t *file); /* Backend manager */ hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); void hashfs_backends_load (const gchar *path); void hashfs_backends_destroy (void); /* Backend */ hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); void hashfs_backend_glob_set (hashfs_backend_t *backend, ...); gboolean hashfs_backend_glob_try (hashfs_backend_t *backend, const gchar *filename); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, const gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); /* Utils */ gchar * hashfs_current_time (void); gchar * hashfs_basename (const gchar *name); gchar * hashfs_md5_str (const gchar *str); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ gchar *log_time = hashfs_current_time(); \ printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ gchar *log_time = hashfs_current_time(); \ FILE *fd = g_fopen(log_path, "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ g_free(log_path); \ g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif diff --git a/src/hashfs/hashfsmount.c b/src/hashfs/hashfsmount.c index 7c3885f..21dd5af 100644 --- a/src/hashfs/hashfsmount.c +++ b/src/hashfs/hashfsmount.c @@ -1,16 +1,52 @@ #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> - #include <fuse.h> +#include "hashfs.h" -int -main(int argc, char *argv[]) +void test_query (gchar *querystr) { + hashfs_db_query_t *query; + hashfs_db_result_t *result; + + + query = hashfs_db_query_new(querystr); + result = hashfs_db_query_result(query); + + printf("num results: %d\n", hashfs_db_result_num(result)); + + for (gint i = 0; i < hashfs_db_result_num(result); i++) { + hashfs_db_entry_t *entry; + const gchar *tmp; + + entry = hashfs_db_result_get_entry(result, i); + + if (hashfs_db_entry_lookup(entry, "path", &tmp)) + printf("path = %s\n", tmp); + + hashfs_db_entry_destroy(entry); + } + + + hashfs_db_query_destroy(query); + hashfs_db_result_destroy(result); +} + +gint +main (gint argc, gchar **argv) +{ + + hashfs_config_load(); + hashfs_db_open(); + + test_query("pkey.BeginsWith(file:) path.BeginsWith(/tmp)"); + test_query("pkey.BeginsWith(file:) anidb:resolved.Equals(1)"); + hashfs_config_save(); + hashfs_db_close(); return 0; }
chrippa/hashfs
c22a5a7624d8e65233b951b885a0363a978349c8
Use transsactions.
diff --git a/src/hashfs/db.c b/src/hashfs/db.c index 02b2a76..6001580 100644 --- a/src/hashfs/db.c +++ b/src/hashfs/db.c @@ -1,163 +1,169 @@ #include <glib.h> #include <string.h> #include <stdio.h> #include "hashfs.h" static hashfs_db_t *db; gboolean hashfs_db_open (void) { gchar *path; gboolean rval; g_return_val_if_fail(db == NULL, FALSE); db = g_new0(hashfs_db_t, 1); db->tdb = tctdbnew(); path = g_build_filename(g_get_user_config_dir(), "hashfs", "metadata.tct", NULL); if (!tctdbopen(db->tdb, path, TDBOWRITER | TDBOCREAT)) { HASHFS_DEBUG("Unable to open DB: %s", hashfs_db_error()); rval = FALSE; } else { HASHFS_DEBUG("Successfully opened DB"); rval = TRUE; } g_free(path); return rval; } void hashfs_db_close (void) { g_return_if_fail(db != NULL); if (!tctdbclose(db->tdb)) { HASHFS_DEBUG("Unable to close DB: %s", hashfs_db_error()); } else { HASHFS_DEBUG("Successfully closed DB"); } tctdbdel(db->tdb); free(db); } gboolean hashfs_db_tran_begin (void) { + HASHFS_DEBUG("Starting transsaction"); + return (gboolean) tctdbtranbegin(db->tdb); } gboolean hashfs_db_tran_commit (void) { + HASHFS_DEBUG("Comitting transsaction"); + return (gboolean) tctdbtrancommit(db->tdb); } gboolean hashfs_db_tran_abort (void) { + HASHFS_DEBUG("Aborting transsaction"); + return (gboolean) tctdbtranabort(db->tdb); } gchar * hashfs_db_error (void) { gint ecode = tctdbecode(db->tdb); return (gchar *) tctdberrmsg(ecode); } hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type) { hashfs_db_entry_t *entry; gchar *pkey, *md5; TCMAP *curdata; md5 = hashfs_md5_str(id); if (!g_strcmp0(prefix, "set")) { pkey = g_strdup_printf("%s:%s:%s:%s", prefix, source, type, md5); } else { pkey = g_strdup_printf("%s:%s", prefix, md5); } entry = g_new0(hashfs_db_entry_t, 1); entry->pkey = pkey; curdata = tctdbget(db->tdb, pkey, strlen(pkey)); if (curdata != NULL) entry->data = curdata; else entry->data = tcmapnew(); HASHFS_DEBUG("Created entry with pkey: %s", pkey); g_free(md5); return entry; } void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value) { g_return_if_fail(entry != NULL); g_return_if_fail(entry->data != NULL); tcmapput2(entry->data, key, value); } gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out) { const gchar *val; val = tcmapget2(entry->data, key); if (val == NULL) return FALSE; *out = val; return TRUE; } gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry) { g_return_val_if_fail(entry != NULL, FALSE); g_return_val_if_fail(entry->pkey != NULL, FALSE); g_return_val_if_fail(entry->data != NULL, FALSE); return (gboolean) tctdbputcat(db->tdb, entry->pkey, strlen(entry->pkey), entry->data); } void hashfs_db_entry_destroy (hashfs_db_entry_t *entry) { g_return_if_fail (entry != NULL); if (entry->data) tcmapdel(entry->data); if (entry->pkey) g_free(entry->pkey); g_free(entry); } diff --git a/src/hashfs/file.c b/src/hashfs/file.c index 4ad70fc..c8aec1f 100644 --- a/src/hashfs/file.c +++ b/src/hashfs/file.c @@ -1,98 +1,101 @@ #include <glib.h> #include "hashfs.h" hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend) { hashfs_file_t *file; struct stat info; stat(filename, &info); file = g_new0(hashfs_file_t, 1); file->backend = backend; file->entry = hashfs_db_entry_new("file", filename, NULL, NULL); file->filename = g_strdup(filename); file->size = (gint64) info.st_size; file->ed2k = NULL; file->md5 = NULL; + hashfs_db_tran_begin(); hashfs_db_entry_set(file->entry, "path", filename); return file; } gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out) { HASHFS_DEBUG("File (%s) looking up property: %s", hashfs_basename(file->filename), key); return hashfs_db_entry_lookup(file->entry, key, out); } void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value) { HASHFS_DEBUG("File (%s) setting property: %s = %s", hashfs_basename(file->filename), key, value); hashfs_db_entry_set(file->entry, key, value); } hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type) { hashfs_set_t *set; const gchar *source; if (file->backend) source = file->backend->desc->shortname; else source = "unknown"; set = hashfs_set_new(name, source, type); hashfs_db_entry_set(file->entry, type, set->entry->pkey); file->sets = g_list_append(file->sets, set); return set; } void hashfs_file_destroy (hashfs_file_t *file) { HASHFS_DEBUG("File (%s) destroying", hashfs_basename(file->filename)); + hashfs_db_tran_commit(); + if (file->filename) g_free(file->filename); if (file->ed2k) g_free(file->ed2k); if (file->md5) g_free(file->md5); if (file->sets) { GList *item; hashfs_set_t *set; for (item = g_list_first(file->sets); item; item = g_list_next(item)) { set = item->data; hashfs_set_destroy(set); } g_list_free(file->sets); } if (file->entry) { hashfs_db_entry_put(file->entry); hashfs_db_entry_destroy(file->entry); } g_free(file); }
chrippa/hashfs
5ba81f7ae0e726f92f1bf2ec6094d15eaf0692d9
Cleanup wscript's a bit.
diff --git a/src/backends/anidb/wscript b/src/backends/anidb/wscript index 3f38dd6..4dcc5b7 100644 --- a/src/backends/anidb/wscript +++ b/src/backends/anidb/wscript @@ -1,29 +1,22 @@ # vim: set fileencoding=utf-8 filetype=python : files = ['anidb.c'] def set_options(opt): pass def configure(conf): pass def build(bld): - import Options - - defines = [] - - if Options.options.debug: - defines += ['DEBUG'] - obj = bld.new_task_gen( features = 'cc cshlib', source = files, target = 'hashfs_anidb', includes = '. ../../hashfs', install_path = '${PREFIX}/lib/hashfs', ccflags = ['-std=gnu99', '-g'], - defines = defines, + defines = bld.env['defines'], uselib = 'glib-2.0', uselib_local = 'anidb', ) diff --git a/src/hashfs/wscript b/src/hashfs/wscript index 7dab0c8..e0e5f09 100644 --- a/src/hashfs/wscript +++ b/src/hashfs/wscript @@ -1,42 +1,37 @@ # vim: set fileencoding=utf-8 filetype=python : -hashfs = ['hashfs.c', 'db.c', 'ed2k.c', 'config.c', 'backend.c', 'util.c', 'set.c', 'file.c'] -hashfsmount = ['hashfsmount.c', 'util.c'] +common = ['config.c', 'backend.c', 'db.c', 'ed2k.c', 'file.c', 'set.c', 'util.c'] +common_libs = 'glib-2.0 gmodule-2.0 tokyocabinet openssl' + +hashfs = ['hashfs.c'] + common +hashfsmount = ['hashfsmount.c'] + common def set_options(opt): pass def configure(conf): for pkg in ['fuse', 'glib-2.0', 'gmodule-2.0', 'tokyocabinet', 'openssl']: if not conf.check_cfg(package = pkg, args = '--cflags --libs', uselib_store = pkg): conf.fatal('Unable to find required library') def build(bld): - import Options - - defines = [] - - if Options.options.debug: - defines += ['DEBUG'] - obj = bld.new_task_gen( features = 'cc cprogram', source = hashfs, target = 'hashfs', install_path = '${PREFIX}/bin', - uselib = 'glib-2.0 gmodule-2.0 tokyocabinet openssl', - uselib_local = 'anidb', + uselib = common_libs, ccflags = ['-std=gnu99', '-g'], - defines = defines + defines = bld.env['defines'] ) obj = bld.new_task_gen( features = 'cc cprogram', source = hashfsmount, target = 'hashfsmount', - uselib = 'fuse glib-2.0', + uselib = 'fuse ' + common_libs, install_path = '${PREFIX}/bin', ccflags = ['-std=gnu99', '-g'], - defines = defines + defines = bld.env['defines'] ) diff --git a/src/lib/libanidb/wscript b/src/lib/libanidb/wscript index 8cf18d5..77f7ccd 100644 --- a/src/lib/libanidb/wscript +++ b/src/lib/libanidb/wscript @@ -1,30 +1,24 @@ # vim: set fileencoding=utf-8 filetype=python : files = ['handlers.c', 'anidb.c'] def set_options(opt): pass def configure(conf): for lib in ['rt']: if not conf.check_cc(lib = lib, uselib_store = lib): conf.fatal('Unable to find required library') def build(bld): - import Options - - defines = [] - if Options.options.debug: - defines += ['DEBUG'] - obj = bld.new_task_gen( features = 'cc cstaticlib', target = 'anidb', source = files, - defines = defines, + defines = bld.env['defines'], ccflags = ['-std=gnu99', '-g'], uselib = 'rt', install_path = False, export_incdirs = '.' ) diff --git a/wscript b/wscript index a6ce7e4..83ae437 100644 --- a/wscript +++ b/wscript @@ -1,36 +1,43 @@ # vim: set fileencoding=utf-8 filetype=python : from logging import fatal, info import os srcdir = '.' blddir = '_build_' bckenddir = 'src/backends' def is_backend(x): return os.path.exists(os.path.join(bckenddir, x, 'wscript')) hashfs = ['src/hashfs'] libs = ['src/lib/libanidb', 'src/lib/libanidb/tests'] backends = [os.path.join(bckenddir, p) for p in os.listdir(bckenddir) if is_backend(p)] subdirs = hashfs + libs + backends def set_options(opt): opt.add_option('--debug', action = 'store_true', default = True, help = 'Enable debug') for dir in subdirs: opt.sub_options(dir) def configure(conf): - import Options - conf.check_tool('gcc') + for dir in subdirs: conf.sub_config(dir) def build(bld): + import Options + + bld.env['defines'] = [] + + if Options.options.debug: + bld.env['defines'] += ['DEBUG'] + + bld.add_subdirs(subdirs)
chrippa/hashfs
280d5587a3e5e962fcbeea328f91b3f3db2e7106
Only mark files as resolved when actually found on AniDB.
diff --git a/src/backends/anidb/anidb.c b/src/backends/anidb/anidb.c index 2bafa88..b8cb19c 100644 --- a/src/backends/anidb/anidb.c +++ b/src/backends/anidb/anidb.c @@ -1,230 +1,233 @@ #include <stdio.h> #include <hashfs.h> #include <anidb.h> static void hashfs_anidb_setup (hashfs_backend_t *backend); static gboolean hashfs_anidb_init (hashfs_backend_t *backend); static void hashfs_anidb_destroy (hashfs_backend_t *backend); static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file); static void dump_result (anidb_result_t *result); HASHFS_BACKEND("anidb", "AniDB", "AniDB hashing backend", hashfs_anidb_setup); typedef struct hashfs_anidb_data_St { anidb_session_t *session; } hashfs_anidb_data_t; static void hashfs_anidb_setup (hashfs_backend_t *backend) { backend->funcs.init = hashfs_anidb_init; backend->funcs.file = hashfs_anidb_handle_file; backend->funcs.destroy = hashfs_anidb_destroy; hashfs_backend_config_register(backend, "username", ""); hashfs_backend_config_register(backend, "password", ""); hashfs_backend_config_register(backend, "local_port", "0"); } static gboolean hashfs_anidb_init (hashfs_backend_t *backend) { anidb_session_t *session; anidb_result_t *res; hashfs_anidb_data_t *data; gchar *username, *password, *port_s; const gchar *key; gint port; gboolean rval; HASHFS_DEBUG("Connecting to AniDB"); hashfs_backend_config_lookup(backend, "username", &username); hashfs_backend_config_lookup(backend, "password", &password); hashfs_backend_config_lookup(backend, "local_port", &port_s); hashfs_backend_glob_set(backend, "*.avi", "*.mkv", "*.ogm", "*.mpg", "*.mpeg", "*.ogg", "*.ogv", "*.mp4", "*.rm", "*.divx", "*.xvid", - "*.flv", NULL); + "*.flv", "*.wmv", "*.rmvb", NULL); port = atoi(port_s); HASHFS_DEBUG("username=%s, password=%s, port=%d", username, password, port); session = anidb_session_new("anidbfuse", "1", port); data = g_new0(hashfs_anidb_data_t, 1); data->session = session; backend->data = data; res = anidb_session_authenticate(session, username, password); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); HASHFS_DEBUG("Successfully logged in"); rval = TRUE; } else { HASHFS_DEBUG("Failed to get session key"); rval = FALSE; } } else { HASHFS_DEBUG("Unable to login to AniDB servers"); rval = FALSE; } g_free(username); g_free(password); g_free(port_s); anidb_result_unref(res); return rval; } static void hashfs_anidb_destroy (hashfs_backend_t *backend) { hashfs_anidb_data_t *data; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; if (data) { if (anidb_session_is_logged_in(data->session)) { HASHFS_DEBUG("Logging out"); anidb_result_unref(anidb_session_logout(data->session)); } anidb_session_unref(data->session); g_free(data); } } static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file) { hashfs_anidb_data_t *data; const gchar *hash, *resolved; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; g_return_if_fail(data); /* File is marked as resolved, don't hash or lookup data */ if (hashfs_file_prop_lookup(file, "anidb:resolved", &resolved)) { if (atoi(resolved) > 0) return; } if (anidb_session_is_logged_in(data->session)) { if (hashfs_file_hash_ed2k(file, &hash)) { hashfs_set_t *set; anidb_result_t *res; const gchar *tmp, *aid, *gid; HASHFS_DEBUG("ed2k hash: %s", hash); res = anidb_session_file_ed2k(data->session, file->size, hash); for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; dict = anidb_dict_next(dict)) { hashfs_file_prop_set(file, dict->key, dict->value); } if (anidb_result_dict_get(res, "aid", &aid)) { set = hashfs_file_add_to_set(file, aid, "anime"); if (!hashfs_set_prop_lookup(set, "aid", &tmp)) { anidb_result_t *res; HASHFS_DEBUG("Need to lookup anime!"); res = anidb_session_anime_id(data->session, atoi(aid)); for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; dict = anidb_dict_next(dict)) { hashfs_set_prop_set(set, dict->key, dict->value); } anidb_result_unref(res); } } if (anidb_result_dict_get(res, "gid", &gid)) { set = hashfs_file_add_to_set(file, gid, "group"); if (!hashfs_set_prop_lookup(set, "gid", &tmp)) { anidb_result_t *res; HASHFS_DEBUG("Need to lookup group!"); res = anidb_session_group_id(data->session, atoi(gid)); for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; dict = anidb_dict_next(dict)) { hashfs_set_prop_set(set, dict->key, dict->value); } anidb_result_unref(res); } } - hashfs_file_prop_set(file, "anidb:resolved", "1"); + if (anidb_result_get_type(res) == ANIDB_RESULT_DICT) + hashfs_file_prop_set(file, "anidb:resolved", "1"); + else + hashfs_file_prop_set(file, "anidb:resolved", "0"); anidb_result_unref(res); } } } static void dump_result (anidb_result_t *result) { gint n; const gchar *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: HASHFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); HASHFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); HASHFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: HASHFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { HASHFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); } HASHFS_DEBUG(">"); break; } } diff --git a/src/lib/libanidb/anidb.c b/src/lib/libanidb/anidb.c index a73a0f4..651b4b2 100644 --- a/src/lib/libanidb/anidb.c +++ b/src/lib/libanidb/anidb.c @@ -1,757 +1,760 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include <time.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, const char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static int get_ms (void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } static void throttle_session (anidb_session_t *session) { int elapsed, needtosleep; elapsed = get_ms() - session->time; needtosleep = ANIDB_THROTTLE_MS - elapsed; if (needtosleep > 0) { usleep(needtosleep * 1000); } session->time = get_ms(); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; // printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; // printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version, int localport) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } if (localport > 0) { local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(localport); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:%d", localport); } } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; strncpy(session->clientname, name, sizeof(session->clientname)); strncpy(session->clientversion, version, sizeof(session->clientversion)); anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); free(session); } } void anidb_session_set_key (anidb_session_t *session, const char *key) { strncpy(session->key, key, sizeof(session->key)); } int anidb_session_is_logged_in (anidb_session_t *session) { if (session->key[0]) return 1; return 0; } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, const char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; - sprintf(out, "%s ", cmd); + snprintf(out, sizeof(out), "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { + if (anidb_handlers[i].func == NULL) + break; + if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, const char *username, const char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, const char *name) { anidb_result_t *res; throttle_session(session); res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; - char aid[10]; + char aid[50]; - sprintf(aid, "%d", id); + snprintf(aid, sizeof(aid), "%d", id); throttle_session(session); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; - char aid[10]; - char part[10]; + char aid[50]; + char part[50]; - sprintf(aid, "%d", id); - sprintf(part, "%d", n); + snprintf(aid, sizeof(aid), "%d", id); + snprintf(part, sizeof(part), "%d", n); throttle_session(session); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; - char eid[10]; + char eid[50]; - sprintf(eid, "%d", id); + snprintf(eid, sizeof(eid), "%d", id); throttle_session(session); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, const char *name, int ep) { anidb_result_t *res; - char epno[10]; + char epno[50]; - sprintf(epno, "%d", ep); + snprintf(epno, sizeof(epno), "%d", ep); throttle_session(session); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; - char aid[10]; - char epno[10]; + char aid[50]; + char epno[50]; - sprintf(aid, "%d", id); - sprintf(epno, "%d", ep); + snprintf(aid, sizeof(aid), "%d", id); + snprintf(epno, sizeof(epno), "%d", ep); throttle_session(session); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; - char fid[10]; + char fid[50]; - sprintf(fid, "%d", id); + snprintf(fid, sizeof(fid), "%d", id); throttle_session(session); res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, const char *ed2k) { anidb_result_t *res; char siz[50]; - sprintf(siz, "%d", size); + snprintf(siz, sizeof(siz), "%d", size); throttle_session(session); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; - char gid[10]; + char gid[50]; - sprintf(gid, "%d", id); + snprintf(gid, sizeof(gid), "%d", id); throttle_session(session); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, const char *name) { anidb_result_t *res; throttle_session(session); res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; - char fid[10]; + char fid[50]; - sprintf(fid, "%d", id); + snprintf(fid, sizeof(fid), "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, const char *ed2k) { anidb_result_t *res; - char siz[20]; + char siz[50]; - sprintf(siz, "%d", size); + snprintf(siz, sizeof(siz), "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; - char lid[10]; + char lid[50]; - sprintf(lid, "%d", id); + snprintf(lid, sizeof(lid), "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; - char fid[10]; + char fid[50]; - sprintf(fid, "%d", id); + snprintf(fid, sizeof(fid), "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, const char *ed2k) { anidb_result_t *res; - char siz[20]; + char siz[50]; - sprintf(siz, "%d", size); + snprintf(siz, sizeof(siz), "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, const char *key, const char *value) { strncpy(dict->key, key, sizeof(dict->key)); strncpy(dict->value, value, sizeof(dict->value)); } int anidb_dict_get (anidb_dict_t *dict, const char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, const char *string) { result->type = ANIDB_RESULT_STRING; strncpy(result->value.string, string, sizeof(result->value.string)); } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, const char *key, const char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, const char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } int anidb_result_dict_get (anidb_result_t *result, const char *key, const char **out) { anidb_dict_t *dict; if (result->type != ANIDB_RESULT_DICT) return 0; for (dict = result->value.dict; dict; dict = dict->next) { if (!strcmp(dict->key, key)) { return anidb_dict_get(dict, out); } } return 0; } anidb_dict_t * anidb_result_get_dict (anidb_result_t *result) { if (result->type != ANIDB_RESULT_DICT) return NULL; return result->value.dict; }
chrippa/hashfs
ddd833f7f8d1ff4cb231ca2c843d6d4bcb0ef8fe
Avoid unnecessary anidb lookups by marking files as resolved and globbing filenames against known file formats.
diff --git a/src/backends/anidb/anidb.c b/src/backends/anidb/anidb.c index b60d053..2bafa88 100644 --- a/src/backends/anidb/anidb.c +++ b/src/backends/anidb/anidb.c @@ -1,218 +1,230 @@ #include <stdio.h> #include <hashfs.h> #include <anidb.h> static void hashfs_anidb_setup (hashfs_backend_t *backend); static gboolean hashfs_anidb_init (hashfs_backend_t *backend); static void hashfs_anidb_destroy (hashfs_backend_t *backend); static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file); static void dump_result (anidb_result_t *result); HASHFS_BACKEND("anidb", "AniDB", "AniDB hashing backend", hashfs_anidb_setup); typedef struct hashfs_anidb_data_St { anidb_session_t *session; } hashfs_anidb_data_t; static void hashfs_anidb_setup (hashfs_backend_t *backend) { backend->funcs.init = hashfs_anidb_init; backend->funcs.file = hashfs_anidb_handle_file; backend->funcs.destroy = hashfs_anidb_destroy; hashfs_backend_config_register(backend, "username", ""); hashfs_backend_config_register(backend, "password", ""); hashfs_backend_config_register(backend, "local_port", "0"); } static gboolean hashfs_anidb_init (hashfs_backend_t *backend) { anidb_session_t *session; anidb_result_t *res; hashfs_anidb_data_t *data; gchar *username, *password, *port_s; const gchar *key; gint port; gboolean rval; HASHFS_DEBUG("Connecting to AniDB"); hashfs_backend_config_lookup(backend, "username", &username); hashfs_backend_config_lookup(backend, "password", &password); hashfs_backend_config_lookup(backend, "local_port", &port_s); + hashfs_backend_glob_set(backend, "*.avi", "*.mkv", "*.ogm", + "*.mpg", "*.mpeg", "*.ogg", "*.ogv", + "*.mp4", "*.rm", "*.divx", "*.xvid", + "*.flv", NULL); port = atoi(port_s); HASHFS_DEBUG("username=%s, password=%s, port=%d", username, password, port); session = anidb_session_new("anidbfuse", "1", port); data = g_new0(hashfs_anidb_data_t, 1); data->session = session; backend->data = data; res = anidb_session_authenticate(session, username, password); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); HASHFS_DEBUG("Successfully logged in"); rval = TRUE; } else { HASHFS_DEBUG("Failed to get session key"); rval = FALSE; } } else { HASHFS_DEBUG("Unable to login to AniDB servers"); rval = FALSE; } g_free(username); g_free(password); g_free(port_s); anidb_result_unref(res); return rval; } static void hashfs_anidb_destroy (hashfs_backend_t *backend) { hashfs_anidb_data_t *data; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; if (data) { if (anidb_session_is_logged_in(data->session)) { HASHFS_DEBUG("Logging out"); anidb_result_unref(anidb_session_logout(data->session)); } anidb_session_unref(data->session); g_free(data); } } static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file) { hashfs_anidb_data_t *data; - const gchar *hash; + const gchar *hash, *resolved; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; g_return_if_fail(data); + /* File is marked as resolved, don't hash or lookup data */ + if (hashfs_file_prop_lookup(file, "anidb:resolved", &resolved)) { + if (atoi(resolved) > 0) + return; + } + if (anidb_session_is_logged_in(data->session)) { if (hashfs_file_hash_ed2k(file, &hash)) { hashfs_set_t *set; anidb_result_t *res; const gchar *tmp, *aid, *gid; HASHFS_DEBUG("ed2k hash: %s", hash); res = anidb_session_file_ed2k(data->session, file->size, hash); for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; dict = anidb_dict_next(dict)) { hashfs_file_prop_set(file, dict->key, dict->value); } if (anidb_result_dict_get(res, "aid", &aid)) { set = hashfs_file_add_to_set(file, aid, "anime"); if (!hashfs_set_prop_lookup(set, "aid", &tmp)) { anidb_result_t *res; HASHFS_DEBUG("Need to lookup anime!"); res = anidb_session_anime_id(data->session, atoi(aid)); for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; dict = anidb_dict_next(dict)) { hashfs_set_prop_set(set, dict->key, dict->value); } anidb_result_unref(res); } } if (anidb_result_dict_get(res, "gid", &gid)) { set = hashfs_file_add_to_set(file, gid, "group"); if (!hashfs_set_prop_lookup(set, "gid", &tmp)) { anidb_result_t *res; HASHFS_DEBUG("Need to lookup group!"); res = anidb_session_group_id(data->session, atoi(gid)); for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; dict = anidb_dict_next(dict)) { hashfs_set_prop_set(set, dict->key, dict->value); } anidb_result_unref(res); } } + hashfs_file_prop_set(file, "anidb:resolved", "1"); + anidb_result_unref(res); } } } static void dump_result (anidb_result_t *result) { gint n; const gchar *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: HASHFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); HASHFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); HASHFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: HASHFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { HASHFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); } HASHFS_DEBUG(">"); break; } } diff --git a/src/hashfs/backend.c b/src/hashfs/backend.c index 5dc95eb..a526823 100644 --- a/src/hashfs/backend.c +++ b/src/hashfs/backend.c @@ -1,189 +1,236 @@ #include <glib.h> #include <gmodule.h> #include "hashfs.h" static GList *backends; hashfs_backend_t * hashfs_backend_load (const gchar *path) { GModule *module; gpointer sym; hashfs_backend_t *backend; hashfs_backend_desc_t *desc; HASHFS_DEBUG("Loading module (%s)", path); module = g_module_open(path, 0); if (!module) { HASHFS_DEBUG("Failed to load module: %s", g_module_error()); return NULL; } if (!g_module_symbol(module, "HASHFS_BACKEND_DESC", (gpointer) &sym)) { HASHFS_DEBUG("Failed to lookup symbol: %s", g_module_error()); g_module_close(module); return NULL; } desc = (hashfs_backend_desc_t *) sym; if (!desc) { HASHFS_DEBUG("HASHFS_BACKEND_DESC == NULL"); g_module_close(module); return NULL; } if (hashfs_backends_lookup(desc->shortname)) { HASHFS_DEBUG("Already loaded backend %s", desc->shortname); g_module_close(module); return NULL; } backend = g_new0(hashfs_backend_t, 1); backend->desc = desc; backend->module = module; desc->setup_func(backend); HASHFS_DEBUG("Backend successfully loaded: %s - %s - %s", desc->shortname, desc->name, desc->description); return backend; } void hashfs_backends_load (const gchar *path) { GDir *dir; GError *error = NULL; const gchar *filename; gchar *pattern, *glob; hashfs_backend_t *backend; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } glob = g_module_build_path(path, "hashfs_*"); pattern = g_path_get_basename(glob); HASHFS_DEBUG("Loooking for backends in: %s", glob); while ((filename = g_dir_read_name(dir))) { if (!g_pattern_match_simple(pattern, filename)) continue; gchar *fullpath = g_build_filename(path, filename, NULL); if (!g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { g_free(fullpath); continue; } backend = hashfs_backend_load(fullpath); if (backend) { backends = g_list_append(backends, backend); } g_free(fullpath); } g_dir_close(dir); g_free(glob); g_free(pattern); } hashfs_backend_t * hashfs_backends_lookup (const gchar *name) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; if (!g_strcmp0(name, backend->desc->shortname)) return backend; } return NULL; } void hashfs_backends_destroy (void) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; hashfs_backend_destroy(backend); } g_list_free(backends); } void hashfs_backend_init (hashfs_backend_t *backend) { if (backend->funcs.init) { backend->funcs.init(backend); } } void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file) { if (backend->funcs.file) { backend->funcs.file(backend, file); } } +void +hashfs_backend_glob_set (hashfs_backend_t *backend, ...) +{ + GPatternSpec *spec; + va_list va; + + + va_start(va, backend); + + for (gchar *str = va_arg(va, char *); str; str = va_arg(va, char *)) { + HASHFS_DEBUG("Backend (%s) accepting glob: %s", backend->desc->shortname, str); + + spec = g_pattern_spec_new(str); + + backend->globs = g_list_append(backend->globs, spec); + } +} + +gboolean +hashfs_backend_glob_try (hashfs_backend_t *backend, const gchar *filename) +{ + GPatternSpec *spec; + GList *item; + + for (item = g_list_first(backend->globs); item; item = g_list_next(item)) { + spec = item->data; + + if (g_pattern_match_string(spec, filename)) + return TRUE; + } + + return FALSE; +} + void hashfs_backend_destroy (hashfs_backend_t *backend) { if (backend->funcs.destroy) { backend->funcs.destroy(backend); } if (backend->module) g_module_close(backend->module); + if (backend->globs) { + GPatternSpec *spec; + GList *item; + + for (item = g_list_first(backend->globs); item; item = g_list_next(item)) { + spec = item->data; + + g_pattern_spec_free(spec); + } + + g_list_free(backend->globs); + } + g_free(backend); } void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, const gchar *defaultval) { if (!hashfs_config_property_exists(backend->desc->shortname, key)) { hashfs_config_property_set(backend->desc->shortname, key, defaultval); } } void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out) { hashfs_config_property_lookup(backend->desc->shortname, key, out); } diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index c983713..e341b3c 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,218 +1,220 @@ #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { - hashfs_file_t *file; + if (hashfs_backend_glob_try(backend, path)) { + hashfs_file_t *file; - HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); + HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); - file = hashfs_file_new(path, backend); - hashfs_backend_file(backend, file); + file = hashfs_file_new(path, backend); + hashfs_backend_file(backend, file); - hashfs_file_destroy(file); + hashfs_file_destroy(file); + } } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; HASHFS_LOG("Hashing dir: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; gchar *val; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { hashfs_config_property_lookup(groups[i], keys[j], &val); printf("%s.%s = %s\n", groups[i], keys[j], val); g_free(val); } g_strfreev(keys); } g_strfreev(groups); } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } g_free(val); g_strfreev(split); } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } g_strfreev(split); } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; hashfs_config_load(); hashfs_db_open(); if (g_module_supported()) { hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); hashfs_backends_destroy(); hashfs_config_save(); hashfs_db_close(); return 0; } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index e776089..b19ccb6 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,175 +1,178 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include <tcutil.h> #include <tctdb.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_db_St; struct hashfs_db_entry_St; struct hashfs_file_St; struct hashfs_set_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_db_St hashfs_db_t; typedef struct hashfs_db_entry_St hashfs_db_entry_t; typedef struct hashfs_file_St hashfs_file_t; typedef struct hashfs_set_St hashfs_set_t; struct hashfs_backend_St { gpointer data; + GList *globs; GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; struct hashfs_db_St { TCTDB *tdb; }; struct hashfs_db_entry_St { TCMAP *data; gchar *pkey; }; struct hashfs_file_St { gchar *filename; gint64 size; GList *sets; hashfs_backend_t *backend; hashfs_db_entry_t *entry; /* Hashes */ gchar *ed2k; gchar *md5; }; struct hashfs_set_St { gchar name[256]; hashfs_db_entry_t *entry; }; /* Config */ GKeyFile * hashfs_config_keyfile (void); void hashfs_config_load (void); void hashfs_config_save (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); /* Database */ gboolean hashfs_db_open (void); void hashfs_db_close (void); gchar * hashfs_db_error (void); gboolean hashfs_db_tran_abort (void); gboolean hashfs_db_tran_begin (void); gboolean hashfs_db_tran_commit (void); /* Database entry */ hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type); gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out); void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value); gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry); void hashfs_db_entry_destroy (hashfs_db_entry_t *entry); /* Set */ hashfs_set_t * hashfs_set_new (const gchar *name, const gchar *source, const gchar *type); gboolean hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, const gchar **out); void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, const gchar *value); void hashfs_set_destroy (hashfs_set_t *set); /* File */ hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend); gboolean hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_hash_md5 (hashfs_file_t *file, const gchar **out); gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value); hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type); void hashfs_file_destroy (hashfs_file_t *file); /* Backend manager */ hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); void hashfs_backends_load (const gchar *path); void hashfs_backends_destroy (void); /* Backend */ hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); +void hashfs_backend_glob_set (hashfs_backend_t *backend, ...); +gboolean hashfs_backend_glob_try (hashfs_backend_t *backend, const gchar *filename); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, const gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); /* Utils */ gchar * hashfs_current_time (void); gchar * hashfs_basename (const gchar *name); gchar * hashfs_md5_str (const gchar *str); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ gchar *log_time = hashfs_current_time(); \ printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ gchar *log_time = hashfs_current_time(); \ FILE *fd = g_fopen(log_path, "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ g_free(log_path); \ g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif
chrippa/hashfs
0943d81a90666ffc97294a2c2863b04daf5b6aa3
Add more DB stuff and use const char more.
diff --git a/src/backends/anidb/anidb.c b/src/backends/anidb/anidb.c index 0f8c029..b60d053 100644 --- a/src/backends/anidb/anidb.c +++ b/src/backends/anidb/anidb.c @@ -1,229 +1,218 @@ #include <stdio.h> #include <hashfs.h> #include <anidb.h> static void hashfs_anidb_setup (hashfs_backend_t *backend); static gboolean hashfs_anidb_init (hashfs_backend_t *backend); static void hashfs_anidb_destroy (hashfs_backend_t *backend); static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file); static void dump_result (anidb_result_t *result); HASHFS_BACKEND("anidb", "AniDB", "AniDB hashing backend", hashfs_anidb_setup); typedef struct hashfs_anidb_data_St { anidb_session_t *session; } hashfs_anidb_data_t; static void hashfs_anidb_setup (hashfs_backend_t *backend) { backend->funcs.init = hashfs_anidb_init; backend->funcs.file = hashfs_anidb_handle_file; backend->funcs.destroy = hashfs_anidb_destroy; hashfs_backend_config_register(backend, "username", ""); hashfs_backend_config_register(backend, "password", ""); hashfs_backend_config_register(backend, "local_port", "0"); } static gboolean hashfs_anidb_init (hashfs_backend_t *backend) { anidb_session_t *session; anidb_result_t *res; hashfs_anidb_data_t *data; - gchar *username, *password, *port_s, *key; + gchar *username, *password, *port_s; + const gchar *key; gint port; gboolean rval; HASHFS_DEBUG("Connecting to AniDB"); hashfs_backend_config_lookup(backend, "username", &username); hashfs_backend_config_lookup(backend, "password", &password); hashfs_backend_config_lookup(backend, "local_port", &port_s); port = atoi(port_s); HASHFS_DEBUG("username=%s, password=%s, port=%d", username, password, port); session = anidb_session_new("anidbfuse", "1", port); + data = g_new0(hashfs_anidb_data_t, 1); data->session = session; backend->data = data; res = anidb_session_authenticate(session, username, password); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); HASHFS_DEBUG("Successfully logged in"); rval = TRUE; } else { HASHFS_DEBUG("Failed to get session key"); rval = FALSE; } } else { HASHFS_DEBUG("Unable to login to AniDB servers"); rval = FALSE; } g_free(username); g_free(password); g_free(port_s); anidb_result_unref(res); return rval; } static void hashfs_anidb_destroy (hashfs_backend_t *backend) { hashfs_anidb_data_t *data; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; if (data) { if (anidb_session_is_logged_in(data->session)) { HASHFS_DEBUG("Logging out"); anidb_result_unref(anidb_session_logout(data->session)); } anidb_session_unref(data->session); g_free(data); } } -#define ANIDB_SET_PROP(res, file, prop) { \ - gchar *tmp; \ - if (anidb_result_dict_get((res), (prop), &tmp)) \ - hashfs_file_prop_set((file), (prop), tmp); \ -} - static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file) { hashfs_anidb_data_t *data; const gchar *hash; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; g_return_if_fail(data); if (anidb_session_is_logged_in(data->session)) { if (hashfs_file_hash_ed2k(file, &hash)) { hashfs_set_t *set; anidb_result_t *res; - gchar *tmp; + const gchar *tmp, *aid, *gid; HASHFS_DEBUG("ed2k hash: %s", hash); - res = anidb_session_file_ed2k(data->session, file->size, (char *) hash); + res = anidb_session_file_ed2k(data->session, file->size, hash); - ANIDB_SET_PROP(res, file, "fid"); - ANIDB_SET_PROP(res, file, "eid"); - ANIDB_SET_PROP(res, file, "state"); - ANIDB_SET_PROP(res, file, "size"); - ANIDB_SET_PROP(res, file, "ed2k"); - ANIDB_SET_PROP(res, file, "md5"); - ANIDB_SET_PROP(res, file, "sha1"); - ANIDB_SET_PROP(res, file, "crc32"); - ANIDB_SET_PROP(res, file, "dub"); - ANIDB_SET_PROP(res, file, "sub"); - ANIDB_SET_PROP(res, file, "quality"); - ANIDB_SET_PROP(res, file, "source"); - ANIDB_SET_PROP(res, file, "audio"); - ANIDB_SET_PROP(res, file, "video"); - ANIDB_SET_PROP(res, file, "resolution"); - ANIDB_SET_PROP(res, file, "ext"); - ANIDB_SET_PROP(res, file, "duration"); - ANIDB_SET_PROP(res, file, "ep_number"); - ANIDB_SET_PROP(res, file, "ep_eng"); - ANIDB_SET_PROP(res, file, "ep_romaji"); - ANIDB_SET_PROP(res, file, "ep_kanji"); + for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; + dict = anidb_dict_next(dict)) { + hashfs_file_prop_set(file, dict->key, dict->value); + } - if (anidb_result_dict_get(res, "anime_romaji", &tmp)) { - set = hashfs_file_add_to_set(file, tmp, "anime"); + if (anidb_result_dict_get(res, "aid", &aid)) { + set = hashfs_file_add_to_set(file, aid, "anime"); - hashfs_set_prop_set(set, "romaji", tmp); + if (!hashfs_set_prop_lookup(set, "aid", &tmp)) { + anidb_result_t *res; - if (anidb_result_dict_get(res, "anime_totalep", &tmp)) - hashfs_set_prop_set(set, "totalep", tmp); + HASHFS_DEBUG("Need to lookup anime!"); - if (anidb_result_dict_get(res, "anime_lastep", &tmp)) - hashfs_set_prop_set(set, "lastep", tmp); + res = anidb_session_anime_id(data->session, atoi(aid)); + + for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; + dict = anidb_dict_next(dict)) { + hashfs_set_prop_set(set, dict->key, dict->value); + } + + anidb_result_unref(res); + } + } - if (anidb_result_dict_get(res, "anime_year", &tmp)) - hashfs_set_prop_set(set, "year", tmp); + if (anidb_result_dict_get(res, "gid", &gid)) { + set = hashfs_file_add_to_set(file, gid, "group"); - if (anidb_result_dict_get(res, "anime_type", &tmp)) - hashfs_set_prop_set(set, "type", tmp); + if (!hashfs_set_prop_lookup(set, "gid", &tmp)) { + anidb_result_t *res; - if (anidb_result_dict_get(res, "anime_kanji", &tmp)) - hashfs_set_prop_set(set, "kanji", tmp); + HASHFS_DEBUG("Need to lookup group!"); - if (anidb_result_dict_get(res, "anime_eng", &tmp)) - hashfs_set_prop_set(set, "eng", tmp); + res = anidb_session_group_id(data->session, atoi(gid)); - if (anidb_result_dict_get(res, "anime_categories", &tmp)) - hashfs_set_prop_set(set, "categories", tmp); + for (anidb_dict_t *dict = anidb_result_get_dict(res); dict; + dict = anidb_dict_next(dict)) { + hashfs_set_prop_set(set, dict->key, dict->value); + } + anidb_result_unref(res); + } } anidb_result_unref(res); } } } static void dump_result (anidb_result_t *result) { gint n; - gchar *str; + const gchar *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: HASHFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); HASHFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); HASHFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: HASHFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { HASHFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); } HASHFS_DEBUG(">"); break; } } diff --git a/src/hashfs/db.c b/src/hashfs/db.c index be0d5eb..02b2a76 100644 --- a/src/hashfs/db.c +++ b/src/hashfs/db.c @@ -1,147 +1,163 @@ #include <glib.h> #include <string.h> #include <stdio.h> #include "hashfs.h" static hashfs_db_t *db; gboolean hashfs_db_open (void) { gchar *path; gboolean rval; g_return_val_if_fail(db == NULL, FALSE); db = g_new0(hashfs_db_t, 1); db->tdb = tctdbnew(); path = g_build_filename(g_get_user_config_dir(), "hashfs", "metadata.tct", NULL); if (!tctdbopen(db->tdb, path, TDBOWRITER | TDBOCREAT)) { HASHFS_DEBUG("Unable to open DB: %s", hashfs_db_error()); rval = FALSE; } else { HASHFS_DEBUG("Successfully opened DB"); rval = TRUE; } g_free(path); return rval; } void hashfs_db_close (void) { g_return_if_fail(db != NULL); if (!tctdbclose(db->tdb)) { HASHFS_DEBUG("Unable to close DB: %s", hashfs_db_error()); } else { HASHFS_DEBUG("Successfully closed DB"); } tctdbdel(db->tdb); free(db); } gboolean hashfs_db_tran_begin (void) { return (gboolean) tctdbtranbegin(db->tdb); } gboolean hashfs_db_tran_commit (void) { return (gboolean) tctdbtrancommit(db->tdb); } gboolean hashfs_db_tran_abort (void) { return (gboolean) tctdbtranabort(db->tdb); } gchar * hashfs_db_error (void) { gint ecode = tctdbecode(db->tdb); return (gchar *) tctdberrmsg(ecode); } hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type) { hashfs_db_entry_t *entry; gchar *pkey, *md5; + TCMAP *curdata; md5 = hashfs_md5_str(id); if (!g_strcmp0(prefix, "set")) { pkey = g_strdup_printf("%s:%s:%s:%s", prefix, source, type, md5); } else { pkey = g_strdup_printf("%s:%s", prefix, md5); } entry = g_new0(hashfs_db_entry_t, 1); entry->pkey = pkey; - entry->data = tcmapnew(); + + curdata = tctdbget(db->tdb, pkey, strlen(pkey)); + + if (curdata != NULL) + entry->data = curdata; + else + entry->data = tcmapnew(); HASHFS_DEBUG("Created entry with pkey: %s", pkey); g_free(md5); return entry; } void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value) { g_return_if_fail(entry != NULL); g_return_if_fail(entry->data != NULL); tcmapput2(entry->data, key, value); } gboolean -hashfs_db_entry_get (hashfs_db_entry_t *entry, const gchar *key, - const gchar **out) +hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, + const gchar **out) { + const gchar *val; + + val = tcmapget2(entry->data, key); + + if (val == NULL) + return FALSE; + + *out = val; + return TRUE; } gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry) { g_return_val_if_fail(entry != NULL, FALSE); g_return_val_if_fail(entry->pkey != NULL, FALSE); g_return_val_if_fail(entry->data != NULL, FALSE); return (gboolean) tctdbputcat(db->tdb, entry->pkey, strlen(entry->pkey), entry->data); } void hashfs_db_entry_destroy (hashfs_db_entry_t *entry) { g_return_if_fail (entry != NULL); if (entry->data) tcmapdel(entry->data); if (entry->pkey) g_free(entry->pkey); g_free(entry); } diff --git a/src/hashfs/ed2k.c b/src/hashfs/ed2k.c index b36de51..7b6bd57 100644 --- a/src/hashfs/ed2k.c +++ b/src/hashfs/ed2k.c @@ -1,98 +1,98 @@ #define _FILE_OFFSET_BITS 64 #define _LARGEFILE_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _LARGE_FILES 1 #define BLOCKSIZE (9500*1024) #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> #include <openssl/md4.h> #include <glib.h> #include <glib/gstdio.h> #include <glib/gprintf.h> #include "hashfs.h" static const gchar hexdigits[16] = "0123456789abcdef"; -gint +gboolean hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out) { gint blocks, fd, len; gint64 size, offset; guchar *hash_blocks, *hash_final; gchar *hash_str; MD4_CTX ctx; gpointer data; if ((fd = g_open(file->filename, O_RDONLY, "rb")) < 0) { HASHFS_DEBUG("Failed to open file (%s)", file->filename); - return 0; + return FALSE; } blocks = file->size / BLOCKSIZE; if ((file->size % BLOCKSIZE) > 0) blocks++; if (blocks < 1) - return 0; + return FALSE; hash_blocks = g_malloc(blocks * 16); hash_str = g_strnfill(33, 0); offset = 0; g_return_val_if_fail(hash_blocks != NULL, 0); g_return_val_if_fail(hash_str != NULL, 0); for (gint b = 0; b < blocks; b++) { len = (blocks - b) == 1 ? file->size % BLOCKSIZE : BLOCKSIZE; data = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, offset); g_return_val_if_fail(data != NULL, 0); MD4_Init(&ctx); MD4_Update(&ctx, data, len); MD4_Final(hash_blocks + (b * 16), &ctx); munmap(data, len); offset += len; } close(fd); /* If we have hashed more than one block, run MD4 on all the previous hashes */ if (blocks > 1) { hash_final = g_malloc(16); MD4_Init(&ctx); MD4_Update(&ctx, hash_blocks, 16 * blocks); MD4_Final(hash_final, &ctx); } else { hash_final = g_memdup(hash_blocks, 16); } /* Convert hash to hex string format */ for (gint i = 0; i < 16; i++) { hash_str[(i<<1)] = hexdigits[(((hash_final[i]) & 0xf0) >> 4)]; hash_str[(i<<1)+1] = hexdigits[(((hash_final[i]) & 0x0f))]; } g_free(hash_blocks); g_free(hash_final); file->ed2k = hash_str; *out = hash_str; - return 1; + return TRUE; } diff --git a/src/hashfs/file.c b/src/hashfs/file.c index fabc3e2..4ad70fc 100644 --- a/src/hashfs/file.c +++ b/src/hashfs/file.c @@ -1,100 +1,98 @@ #include <glib.h> #include "hashfs.h" hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend) { hashfs_file_t *file; struct stat info; stat(filename, &info); file = g_new0(hashfs_file_t, 1); file->backend = backend; file->entry = hashfs_db_entry_new("file", filename, NULL, NULL); file->filename = g_strdup(filename); file->size = (gint64) info.st_size; file->ed2k = NULL; file->md5 = NULL; hashfs_db_entry_set(file->entry, "path", filename); return file; } -gint +gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out) { HASHFS_DEBUG("File (%s) looking up property: %s", hashfs_basename(file->filename), key); - // TODO: Actually look up property from DB. - - return 0; + return hashfs_db_entry_lookup(file->entry, key, out); } void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value) { HASHFS_DEBUG("File (%s) setting property: %s = %s", hashfs_basename(file->filename), key, value); hashfs_db_entry_set(file->entry, key, value); } hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type) { hashfs_set_t *set; const gchar *source; if (file->backend) source = file->backend->desc->shortname; else source = "unknown"; set = hashfs_set_new(name, source, type); hashfs_db_entry_set(file->entry, type, set->entry->pkey); file->sets = g_list_append(file->sets, set); return set; } void hashfs_file_destroy (hashfs_file_t *file) { HASHFS_DEBUG("File (%s) destroying", hashfs_basename(file->filename)); if (file->filename) g_free(file->filename); if (file->ed2k) g_free(file->ed2k); if (file->md5) g_free(file->md5); if (file->sets) { GList *item; hashfs_set_t *set; for (item = g_list_first(file->sets); item; item = g_list_next(item)) { set = item->data; hashfs_set_destroy(set); } g_list_free(file->sets); } if (file->entry) { hashfs_db_entry_put(file->entry); hashfs_db_entry_destroy(file->entry); } g_free(file); } diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index cd04ad7..c983713 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,223 +1,218 @@ #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { hashfs_file_t *file; HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); file = hashfs_file_new(path, backend); hashfs_backend_file(backend, file); hashfs_file_destroy(file); } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; HASHFS_LOG("Hashing dir: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; gchar *val; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { hashfs_config_property_lookup(groups[i], keys[j], &val); printf("%s.%s = %s\n", groups[i], keys[j], val); g_free(val); } g_strfreev(keys); } g_strfreev(groups); } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } g_free(val); g_strfreev(split); } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } g_strfreev(split); } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; hashfs_config_load(); hashfs_db_open(); if (g_module_supported()) { -// gchar *backenddir = g_build_filename(g_get_user_config_dir(), "hashfs", "backends", NULL); - -// hashfs_backends_load(backenddir); hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); - -// g_free(backenddir); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); hashfs_backends_destroy(); hashfs_config_save(); hashfs_db_close(); return 0; } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index 117ce98..e776089 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,175 +1,175 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include <tcutil.h> #include <tctdb.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_db_St; struct hashfs_db_entry_St; struct hashfs_file_St; struct hashfs_set_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_db_St hashfs_db_t; typedef struct hashfs_db_entry_St hashfs_db_entry_t; typedef struct hashfs_file_St hashfs_file_t; typedef struct hashfs_set_St hashfs_set_t; struct hashfs_backend_St { gpointer data; GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; struct hashfs_db_St { TCTDB *tdb; }; struct hashfs_db_entry_St { TCMAP *data; gchar *pkey; }; struct hashfs_file_St { gchar *filename; gint64 size; GList *sets; hashfs_backend_t *backend; hashfs_db_entry_t *entry; /* Hashes */ gchar *ed2k; gchar *md5; }; struct hashfs_set_St { gchar name[256]; hashfs_db_entry_t *entry; }; /* Config */ GKeyFile * hashfs_config_keyfile (void); void hashfs_config_load (void); void hashfs_config_save (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); /* Database */ gboolean hashfs_db_open (void); void hashfs_db_close (void); gchar * hashfs_db_error (void); gboolean hashfs_db_tran_abort (void); gboolean hashfs_db_tran_begin (void); gboolean hashfs_db_tran_commit (void); /* Database entry */ hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type); +gboolean hashfs_db_entry_lookup (hashfs_db_entry_t *entry, const gchar *key, const gchar **out); void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value); -gboolean hashfs_db_entry_get (hashfs_db_entry_t *entry, const gchar *key, const gchar **out); gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry); void hashfs_db_entry_destroy (hashfs_db_entry_t *entry); /* Set */ hashfs_set_t * hashfs_set_new (const gchar *name, const gchar *source, const gchar *type); -gint hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, const gchar **out); +gboolean hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, const gchar **out); void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, const gchar *value); void hashfs_set_destroy (hashfs_set_t *set); /* File */ hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend); -gint hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out); -gint hashfs_file_hash_md5 (hashfs_file_t *file, const gchar **out); -gint hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out); +gboolean hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out); +gboolean hashfs_file_hash_md5 (hashfs_file_t *file, const gchar **out); +gboolean hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value); hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type); void hashfs_file_destroy (hashfs_file_t *file); /* Backend manager */ hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); void hashfs_backends_load (const gchar *path); void hashfs_backends_destroy (void); /* Backend */ hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, const gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); /* Utils */ gchar * hashfs_current_time (void); gchar * hashfs_basename (const gchar *name); gchar * hashfs_md5_str (const gchar *str); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ gchar *log_time = hashfs_current_time(); \ printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ gchar *log_time = hashfs_current_time(); \ FILE *fd = g_fopen(log_path, "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ g_free(log_path); \ g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif diff --git a/src/hashfs/set.c b/src/hashfs/set.c index b163542..99fb597 100644 --- a/src/hashfs/set.c +++ b/src/hashfs/set.c @@ -1,52 +1,50 @@ #include <glib.h> #include <glib/gprintf.h> #include "hashfs.h" hashfs_set_t * hashfs_set_new (const gchar *name, const gchar *source, const gchar *type) { hashfs_set_t *set; set = g_new0(hashfs_set_t, 1); set->entry = hashfs_db_entry_new("set", name, source, type); g_strlcpy(set->name, name, sizeof(set->name)); HASHFS_DEBUG("Creating new set: %s", name); return set; } -gint +gboolean hashfs_set_prop_lookup (hashfs_set_t *set, const gchar *key, const gchar **out) { HASHFS_DEBUG("Set (%s) looking up property: %s", set->name, key); - // TODO: Actually look up property from DB. - - return 0; + return hashfs_db_entry_lookup(set->entry, key, out); } void hashfs_set_prop_set (hashfs_set_t *set, const gchar *key, const gchar *value) { HASHFS_DEBUG("Set (%s) setting property: %s = %s", set->name, key, value); hashfs_db_entry_set(set->entry, key, value); } void hashfs_set_destroy (hashfs_set_t *set) { HASHFS_DEBUG("Set (%s) destroying", set->name); if (set->entry) { hashfs_db_entry_put(set->entry); hashfs_db_entry_destroy(set->entry); } g_free(set); } diff --git a/src/lib/libanidb/anidb.c b/src/lib/libanidb/anidb.c index bf917a7..a73a0f4 100644 --- a/src/lib/libanidb/anidb.c +++ b/src/lib/libanidb/anidb.c @@ -1,757 +1,757 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include <time.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; -static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); +static anidb_result_t * anidb_session_cmd (anidb_session_t *session, const char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static int get_ms (void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } static void throttle_session (anidb_session_t *session) { int elapsed, needtosleep; elapsed = get_ms() - session->time; needtosleep = ANIDB_THROTTLE_MS - elapsed; if (needtosleep > 0) { usleep(needtosleep * 1000); } session->time = get_ms(); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; // printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; // printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version, int localport) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } if (localport > 0) { local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(localport); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:%d", localport); } } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; strncpy(session->clientname, name, sizeof(session->clientname)); strncpy(session->clientversion, version, sizeof(session->clientversion)); anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); free(session); } } void -anidb_session_set_key (anidb_session_t *session, char *key) +anidb_session_set_key (anidb_session_t *session, const char *key) { strncpy(session->key, key, sizeof(session->key)); } int anidb_session_is_logged_in (anidb_session_t *session) { if (session->key[0]) return 1; return 0; } static anidb_result_t * -anidb_session_cmd (anidb_session_t *session, char *cmd, ...) +anidb_session_cmd (anidb_session_t *session, const char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * -anidb_session_authenticate (anidb_session_t *session, char *username, - char *password) +anidb_session_authenticate (anidb_session_t *session, const char *username, + const char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * -anidb_session_anime_name (anidb_session_t *session, char *name) +anidb_session_anime_name (anidb_session_t *session, const char *name) { anidb_result_t *res; throttle_session(session); res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); throttle_session(session); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); throttle_session(session); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); throttle_session(session); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * -anidb_session_episode_name (anidb_session_t *session, char *name, int ep) +anidb_session_episode_name (anidb_session_t *session, const char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); throttle_session(session); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); throttle_session(session); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); throttle_session(session); res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * -anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k) +anidb_session_file_ed2k (anidb_session_t *session, int64_t size, const char *ed2k) { anidb_result_t *res; char siz[50]; sprintf(siz, "%d", size); throttle_session(session); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); throttle_session(session); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * -anidb_session_group_name (anidb_session_t *session, char *name) +anidb_session_group_name (anidb_session_t *session, const char *name) { anidb_result_t *res; throttle_session(session); res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * -anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) +anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, const char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * -anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) +anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, const char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void -anidb_dict_set (anidb_dict_t *dict, char *key, char *value) +anidb_dict_set (anidb_dict_t *dict, const char *key, const char *value) { strncpy(dict->key, key, sizeof(dict->key)); strncpy(dict->value, value, sizeof(dict->value)); } int -anidb_dict_get (anidb_dict_t *dict, char **out) +anidb_dict_get (anidb_dict_t *dict, const char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void -anidb_result_set_str (anidb_result_t *result, char *string) +anidb_result_set_str (anidb_result_t *result, const char *string) { result->type = ANIDB_RESULT_STRING; strncpy(result->value.string, string, sizeof(result->value.string)); } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void -anidb_result_dict_set (anidb_result_t *result, char *key, char *value) +anidb_result_dict_set (anidb_result_t *result, const char *key, const char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int -anidb_result_get_str (anidb_result_t *result, char **out) +anidb_result_get_str (anidb_result_t *result, const char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } int -anidb_result_dict_get (anidb_result_t *result, char *key, char **out) +anidb_result_dict_get (anidb_result_t *result, const char *key, const char **out) { anidb_dict_t *dict; if (result->type != ANIDB_RESULT_DICT) return 0; for (dict = result->value.dict; dict; dict = dict->next) { if (!strcmp(dict->key, key)) { return anidb_dict_get(dict, out); } } return 0; } anidb_dict_t * anidb_result_get_dict (anidb_result_t *result) { if (result->type != ANIDB_RESULT_DICT) return NULL; return result->value.dict; } diff --git a/src/lib/libanidb/anidb.h b/src/lib/libanidb/anidb.h index 468a828..ce1c832 100644 --- a/src/lib/libanidb/anidb.h +++ b/src/lib/libanidb/anidb.h @@ -1,312 +1,318 @@ #ifndef _LIBANIDB_H #define _LIBANIDB_H #include <sys/time.h> + +/* Types */ +enum anidb_result_type; +struct anidb_error_St; +struct anidb_dict_St; +struct anidb_session_St; +struct anidb_result_St; +struct anidb_result_handler_St; + +typedef enum anidb_result_type anidb_result_type_t; +typedef struct anidb_dict_St anidb_dict_t; +typedef struct anidb_result_St anidb_result_t; +typedef struct anidb_result_handler_St anidb_result_handler_t; +typedef struct anidb_session_St anidb_session_t; + enum anidb_result_type { ANIDB_RESULT_NULL, ANIDB_RESULT_NUMBER, ANIDB_RESULT_STRING, ANIDB_RESULT_DICT }; struct anidb_session_St { int socket; int time; char clientname[256]; char clientversion[256]; char key[10]; int refcount; }; struct anidb_dict_St { char key[50]; char value[512]; - struct anidb_dict_St *next; + anidb_dict_t *next; int refcount; }; struct anidb_result_St { - struct anidb_error_St *error; int code; - enum anidb_result_type type; + anidb_result_type_t type; union { int number; char string[256]; - struct anidb_dict_St *dict; + anidb_dict_t *dict; } value; int refcount; }; struct anidb_result_handler_St { int code; - void (*func)(struct anidb_result_St *, char *); + void (*func)(anidb_result_t *, char *); }; -/* Types */ -typedef enum anidb_result_type anidb_result_type_t; -typedef struct anidb_session_St anidb_session_t; -typedef struct anidb_dict_St anidb_dict_t; -typedef struct anidb_result_St anidb_result_t; -typedef struct anidb_result_handler_St anidb_result_handler_t; -typedef struct anidb_error_St anidb_error_t; - /* Session */ anidb_session_t * anidb_session_new (char *name, char *version, int localport); /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, - char *username, - char *password); + const char *username, + const char *password); /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session); /* ANIME */ -anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name); +anidb_result_t * anidb_session_anime_name (anidb_session_t *session, const char *name); anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id); /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int ep); /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id); -anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep); +anidb_result_t * anidb_session_episode_name (anidb_session_t *session, const char *name, int ep); anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep); /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id); -anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k); +anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, const char *ed2k); /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id); -anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name); +anidb_result_t * anidb_session_group_name (anidb_session_t *session, const char *name); /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id); /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id); -anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k); +anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, const char *ed2k); /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id); -anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k); +anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, const char *ed2k); /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session); /* VOTE */ /* RANDOM */ /* MYLISTEXPORT */ /* PING */ anidb_result_t * anidb_session_ping (anidb_session_t *session); /* VERSION */ anidb_result_t * anidb_session_uptime (anidb_session_t *session); /* UPTIME */ anidb_result_t * anidb_session_version (anidb_session_t *session); /* ENCODING */ /* SENDMSG */ /* USER */ -void anidb_session_set_key (anidb_session_t *session, char *key); +void anidb_session_set_key (anidb_session_t *session, const char *key); int anidb_session_is_logged_in (anidb_session_t *session); void anidb_session_ref (anidb_session_t *session); void anidb_session_unref (anidb_session_t *session); /* Dict */ anidb_dict_t * anidb_dict_new (void); anidb_dict_t * anidb_dict_next (anidb_dict_t *dict); void anidb_dict_ref (anidb_dict_t *dict); void anidb_dict_unref (anidb_dict_t *dict); -void anidb_dict_set (anidb_dict_t *dict, char *key, char *value); -int anidb_dict_get (anidb_dict_t *dict, char **out); +void anidb_dict_set (anidb_dict_t *dict, const char *key, const char *value); +int anidb_dict_get (anidb_dict_t *dict, const char **out); /* Result */ anidb_result_t * anidb_result_new (int code); void anidb_result_ref (anidb_result_t *result); void anidb_result_unref (anidb_result_t *result); -void anidb_result_set_str (anidb_result_t *result, char *string); +void anidb_result_set_str (anidb_result_t *result, const char *string); void anidb_result_set_int (anidb_result_t *result, int number); -void anidb_result_dict_set (anidb_result_t *result, char *key, char *value); +void anidb_result_dict_set (anidb_result_t *result, const char *key, const char *value); anidb_result_type_t anidb_result_get_type (anidb_result_t *result); int anidb_result_get_code (anidb_result_t *result); -int anidb_result_get_str (anidb_result_t *result, char **out); +int anidb_result_get_str (anidb_result_t *result, const char **out); int anidb_result_get_int (anidb_result_t *result, int *out); -int anidb_result_dict_get (anidb_result_t *result, char *key, char **out); +int anidb_result_dict_get (anidb_result_t *result, const char *key, const char **out); anidb_dict_t * anidb_result_get_dict (anidb_result_t *result); #define ANIDB_SERVER_HOST "api.anidb.net" #define ANIDB_SERVER_PORT 9000 #define ANIDB_PROTO_VERSION "3" #define ANIDB_THROTTLE_MS 2000 /* Positive responses 2XX */ #define ANIDB_LOGIN_ACCEPTED 200 #define ANIDB_LOGIN_ACCEPTED_NEW_VER 201 #define ANIDB_LOGGED_OUT 203 #define ANIDB_RESOURCE 205 #define ANIDB_STATS 206 #define ANIDB_TOP 207 #define ANIDB_UPTIME 208 #define ANIDB_ENCRYPTION_ENABLED 209 #define ANIDB_MYLIST_ENTRY_ADDED 210 #define ANIDB_MYLIST_ENTRY_DELETED 211 #define ANIDB_ADDED_FILE 214 #define ANIDB_ADDED_STREAM 215 #define ANIDB_ENCODING_CHANGED 219 #define ANIDB_FILE 220 #define ANIDB_MYLIST 221 #define ANIDB_MYLIST_STATS 222 #define ANIDB_ANIME 230 #define ANIDB_ANIME_BEST_MATCH 231 #define ANIDB_RANDOMANIME 232 #define ANIDB_ANIME_DESCRIPTION 233 #define ANIDB_EPISODE 240 #define ANIDB_PRODUCER 245 #define ANIDB_GROUP 250 #define ANIDB_BUDDY_LIST 253 #define ANIDB_BUDDY_STATE 254 #define ANIDB_BUDDY_ADDED 255 #define ANIDB_BUDDY_DELETED 256 #define ANIDB_BUDDY_ACCEPTED 257 #define ANIDB_BUDDY_DENIED 258 #define ANIDB_VOTED 260 #define ANIDB_VOTE_FOUND 261 #define ANIDB_VOTE_UPDATED 262 #define ANIDB_VOTE_REVOKED 263 #define ANIDB_NOTIFICATION_ENABLED 270 #define ANIDB_NOTIFICATION_NOTIFY 271 #define ANIDB_NOTIFICATION_MESSAGE 272 #define ANIDB_NOTIFICATION_BUDDY 273 #define ANIDB_NOTIFICATION_SHUTDOWN 274 #define ANIDB_PUSHACK_CONFIRMED 280 #define ANIDB_NOTIFYACK_SUCCESSFUL_M 281 #define ANIDB_NOTIFYACK_SUCCESSFUL_N 282 #define ANIDB_NOTIFICATION 290 #define ANIDB_NOTIFYLIST 291 #define ANIDB_NOTIFYGET_MESSAGE 292 #define ANIDB_NOTIFYGET_NOTIFY 293 #define ANIDB_SENDMSG_SUCCESSFUL 294 #define ANIDB_USER 295 /* Affirmative/Negative responses 3XX */ #define ANIDB_PONG 300 #define ANIDB_AUTHPONG 301 #define ANIDB_NO_SUCH_RESOURCE 305 #define ANIDB_API_PASSWORD_NOT_DEFINED 309 #define ANIDB_FILE_ALREADY_IN_MYLIST 310 #define ANIDB_MYLIST_ENTRY_EDITED 311 #define ANIDB_MULTIPLE_MYLIST_ENTRIES 312 #define ANIDB_SIZE_HASH_EXISTS 314 #define ANIDB_INVALID_DATA 315 #define ANIDB_STREAMNOID_USED 316 #define ANIDB_NO_SUCH_FILE 320 #define ANIDB_NO_SUCH_ENTRY 321 #define ANIDB_MULTIPLE_FILES_FOUND 322 #define ANIDB_NO_SUCH_ANIME 330 #define ANIDB_NO_SUCH_ANIME_DESCRIPTION 333 #define ANIDB_NO_SUCH_EPISODE 340 #define ANIDB_NO_SUCH_PRODUCER 345 #define ANIDB_NO_SUCH_GROUP 350 #define ANIDB_BUDDY_ALREADY_ADDED 355 #define ANIDB_NO_SUCH_BUDDY 356 #define ANIDB_BUDDY_ALREADY_ACCEPTED 357 #define ANIDB_BUDDY_ALREADY_DENIED 358 #define ANIDB_NO_SUCH_VOTE 360 #define ANIDB_INVALID_VOTE_TYPE 361 #define ANIDB_INVALID_VOTE_VALUE 362 #define ANIDB_PERMVOTE_NOT_ALLOWED 363 #define ANIDB_ALREADY_PERMVOTED 364 #define ANIDB_NOTIFICATION_DISABLED 370 #define ANIDB_NO_SUCH_PACKET_PENDING 380 #define ANIDB_NO_SUCH_ENTRY_M 381 #define ANIDB_NO_SUCH_ENTRY_N 382 #define ANIDB_NO_SUCH_MESSAGE 392 #define ANIDB_NO_SUCH_NOTIFY 393 #define ANIDB_NO_SUCH_USER 394 /* Negative responses 4XX */ #define ANIDB_NOT_LOGGED_IN 403 #define ANIDB_NO_SUCH_MYLIST_FILE 410 #define ANIDB_NO_SUCH_MYLIST_ENTRY 411 /* Client side failure 5XX */ #define ANIDB_LOGIN_FAILED 500 #define ANIDB_LOGIN_FIRST 501 #define ANIDB_ACCESS_DENIED 502 #define ANIDB_CLIENT_VERSION_OUTDATED 503 #define ANIDB_CLIENT_BANNED 504 #define ANIDB_ILLEGAL_INPUT_OR_ACCESS_DENIED 505 #define ANIDB_INVALID_SESSION 506 #define ANIDB_NO_SUCH_ENCRYPTION_TYPE 509 #define ANIDB_ENCODING_NOT_SUPPORTED 519 #define ANIDB_BANNED 555 #define ANIDB_UNKNOWN_COMMAND 598 /* Server side failure 6XX */ #define ANIDB_INTERNAL_SERVER_ERROR 600 #define ANIDB_ANIDB_OUT_OF_SERVICE 601 #define ANIDB_SERVER_BUSY 602 #define ANIDB_API_VIOLATION 666 #endif diff --git a/src/lib/libanidb/tests/test01.c b/src/lib/libanidb/tests/test01.c index 1429350..74bf8b1 100644 --- a/src/lib/libanidb/tests/test01.c +++ b/src/lib/libanidb/tests/test01.c @@ -1,169 +1,169 @@ #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <anidb.h> static void dump_result (anidb_result_t *result) { int n; - char *str; + const char *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: printf("<result %p null>\n", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); printf("<result %p (string) \"%s\">\n", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); printf("<result %p (int) \"%d\">\n", result, n); break; case ANIDB_RESULT_DICT: printf("<result %p (dict)\n", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { printf(" %s = \"%s\"", dict->key, dict->value); if (anidb_dict_next(dict)) printf(",\n"); } printf(">\n"); break; } } static void dump_anime (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_anime_name(session, name); if (anidb_result_get_code(res) == ANIDB_ANIME) { dump_result(res); } anidb_result_unref(res); } static void dump_animedesc (anidb_session_t *session, int id, int part) { anidb_result_t *res; res = anidb_session_animedesc(session, id, part); if (anidb_result_get_code(res) == ANIDB_ANIME_DESCRIPTION) { dump_result(res); } anidb_result_unref(res); } static void dump_episode (anidb_session_t *session, int id) { anidb_result_t *res; res = anidb_session_episode_id(session, id); if (anidb_result_get_code(res) == ANIDB_EPISODE) { dump_result(res); } anidb_result_unref(res); } static void dump_file (anidb_session_t *session, int id) { anidb_result_t *res; // res = anidb_session_file_ed2k(session, 44255118, "90033a52db54437dc4a6041348422d4b"); res = anidb_session_file_id(session, id); if (anidb_result_get_code(res) == ANIDB_FILE) { dump_result(res); } anidb_result_unref(res); } static void dump_group (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_group_name(session, name); if (anidb_result_get_code(res) == ANIDB_GROUP) { dump_result(res); } anidb_result_unref(res); } int main (int argc, char *argv[]) { anidb_session_t *session; anidb_result_t *res; - char *key; + const char *key; if (argc < 4) { printf("Usage: %s <username> <password> <port>\n", argv[0]); exit(0); } session = anidb_session_new("anidbfs", "1", atoi(argv[3])); res = anidb_session_authenticate(session, argv[1], argv[2]); dump_result(res); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); } dump_anime(session, "Neon Genesis Evangelion"); dump_group(session, "Chrippa Crapsubs"); dump_animedesc(session, 23, 0); dump_episode(session, 21346); dump_file(session, 43698); anidb_result_t *logout = anidb_session_logout(session); dump_result(logout); anidb_result_unref(logout); } anidb_result_unref(res); anidb_session_unref(session); return 0; }
chrippa/hashfs
43fc59c440207d516c2a6b1008c97c5d9edb0581
Add initial database code (using TokyoCabinet).
diff --git a/src/backends/anidb/anidb.c b/src/backends/anidb/anidb.c index 6766581..0f8c029 100644 --- a/src/backends/anidb/anidb.c +++ b/src/backends/anidb/anidb.c @@ -1,231 +1,229 @@ #include <stdio.h> #include <hashfs.h> #include <anidb.h> static void hashfs_anidb_setup (hashfs_backend_t *backend); static gboolean hashfs_anidb_init (hashfs_backend_t *backend); static void hashfs_anidb_destroy (hashfs_backend_t *backend); static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file); static void dump_result (anidb_result_t *result); HASHFS_BACKEND("anidb", "AniDB", "AniDB hashing backend", hashfs_anidb_setup); typedef struct hashfs_anidb_data_St { anidb_session_t *session; } hashfs_anidb_data_t; static void hashfs_anidb_setup (hashfs_backend_t *backend) { backend->funcs.init = hashfs_anidb_init; backend->funcs.file = hashfs_anidb_handle_file; backend->funcs.destroy = hashfs_anidb_destroy; hashfs_backend_config_register(backend, "username", ""); hashfs_backend_config_register(backend, "password", ""); hashfs_backend_config_register(backend, "local_port", "0"); } static gboolean hashfs_anidb_init (hashfs_backend_t *backend) { anidb_session_t *session; anidb_result_t *res; hashfs_anidb_data_t *data; gchar *username, *password, *port_s, *key; gint port; gboolean rval; HASHFS_DEBUG("Connecting to AniDB"); hashfs_backend_config_lookup(backend, "username", &username); hashfs_backend_config_lookup(backend, "password", &password); hashfs_backend_config_lookup(backend, "local_port", &port_s); port = atoi(port_s); HASHFS_DEBUG("username=%s, password=%s, port=%d", username, password, port); session = anidb_session_new("anidbfuse", "1", port); data = g_new0(hashfs_anidb_data_t, 1); data->session = session; backend->data = data; res = anidb_session_authenticate(session, username, password); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); HASHFS_DEBUG("Successfully logged in"); rval = TRUE; } else { HASHFS_DEBUG("Failed to get session key"); rval = FALSE; } } else { HASHFS_DEBUG("Unable to login to AniDB servers"); rval = FALSE; } g_free(username); g_free(password); g_free(port_s); anidb_result_unref(res); return rval; } static void hashfs_anidb_destroy (hashfs_backend_t *backend) { hashfs_anidb_data_t *data; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; if (data) { if (anidb_session_is_logged_in(data->session)) { HASHFS_DEBUG("Logging out"); anidb_result_unref(anidb_session_logout(data->session)); } anidb_session_unref(data->session); g_free(data); } } #define ANIDB_SET_PROP(res, file, prop) { \ gchar *tmp; \ if (anidb_result_dict_get((res), (prop), &tmp)) \ hashfs_file_prop_set((file), (prop), tmp); \ } static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file) { hashfs_anidb_data_t *data; - gchar *hash; + const gchar *hash; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; g_return_if_fail(data); if (anidb_session_is_logged_in(data->session)) { if (hashfs_file_hash_ed2k(file, &hash)) { hashfs_set_t *set; anidb_result_t *res; gchar *tmp; HASHFS_DEBUG("ed2k hash: %s", hash); - res = anidb_session_file_ed2k(data->session, file->size, hash); - -// dump_result(res); + res = anidb_session_file_ed2k(data->session, file->size, (char *) hash); ANIDB_SET_PROP(res, file, "fid"); ANIDB_SET_PROP(res, file, "eid"); ANIDB_SET_PROP(res, file, "state"); ANIDB_SET_PROP(res, file, "size"); ANIDB_SET_PROP(res, file, "ed2k"); ANIDB_SET_PROP(res, file, "md5"); ANIDB_SET_PROP(res, file, "sha1"); ANIDB_SET_PROP(res, file, "crc32"); ANIDB_SET_PROP(res, file, "dub"); ANIDB_SET_PROP(res, file, "sub"); ANIDB_SET_PROP(res, file, "quality"); ANIDB_SET_PROP(res, file, "source"); ANIDB_SET_PROP(res, file, "audio"); ANIDB_SET_PROP(res, file, "video"); ANIDB_SET_PROP(res, file, "resolution"); ANIDB_SET_PROP(res, file, "ext"); ANIDB_SET_PROP(res, file, "duration"); ANIDB_SET_PROP(res, file, "ep_number"); ANIDB_SET_PROP(res, file, "ep_eng"); ANIDB_SET_PROP(res, file, "ep_romaji"); ANIDB_SET_PROP(res, file, "ep_kanji"); if (anidb_result_dict_get(res, "anime_romaji", &tmp)) { - set = hashfs_file_add_to_set(file, tmp); + set = hashfs_file_add_to_set(file, tmp, "anime"); hashfs_set_prop_set(set, "romaji", tmp); if (anidb_result_dict_get(res, "anime_totalep", &tmp)) hashfs_set_prop_set(set, "totalep", tmp); if (anidb_result_dict_get(res, "anime_lastep", &tmp)) hashfs_set_prop_set(set, "lastep", tmp); if (anidb_result_dict_get(res, "anime_year", &tmp)) hashfs_set_prop_set(set, "year", tmp); if (anidb_result_dict_get(res, "anime_type", &tmp)) hashfs_set_prop_set(set, "type", tmp); if (anidb_result_dict_get(res, "anime_kanji", &tmp)) hashfs_set_prop_set(set, "kanji", tmp); if (anidb_result_dict_get(res, "anime_eng", &tmp)) hashfs_set_prop_set(set, "eng", tmp); if (anidb_result_dict_get(res, "anime_categories", &tmp)) hashfs_set_prop_set(set, "categories", tmp); } anidb_result_unref(res); } } } static void dump_result (anidb_result_t *result) { gint n; gchar *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: HASHFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); HASHFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); HASHFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: HASHFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { HASHFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); } HASHFS_DEBUG(">"); break; } } diff --git a/src/hashfs/backend.c b/src/hashfs/backend.c index 85ac4c0..5dc95eb 100644 --- a/src/hashfs/backend.c +++ b/src/hashfs/backend.c @@ -1,189 +1,189 @@ #include <glib.h> #include <gmodule.h> #include "hashfs.h" static GList *backends; hashfs_backend_t * hashfs_backend_load (const gchar *path) { GModule *module; gpointer sym; hashfs_backend_t *backend; hashfs_backend_desc_t *desc; HASHFS_DEBUG("Loading module (%s)", path); module = g_module_open(path, 0); if (!module) { HASHFS_DEBUG("Failed to load module: %s", g_module_error()); return NULL; } if (!g_module_symbol(module, "HASHFS_BACKEND_DESC", (gpointer) &sym)) { HASHFS_DEBUG("Failed to lookup symbol: %s", g_module_error()); g_module_close(module); return NULL; } desc = (hashfs_backend_desc_t *) sym; if (!desc) { HASHFS_DEBUG("HASHFS_BACKEND_DESC == NULL"); g_module_close(module); return NULL; } if (hashfs_backends_lookup(desc->shortname)) { HASHFS_DEBUG("Already loaded backend %s", desc->shortname); g_module_close(module); return NULL; } backend = g_new0(hashfs_backend_t, 1); backend->desc = desc; backend->module = module; desc->setup_func(backend); HASHFS_DEBUG("Backend successfully loaded: %s - %s - %s", desc->shortname, desc->name, desc->description); return backend; } void -hashfs_backends_load (gchar *path) +hashfs_backends_load (const gchar *path) { GDir *dir; GError *error = NULL; const gchar *filename; gchar *pattern, *glob; hashfs_backend_t *backend; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } glob = g_module_build_path(path, "hashfs_*"); pattern = g_path_get_basename(glob); HASHFS_DEBUG("Loooking for backends in: %s", glob); while ((filename = g_dir_read_name(dir))) { if (!g_pattern_match_simple(pattern, filename)) continue; gchar *fullpath = g_build_filename(path, filename, NULL); if (!g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { g_free(fullpath); continue; } backend = hashfs_backend_load(fullpath); if (backend) { backends = g_list_append(backends, backend); } g_free(fullpath); } g_dir_close(dir); g_free(glob); g_free(pattern); } hashfs_backend_t * hashfs_backends_lookup (const gchar *name) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; if (!g_strcmp0(name, backend->desc->shortname)) return backend; } return NULL; } void hashfs_backends_destroy (void) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; hashfs_backend_destroy(backend); } g_list_free(backends); } void hashfs_backend_init (hashfs_backend_t *backend) { if (backend->funcs.init) { backend->funcs.init(backend); } } void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file) { if (backend->funcs.file) { backend->funcs.file(backend, file); } } void hashfs_backend_destroy (hashfs_backend_t *backend) { if (backend->funcs.destroy) { backend->funcs.destroy(backend); } if (backend->module) g_module_close(backend->module); g_free(backend); } void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, - gchar *defaultval) + const gchar *defaultval) { if (!hashfs_config_property_exists(backend->desc->shortname, key)) { hashfs_config_property_set(backend->desc->shortname, key, defaultval); } } void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out) { hashfs_config_property_lookup(backend->desc->shortname, key, out); } diff --git a/src/hashfs/db.c b/src/hashfs/db.c index e69de29..be0d5eb 100644 --- a/src/hashfs/db.c +++ b/src/hashfs/db.c @@ -0,0 +1,147 @@ +#include <glib.h> +#include <string.h> +#include <stdio.h> + + +#include "hashfs.h" + + +static hashfs_db_t *db; + +gboolean +hashfs_db_open (void) +{ + gchar *path; + gboolean rval; + + g_return_val_if_fail(db == NULL, FALSE); + + db = g_new0(hashfs_db_t, 1); + db->tdb = tctdbnew(); + + path = g_build_filename(g_get_user_config_dir(), "hashfs", "metadata.tct", NULL); + + if (!tctdbopen(db->tdb, path, TDBOWRITER | TDBOCREAT)) { + HASHFS_DEBUG("Unable to open DB: %s", hashfs_db_error()); + + rval = FALSE; + } else { + HASHFS_DEBUG("Successfully opened DB"); + + rval = TRUE; + } + + g_free(path); + + return rval; +} + +void +hashfs_db_close (void) +{ + g_return_if_fail(db != NULL); + + if (!tctdbclose(db->tdb)) { + HASHFS_DEBUG("Unable to close DB: %s", hashfs_db_error()); + } else { + HASHFS_DEBUG("Successfully closed DB"); + } + + tctdbdel(db->tdb); + + free(db); +} + +gboolean +hashfs_db_tran_begin (void) +{ + return (gboolean) tctdbtranbegin(db->tdb); +} + +gboolean +hashfs_db_tran_commit (void) +{ + return (gboolean) tctdbtrancommit(db->tdb); +} + +gboolean +hashfs_db_tran_abort (void) +{ + return (gboolean) tctdbtranabort(db->tdb); +} + +gchar * +hashfs_db_error (void) +{ + gint ecode = tctdbecode(db->tdb); + + return (gchar *) tctdberrmsg(ecode); +} + +hashfs_db_entry_t * +hashfs_db_entry_new (const gchar *prefix, const gchar *id, + const gchar *source, const gchar *type) +{ + hashfs_db_entry_t *entry; + gchar *pkey, *md5; + + md5 = hashfs_md5_str(id); + + if (!g_strcmp0(prefix, "set")) { + pkey = g_strdup_printf("%s:%s:%s:%s", prefix, source, type, md5); + } else { + pkey = g_strdup_printf("%s:%s", prefix, md5); + } + + entry = g_new0(hashfs_db_entry_t, 1); + entry->pkey = pkey; + entry->data = tcmapnew(); + + HASHFS_DEBUG("Created entry with pkey: %s", pkey); + + g_free(md5); + + return entry; +} + +void +hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, + const gchar *value) +{ + g_return_if_fail(entry != NULL); + g_return_if_fail(entry->data != NULL); + + tcmapput2(entry->data, key, value); +} + +gboolean +hashfs_db_entry_get (hashfs_db_entry_t *entry, const gchar *key, + const gchar **out) +{ + +} + +gboolean +hashfs_db_entry_put (hashfs_db_entry_t *entry) +{ + g_return_val_if_fail(entry != NULL, FALSE); + g_return_val_if_fail(entry->pkey != NULL, FALSE); + g_return_val_if_fail(entry->data != NULL, FALSE); + + return (gboolean) tctdbputcat(db->tdb, entry->pkey, strlen(entry->pkey), + entry->data); +} + +void +hashfs_db_entry_destroy (hashfs_db_entry_t *entry) +{ + g_return_if_fail (entry != NULL); + + if (entry->data) + tcmapdel(entry->data); + + if (entry->pkey) + g_free(entry->pkey); + + g_free(entry); +} diff --git a/src/hashfs/ed2k.c b/src/hashfs/ed2k.c index ba4f212..b36de51 100644 --- a/src/hashfs/ed2k.c +++ b/src/hashfs/ed2k.c @@ -1,98 +1,98 @@ #define _FILE_OFFSET_BITS 64 #define _LARGEFILE_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _LARGE_FILES 1 #define BLOCKSIZE (9500*1024) #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> #include <openssl/md4.h> #include <glib.h> #include <glib/gstdio.h> #include <glib/gprintf.h> #include "hashfs.h" static const gchar hexdigits[16] = "0123456789abcdef"; gint -hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out) +hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out) { gint blocks, fd, len; gint64 size, offset; guchar *hash_blocks, *hash_final; gchar *hash_str; MD4_CTX ctx; gpointer data; if ((fd = g_open(file->filename, O_RDONLY, "rb")) < 0) { HASHFS_DEBUG("Failed to open file (%s)", file->filename); return 0; } blocks = file->size / BLOCKSIZE; if ((file->size % BLOCKSIZE) > 0) blocks++; if (blocks < 1) return 0; hash_blocks = g_malloc(blocks * 16); hash_str = g_strnfill(33, 0); offset = 0; g_return_val_if_fail(hash_blocks != NULL, 0); g_return_val_if_fail(hash_str != NULL, 0); for (gint b = 0; b < blocks; b++) { len = (blocks - b) == 1 ? file->size % BLOCKSIZE : BLOCKSIZE; data = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, offset); g_return_val_if_fail(data != NULL, 0); MD4_Init(&ctx); MD4_Update(&ctx, data, len); MD4_Final(hash_blocks + (b * 16), &ctx); munmap(data, len); offset += len; } close(fd); /* If we have hashed more than one block, run MD4 on all the previous hashes */ if (blocks > 1) { hash_final = g_malloc(16); MD4_Init(&ctx); MD4_Update(&ctx, hash_blocks, 16 * blocks); MD4_Final(hash_final, &ctx); } else { hash_final = g_memdup(hash_blocks, 16); } /* Convert hash to hex string format */ for (gint i = 0; i < 16; i++) { hash_str[(i<<1)] = hexdigits[(((hash_final[i]) & 0xf0) >> 4)]; hash_str[(i<<1)+1] = hexdigits[(((hash_final[i]) & 0x0f))]; } g_free(hash_blocks); g_free(hash_final); file->ed2k = hash_str; *out = hash_str; return 1; } diff --git a/src/hashfs/file.c b/src/hashfs/file.c index 24f7ffe..fabc3e2 100644 --- a/src/hashfs/file.c +++ b/src/hashfs/file.c @@ -1,79 +1,100 @@ #include <glib.h> #include "hashfs.h" hashfs_file_t * -hashfs_file_new (gchar *filename) +hashfs_file_new (const gchar *filename, hashfs_backend_t *backend) { hashfs_file_t *file; struct stat info; stat(filename, &info); file = g_new0(hashfs_file_t, 1); - file->filename = filename; + file->backend = backend; + file->entry = hashfs_db_entry_new("file", filename, NULL, NULL); + file->filename = g_strdup(filename); file->size = (gint64) info.st_size; + file->ed2k = NULL; file->md5 = NULL; + hashfs_db_entry_set(file->entry, "path", filename); + return file; } gint hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, - gchar **out) + const gchar **out) { HASHFS_DEBUG("File (%s) looking up property: %s", hashfs_basename(file->filename), key); // TODO: Actually look up property from DB. return 0; } void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, - gchar *value) + const gchar *value) { HASHFS_DEBUG("File (%s) setting property: %s = %s", hashfs_basename(file->filename), key, value); - // TODO: Set property in DB. + hashfs_db_entry_set(file->entry, key, value); } hashfs_set_t * -hashfs_file_add_to_set (hashfs_file_t *file, gchar *setname) +hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, + const gchar *type) { hashfs_set_t *set; + const gchar *source; + + if (file->backend) + source = file->backend->desc->shortname; + else + source = "unknown"; - set = hashfs_set_new(setname); + set = hashfs_set_new(name, source, type); - hashfs_set_add_file(set, file); + hashfs_db_entry_set(file->entry, type, set->entry->pkey); file->sets = g_list_append(file->sets, set); return set; } void hashfs_file_destroy (hashfs_file_t *file) { + HASHFS_DEBUG("File (%s) destroying", hashfs_basename(file->filename)); + + if (file->filename) + g_free(file->filename); + if (file->ed2k) g_free(file->ed2k); if (file->md5) g_free(file->md5); if (file->sets) { GList *item; hashfs_set_t *set; for (item = g_list_first(file->sets); item; item = g_list_next(item)) { set = item->data; hashfs_set_destroy(set); } g_list_free(file->sets); } - HASHFS_DEBUG("File (%s) destroying", hashfs_basename(file->filename)); + if (file->entry) { + hashfs_db_entry_put(file->entry); + hashfs_db_entry_destroy(file->entry); + } + g_free(file); } diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index 81b4b0d..cd04ad7 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,221 +1,223 @@ #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { hashfs_file_t *file; HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); - file = hashfs_file_new(path); - + file = hashfs_file_new(path, backend); hashfs_backend_file(backend, file); hashfs_file_destroy(file); } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; HASHFS_LOG("Hashing dir: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; gchar *val; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { hashfs_config_property_lookup(groups[i], keys[j], &val); printf("%s.%s = %s\n", groups[i], keys[j], val); g_free(val); } g_strfreev(keys); } g_strfreev(groups); } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } g_free(val); g_strfreev(split); } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } g_strfreev(split); } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; hashfs_config_load(); + hashfs_db_open(); if (g_module_supported()) { - gchar *backenddir = g_build_filename(g_get_user_config_dir(), "hashfs", "backends", NULL); +// gchar *backenddir = g_build_filename(g_get_user_config_dir(), "hashfs", "backends", NULL); - hashfs_backends_load(backenddir); +// hashfs_backends_load(backenddir); hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); - g_free(backenddir); +// g_free(backenddir); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); - hashfs_config_save(); hashfs_backends_destroy(); + hashfs_config_save(); + hashfs_db_close(); + return 0; } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index 05935a7..117ce98 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,131 +1,175 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> + #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> +#include <tcutil.h> +#include <tctdb.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; +struct hashfs_db_St; +struct hashfs_db_entry_St; struct hashfs_file_St; struct hashfs_set_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; +typedef struct hashfs_db_St hashfs_db_t; +typedef struct hashfs_db_entry_St hashfs_db_entry_t; typedef struct hashfs_file_St hashfs_file_t; typedef struct hashfs_set_St hashfs_set_t; - -struct hashfs_file_St { - gchar *filename; - gint64 size; - GList *sets; - - /* Hashes */ - gchar *ed2k; - gchar *md5; -}; - -struct hashfs_set_St { - gchar name[256]; -}; - struct hashfs_backend_St { gpointer data; GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; -gchar * hashfs_current_time (void); -gchar * hashfs_basename (gchar *name); +struct hashfs_db_St { + TCTDB *tdb; +}; +struct hashfs_db_entry_St { + TCMAP *data; + gchar *pkey; +}; +struct hashfs_file_St { + gchar *filename; + gint64 size; + GList *sets; + hashfs_backend_t *backend; + hashfs_db_entry_t *entry; + + /* Hashes */ + gchar *ed2k; + gchar *md5; +}; + +struct hashfs_set_St { + gchar name[256]; + hashfs_db_entry_t *entry; +}; + +/* Config */ GKeyFile * hashfs_config_keyfile (void); void hashfs_config_load (void); void hashfs_config_save (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); -hashfs_set_t * hashfs_set_new (gchar *name); -void hashfs_set_add_file (hashfs_set_t *set, hashfs_file_t *file); -gint hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, gchar **out); -void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, gchar *value); + +/* Database */ +gboolean hashfs_db_open (void); +void hashfs_db_close (void); +gchar * hashfs_db_error (void); + +gboolean hashfs_db_tran_abort (void); +gboolean hashfs_db_tran_begin (void); +gboolean hashfs_db_tran_commit (void); + +/* Database entry */ +hashfs_db_entry_t * hashfs_db_entry_new (const gchar *prefix, const gchar *id, const gchar *source, const gchar *type); +void hashfs_db_entry_set (hashfs_db_entry_t *entry, const gchar *key, const gchar *value); +gboolean hashfs_db_entry_get (hashfs_db_entry_t *entry, const gchar *key, const gchar **out); +gboolean hashfs_db_entry_put (hashfs_db_entry_t *entry); +void hashfs_db_entry_destroy (hashfs_db_entry_t *entry); + +/* Set */ +hashfs_set_t * hashfs_set_new (const gchar *name, const gchar *source, const gchar *type); +gint hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, const gchar **out); +void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, const gchar *value); void hashfs_set_destroy (hashfs_set_t *set); -hashfs_file_t * hashfs_file_new (gchar *filename); -gint hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out); -gint hashfs_file_hash_md5 (hashfs_file_t *file, gchar **out); -gint hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, gchar **out); -void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, gchar *value); -hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, gchar *setname); + +/* File */ +hashfs_file_t * hashfs_file_new (const gchar *filename, hashfs_backend_t *backend); +gint hashfs_file_hash_ed2k (hashfs_file_t *file, const gchar **out); +gint hashfs_file_hash_md5 (hashfs_file_t *file, const gchar **out); +gint hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, const gchar **out); +void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, const gchar *value); +hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, const gchar *name, const gchar *type); void hashfs_file_destroy (hashfs_file_t *file); + +/* Backend manager */ hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); -void hashfs_backends_load (gchar *path); +void hashfs_backends_load (const gchar *path); void hashfs_backends_destroy (void); + +/* Backend */ hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); - -void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, gchar *defaultval); +void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, const gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); + +/* Utils */ +gchar * hashfs_current_time (void); +gchar * hashfs_basename (const gchar *name); +gchar * hashfs_md5_str (const gchar *str); + + #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ gchar *log_time = hashfs_current_time(); \ printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ gchar *log_time = hashfs_current_time(); \ FILE *fd = g_fopen(log_path, "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ g_free(log_path); \ g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif diff --git a/src/hashfs/set.c b/src/hashfs/set.c index 1d04b56..b163542 100644 --- a/src/hashfs/set.c +++ b/src/hashfs/set.c @@ -1,56 +1,52 @@ #include <glib.h> #include <glib/gprintf.h> #include "hashfs.h" hashfs_set_t * -hashfs_set_new (gchar *name) +hashfs_set_new (const gchar *name, const gchar *source, const gchar *type) { hashfs_set_t *set; set = g_new0(hashfs_set_t, 1); + set->entry = hashfs_db_entry_new("set", name, source, type); g_strlcpy(set->name, name, sizeof(set->name)); HASHFS_DEBUG("Creating new set: %s", name); - // TODO: Create new entry in DB if necessary. - return set; } -void -hashfs_set_add_file (hashfs_set_t *set, hashfs_file_t *file) -{ - HASHFS_DEBUG("Set (%s) adding file: %s", set->name, file->filename); - - // TODO: Add fileid to set in DB. -} - gint hashfs_set_prop_lookup (hashfs_set_t *set, const gchar *key, - gchar **out) + const gchar **out) { HASHFS_DEBUG("Set (%s) looking up property: %s", set->name, key); // TODO: Actually look up property from DB. return 0; } void hashfs_set_prop_set (hashfs_set_t *set, const gchar *key, - gchar *value) + const gchar *value) { HASHFS_DEBUG("Set (%s) setting property: %s = %s", set->name, key, value); - // TODO: Set property in DB. + hashfs_db_entry_set(set->entry, key, value); } void hashfs_set_destroy (hashfs_set_t *set) { HASHFS_DEBUG("Set (%s) destroying", set->name); + if (set->entry) { + hashfs_db_entry_put(set->entry); + hashfs_db_entry_destroy(set->entry); + } + g_free(set); } diff --git a/src/hashfs/util.c b/src/hashfs/util.c index 520cc6f..8e135e3 100644 --- a/src/hashfs/util.c +++ b/src/hashfs/util.c @@ -1,35 +1,41 @@ #include <sys/time.h> #include <string.h> #include <time.h> #include "hashfs.h" gchar * -hashfs_basename (char *name) +hashfs_basename (const gchar *name) { - const char *base; + gchar *ptr, *base; - for (base = name; *name; name++) { - if (*name == '/') { - base = name + 1; + for (ptr = (gchar *) name; *ptr; ptr++) { + if (*ptr == '/') { + base = ptr + 1; } } - return (char *) base; + return base; } gchar * hashfs_current_time (void) { char buf[256]; time_t tv; struct tm st; tv = time(NULL); localtime_r(&tv, &st); strftime(buf, sizeof(buf), "%H:%M:%S", &st); return g_strdup(buf); } +gchar * +hashfs_md5_str (const gchar *str) +{ + return g_compute_checksum_for_string(G_CHECKSUM_MD5, str, -1); +} + diff --git a/src/hashfs/wscript b/src/hashfs/wscript index bb38a11..7dab0c8 100644 --- a/src/hashfs/wscript +++ b/src/hashfs/wscript @@ -1,42 +1,42 @@ # vim: set fileencoding=utf-8 filetype=python : hashfs = ['hashfs.c', 'db.c', 'ed2k.c', 'config.c', 'backend.c', 'util.c', 'set.c', 'file.c'] hashfsmount = ['hashfsmount.c', 'util.c'] def set_options(opt): pass def configure(conf): - for pkg in ['fuse', 'glib-2.0', 'gmodule-2.0', 'openssl']: + for pkg in ['fuse', 'glib-2.0', 'gmodule-2.0', 'tokyocabinet', 'openssl']: if not conf.check_cfg(package = pkg, args = '--cflags --libs', uselib_store = pkg): conf.fatal('Unable to find required library') def build(bld): import Options defines = [] if Options.options.debug: defines += ['DEBUG'] obj = bld.new_task_gen( features = 'cc cprogram', source = hashfs, target = 'hashfs', install_path = '${PREFIX}/bin', - uselib = 'glib-2.0 gmodule-2.0 openssl', + uselib = 'glib-2.0 gmodule-2.0 tokyocabinet openssl', uselib_local = 'anidb', ccflags = ['-std=gnu99', '-g'], defines = defines ) obj = bld.new_task_gen( features = 'cc cprogram', source = hashfsmount, target = 'hashfsmount', uselib = 'fuse glib-2.0', install_path = '${PREFIX}/bin', ccflags = ['-std=gnu99', '-g'], defines = defines )
chrippa/hashfs
5a439f27f8b2a54284705089a1ec05217b7f0db6
Add stubs for file sets and properties.
diff --git a/src/backends/anidb/anidb.c b/src/backends/anidb/anidb.c index 7569c26..6766581 100644 --- a/src/backends/anidb/anidb.c +++ b/src/backends/anidb/anidb.c @@ -1,176 +1,231 @@ #include <stdio.h> #include <hashfs.h> #include <anidb.h> static void hashfs_anidb_setup (hashfs_backend_t *backend); static gboolean hashfs_anidb_init (hashfs_backend_t *backend); static void hashfs_anidb_destroy (hashfs_backend_t *backend); static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file); static void dump_result (anidb_result_t *result); HASHFS_BACKEND("anidb", "AniDB", "AniDB hashing backend", hashfs_anidb_setup); typedef struct hashfs_anidb_data_St { anidb_session_t *session; } hashfs_anidb_data_t; static void hashfs_anidb_setup (hashfs_backend_t *backend) { backend->funcs.init = hashfs_anidb_init; backend->funcs.file = hashfs_anidb_handle_file; backend->funcs.destroy = hashfs_anidb_destroy; hashfs_backend_config_register(backend, "username", ""); hashfs_backend_config_register(backend, "password", ""); hashfs_backend_config_register(backend, "local_port", "0"); } static gboolean hashfs_anidb_init (hashfs_backend_t *backend) { anidb_session_t *session; anidb_result_t *res; hashfs_anidb_data_t *data; gchar *username, *password, *port_s, *key; gint port; gboolean rval; - HASHFS_DEBUG("Init func"); HASHFS_DEBUG("Connecting to AniDB"); hashfs_backend_config_lookup(backend, "username", &username); hashfs_backend_config_lookup(backend, "password", &password); hashfs_backend_config_lookup(backend, "local_port", &port_s); port = atoi(port_s); HASHFS_DEBUG("username=%s, password=%s, port=%d", username, password, port); session = anidb_session_new("anidbfuse", "1", port); data = g_new0(hashfs_anidb_data_t, 1); data->session = session; backend->data = data; res = anidb_session_authenticate(session, username, password); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); HASHFS_DEBUG("Successfully logged in"); rval = TRUE; } else { HASHFS_DEBUG("Failed to get session key"); rval = FALSE; } } else { HASHFS_DEBUG("Unable to login to AniDB servers"); rval = FALSE; } g_free(username); g_free(password); g_free(port_s); anidb_result_unref(res); return rval; } static void hashfs_anidb_destroy (hashfs_backend_t *backend) { hashfs_anidb_data_t *data; - HASHFS_DEBUG("Destroy func"); - g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; if (data) { if (anidb_session_is_logged_in(data->session)) { HASHFS_DEBUG("Logging out"); anidb_result_unref(anidb_session_logout(data->session)); } anidb_session_unref(data->session); g_free(data); } } +#define ANIDB_SET_PROP(res, file, prop) { \ + gchar *tmp; \ + if (anidb_result_dict_get((res), (prop), &tmp)) \ + hashfs_file_prop_set((file), (prop), tmp); \ +} + static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file) { hashfs_anidb_data_t *data; gchar *hash; - anidb_result_t *res; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; g_return_if_fail(data); if (anidb_session_is_logged_in(data->session)) { if (hashfs_file_hash_ed2k(file, &hash)) { + hashfs_set_t *set; + anidb_result_t *res; + gchar *tmp; + HASHFS_DEBUG("ed2k hash: %s", hash); res = anidb_session_file_ed2k(data->session, file->size, hash); - dump_result(res); +// dump_result(res); + + ANIDB_SET_PROP(res, file, "fid"); + ANIDB_SET_PROP(res, file, "eid"); + ANIDB_SET_PROP(res, file, "state"); + ANIDB_SET_PROP(res, file, "size"); + ANIDB_SET_PROP(res, file, "ed2k"); + ANIDB_SET_PROP(res, file, "md5"); + ANIDB_SET_PROP(res, file, "sha1"); + ANIDB_SET_PROP(res, file, "crc32"); + ANIDB_SET_PROP(res, file, "dub"); + ANIDB_SET_PROP(res, file, "sub"); + ANIDB_SET_PROP(res, file, "quality"); + ANIDB_SET_PROP(res, file, "source"); + ANIDB_SET_PROP(res, file, "audio"); + ANIDB_SET_PROP(res, file, "video"); + ANIDB_SET_PROP(res, file, "resolution"); + ANIDB_SET_PROP(res, file, "ext"); + ANIDB_SET_PROP(res, file, "duration"); + ANIDB_SET_PROP(res, file, "ep_number"); + ANIDB_SET_PROP(res, file, "ep_eng"); + ANIDB_SET_PROP(res, file, "ep_romaji"); + ANIDB_SET_PROP(res, file, "ep_kanji"); + + if (anidb_result_dict_get(res, "anime_romaji", &tmp)) { + set = hashfs_file_add_to_set(file, tmp); + + hashfs_set_prop_set(set, "romaji", tmp); + + if (anidb_result_dict_get(res, "anime_totalep", &tmp)) + hashfs_set_prop_set(set, "totalep", tmp); + + if (anidb_result_dict_get(res, "anime_lastep", &tmp)) + hashfs_set_prop_set(set, "lastep", tmp); + + if (anidb_result_dict_get(res, "anime_year", &tmp)) + hashfs_set_prop_set(set, "year", tmp); + + if (anidb_result_dict_get(res, "anime_type", &tmp)) + hashfs_set_prop_set(set, "type", tmp); + + if (anidb_result_dict_get(res, "anime_kanji", &tmp)) + hashfs_set_prop_set(set, "kanji", tmp); + + if (anidb_result_dict_get(res, "anime_eng", &tmp)) + hashfs_set_prop_set(set, "eng", tmp); + + if (anidb_result_dict_get(res, "anime_categories", &tmp)) + hashfs_set_prop_set(set, "categories", tmp); + + } anidb_result_unref(res); - g_free(hash); } } } static void dump_result (anidb_result_t *result) { gint n; gchar *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: HASHFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); HASHFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); HASHFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: HASHFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { HASHFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); } HASHFS_DEBUG(">"); break; } } diff --git a/src/hashfs/backend.c b/src/hashfs/backend.c index 8cdcd3f..85ac4c0 100644 --- a/src/hashfs/backend.c +++ b/src/hashfs/backend.c @@ -1,203 +1,189 @@ #include <glib.h> #include <gmodule.h> #include "hashfs.h" static GList *backends; hashfs_backend_t * hashfs_backend_load (const gchar *path) { GModule *module; gpointer sym; hashfs_backend_t *backend; hashfs_backend_desc_t *desc; HASHFS_DEBUG("Loading module (%s)", path); module = g_module_open(path, 0); if (!module) { HASHFS_DEBUG("Failed to load module: %s", g_module_error()); return NULL; } if (!g_module_symbol(module, "HASHFS_BACKEND_DESC", (gpointer) &sym)) { HASHFS_DEBUG("Failed to lookup symbol: %s", g_module_error()); g_module_close(module); return NULL; } desc = (hashfs_backend_desc_t *) sym; if (!desc) { HASHFS_DEBUG("HASHFS_BACKEND_DESC == NULL"); g_module_close(module); return NULL; } if (hashfs_backends_lookup(desc->shortname)) { HASHFS_DEBUG("Already loaded backend %s", desc->shortname); g_module_close(module); return NULL; } backend = g_new0(hashfs_backend_t, 1); backend->desc = desc; backend->module = module; desc->setup_func(backend); HASHFS_DEBUG("Backend successfully loaded: %s - %s - %s", desc->shortname, desc->name, desc->description); return backend; } void hashfs_backends_load (gchar *path) { GDir *dir; GError *error = NULL; const gchar *filename; gchar *pattern, *glob; hashfs_backend_t *backend; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } glob = g_module_build_path(path, "hashfs_*"); pattern = g_path_get_basename(glob); HASHFS_DEBUG("Loooking for backends in: %s", glob); while ((filename = g_dir_read_name(dir))) { if (!g_pattern_match_simple(pattern, filename)) continue; gchar *fullpath = g_build_filename(path, filename, NULL); if (!g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { g_free(fullpath); continue; } backend = hashfs_backend_load(fullpath); if (backend) { backends = g_list_append(backends, backend); } g_free(fullpath); } g_dir_close(dir); g_free(glob); g_free(pattern); } hashfs_backend_t * hashfs_backends_lookup (const gchar *name) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; if (!g_strcmp0(name, backend->desc->shortname)) return backend; } return NULL; } void hashfs_backends_destroy (void) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; hashfs_backend_destroy(backend); } g_list_free(backends); } -hashfs_file_t * -hashfs_file_new (gchar *filename) -{ - hashfs_file_t *file; - struct stat info; - - stat(filename, &info); - - file = g_new0(hashfs_file_t, 1); - file->filename = filename; - file->size = (gint64) info.st_size; - - return file; -} void hashfs_backend_init (hashfs_backend_t *backend) { if (backend->funcs.init) { backend->funcs.init(backend); } } void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file) { if (backend->funcs.file) { backend->funcs.file(backend, file); } } void hashfs_backend_destroy (hashfs_backend_t *backend) { if (backend->funcs.destroy) { backend->funcs.destroy(backend); } if (backend->module) g_module_close(backend->module); g_free(backend); } void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, gchar *defaultval) { if (!hashfs_config_property_exists(backend->desc->shortname, key)) { hashfs_config_property_set(backend->desc->shortname, key, defaultval); } } void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out) { hashfs_config_property_lookup(backend->desc->shortname, key, out); } diff --git a/src/hashfs/config.c b/src/hashfs/config.c index 0590d39..249dbad 100644 --- a/src/hashfs/config.c +++ b/src/hashfs/config.c @@ -1,103 +1,102 @@ #include <glib.h> #include "hashfs.h" static GKeyFile *config; -static gboolean config_loaded; static gchar * hashfs_config_build_path (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key) { if (g_key_file_has_group(config, group)) { return g_key_file_has_key(config, group, key, NULL); } return FALSE; } void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out) { *out = g_key_file_get_string(config, group, key, NULL); } void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value) { g_key_file_set_string(config, group, key, value); } GKeyFile * hashfs_config_keyfile (void) { return config; } void hashfs_config_load (void) { GError *error = NULL; gchar *configfile; config = g_key_file_new(); configfile = hashfs_config_build_path(); g_key_file_load_from_file(config, configfile, G_KEY_FILE_NONE, &error); if (error) { /* Don't error when file doesn't exist or is empty */ if (error->code != 4 && error->code != 1) { HASHFS_ERROR("Unable to load config file (%s): %d %s", configfile, error->message); } g_error_free(error); } g_free(configfile); } void hashfs_config_save (void) { gchar *configfile, *data; FILE *file; configfile = hashfs_config_build_path(); data = g_key_file_to_data(config, NULL, NULL); file = g_fopen(configfile, "w"); fputs(data, file); fclose(file); g_free(configfile); g_free(data); g_key_file_free(config); } static gchar * hashfs_config_build_path (void) { gchar *configdir, *configfile; const gchar *userconfigdir; userconfigdir = g_get_user_config_dir(); configdir = g_build_filename(userconfigdir, "hashfs", NULL); configfile = g_build_filename(configdir, "hashfs.conf", NULL); if (g_file_test(configdir, G_FILE_TEST_EXISTS)) { if (!g_file_test(configdir, G_FILE_TEST_IS_DIR)) HASHFS_ERROR("Config directory already exists but is not a directory (%s)", configdir); } else { if (g_mkdir_with_parents(configdir, 0755) < 0) { HASHFS_ERROR("Unable to create config directory (%s)", configdir); } } g_free(configdir); return configfile; } diff --git a/src/hashfs/ed2k.c b/src/hashfs/ed2k.c index 0610b94..ba4f212 100644 --- a/src/hashfs/ed2k.c +++ b/src/hashfs/ed2k.c @@ -1,97 +1,98 @@ #define _FILE_OFFSET_BITS 64 #define _LARGEFILE_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _LARGE_FILES 1 #define BLOCKSIZE (9500*1024) #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> #include <openssl/md4.h> #include <glib.h> #include <glib/gstdio.h> #include <glib/gprintf.h> #include "hashfs.h" static const gchar hexdigits[16] = "0123456789abcdef"; gint hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out) { gint blocks, fd, len; gint64 size, offset; guchar *hash_blocks, *hash_final; gchar *hash_str; MD4_CTX ctx; gpointer data; if ((fd = g_open(file->filename, O_RDONLY, "rb")) < 0) { HASHFS_DEBUG("Failed to open file (%s)", file->filename); return 0; } blocks = file->size / BLOCKSIZE; if ((file->size % BLOCKSIZE) > 0) blocks++; if (blocks < 1) return 0; hash_blocks = g_malloc(blocks * 16); hash_str = g_strnfill(33, 0); offset = 0; g_return_val_if_fail(hash_blocks != NULL, 0); g_return_val_if_fail(hash_str != NULL, 0); for (gint b = 0; b < blocks; b++) { len = (blocks - b) == 1 ? file->size % BLOCKSIZE : BLOCKSIZE; data = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, offset); g_return_val_if_fail(data != NULL, 0); MD4_Init(&ctx); MD4_Update(&ctx, data, len); MD4_Final(hash_blocks + (b * 16), &ctx); munmap(data, len); offset += len; } close(fd); /* If we have hashed more than one block, run MD4 on all the previous hashes */ if (blocks > 1) { hash_final = g_malloc(16); MD4_Init(&ctx); MD4_Update(&ctx, hash_blocks, 16 * blocks); MD4_Final(hash_final, &ctx); } else { hash_final = g_memdup(hash_blocks, 16); } /* Convert hash to hex string format */ for (gint i = 0; i < 16; i++) { hash_str[(i<<1)] = hexdigits[(((hash_final[i]) & 0xf0) >> 4)]; hash_str[(i<<1)+1] = hexdigits[(((hash_final[i]) & 0x0f))]; } g_free(hash_blocks); g_free(hash_final); + file->ed2k = hash_str; *out = hash_str; return 1; } diff --git a/src/hashfs/file.c b/src/hashfs/file.c new file mode 100644 index 0000000..24f7ffe --- /dev/null +++ b/src/hashfs/file.c @@ -0,0 +1,79 @@ +#include <glib.h> + +#include "hashfs.h" + +hashfs_file_t * +hashfs_file_new (gchar *filename) +{ + hashfs_file_t *file; + struct stat info; + + stat(filename, &info); + + file = g_new0(hashfs_file_t, 1); + file->filename = filename; + file->size = (gint64) info.st_size; + file->ed2k = NULL; + file->md5 = NULL; + + return file; +} + +gint +hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, + gchar **out) +{ + HASHFS_DEBUG("File (%s) looking up property: %s", hashfs_basename(file->filename), key); + + // TODO: Actually look up property from DB. + + return 0; +} + +void +hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, + gchar *value) +{ + HASHFS_DEBUG("File (%s) setting property: %s = %s", hashfs_basename(file->filename), key, value); + + // TODO: Set property in DB. +} + +hashfs_set_t * +hashfs_file_add_to_set (hashfs_file_t *file, gchar *setname) +{ + hashfs_set_t *set; + + set = hashfs_set_new(setname); + + hashfs_set_add_file(set, file); + + file->sets = g_list_append(file->sets, set); + + return set; +} + +void +hashfs_file_destroy (hashfs_file_t *file) +{ + if (file->ed2k) + g_free(file->ed2k); + + if (file->md5) + g_free(file->md5); + + if (file->sets) { + GList *item; + hashfs_set_t *set; + + for (item = g_list_first(file->sets); item; item = g_list_next(item)) { + set = item->data; + hashfs_set_destroy(set); + } + g_list_free(file->sets); + } + + HASHFS_DEBUG("File (%s) destroying", hashfs_basename(file->filename)); + + g_free(file); +} diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index f6ace86..81b4b0d 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,209 +1,221 @@ #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { hashfs_file_t *file; HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); file = hashfs_file_new(path); hashfs_backend_file(backend, file); - g_free(file); + hashfs_file_destroy(file); } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; HASHFS_LOG("Hashing dir: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; + gchar *val; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { - printf("%s.%s = %s\n", groups[i], keys[j], g_key_file_get_string(config, - groups[i], keys[j], NULL)); + hashfs_config_property_lookup(groups[i], keys[j], &val); + printf("%s.%s = %s\n", groups[i], keys[j], val); + + g_free(val); } + + g_strfreev(keys); } + + g_strfreev(groups); } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } + + g_free(val); + g_strfreev(split); } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } + + g_strfreev(split); } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; hashfs_config_load(); if (g_module_supported()) { gchar *backenddir = g_build_filename(g_get_user_config_dir(), "hashfs", "backends", NULL); hashfs_backends_load(backenddir); hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); g_free(backenddir); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); hashfs_config_save(); hashfs_backends_destroy(); return 0; } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index 675edc8..05935a7 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,111 +1,131 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_file_St; +struct hashfs_set_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_file_St hashfs_file_t; +typedef struct hashfs_set_St hashfs_set_t; struct hashfs_file_St { gchar *filename; gint64 size; + GList *sets; + + /* Hashes */ + gchar *ed2k; + gchar *md5; +}; + +struct hashfs_set_St { + gchar name[256]; }; struct hashfs_backend_St { gpointer data; GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; gchar * hashfs_current_time (void); gchar * hashfs_basename (gchar *name); GKeyFile * hashfs_config_keyfile (void); void hashfs_config_load (void); void hashfs_config_save (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); +hashfs_set_t * hashfs_set_new (gchar *name); +void hashfs_set_add_file (hashfs_set_t *set, hashfs_file_t *file); +gint hashfs_set_prop_lookup (hashfs_set_t *file, const gchar *key, gchar **out); +void hashfs_set_prop_set (hashfs_set_t *file, const gchar *key, gchar *value); +void hashfs_set_destroy (hashfs_set_t *set); + hashfs_file_t * hashfs_file_new (gchar *filename); gint hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out); +gint hashfs_file_hash_md5 (hashfs_file_t *file, gchar **out); gint hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, gchar *value); +hashfs_set_t * hashfs_file_add_to_set (hashfs_file_t *file, gchar *setname); +void hashfs_file_destroy (hashfs_file_t *file); hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); void hashfs_backends_load (gchar *path); void hashfs_backends_destroy (void); hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ gchar *log_time = hashfs_current_time(); \ printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ gchar *log_time = hashfs_current_time(); \ FILE *fd = g_fopen(log_path, "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ g_free(log_path); \ g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif diff --git a/src/hashfs/set.c b/src/hashfs/set.c new file mode 100644 index 0000000..1d04b56 --- /dev/null +++ b/src/hashfs/set.c @@ -0,0 +1,56 @@ +#include <glib.h> +#include <glib/gprintf.h> + + +#include "hashfs.h" + +hashfs_set_t * +hashfs_set_new (gchar *name) +{ + hashfs_set_t *set; + + set = g_new0(hashfs_set_t, 1); + g_strlcpy(set->name, name, sizeof(set->name)); + + HASHFS_DEBUG("Creating new set: %s", name); + + // TODO: Create new entry in DB if necessary. + + return set; +} + +void +hashfs_set_add_file (hashfs_set_t *set, hashfs_file_t *file) +{ + HASHFS_DEBUG("Set (%s) adding file: %s", set->name, file->filename); + + // TODO: Add fileid to set in DB. +} + +gint +hashfs_set_prop_lookup (hashfs_set_t *set, const gchar *key, + gchar **out) +{ + HASHFS_DEBUG("Set (%s) looking up property: %s", set->name, key); + + // TODO: Actually look up property from DB. + + return 0; +} + +void +hashfs_set_prop_set (hashfs_set_t *set, const gchar *key, + gchar *value) +{ + HASHFS_DEBUG("Set (%s) setting property: %s = %s", set->name, key, value); + + // TODO: Set property in DB. +} + +void +hashfs_set_destroy (hashfs_set_t *set) +{ + HASHFS_DEBUG("Set (%s) destroying", set->name); + + g_free(set); +} diff --git a/src/hashfs/util.c b/src/hashfs/util.c index c39c9d9..520cc6f 100644 --- a/src/hashfs/util.c +++ b/src/hashfs/util.c @@ -1,35 +1,35 @@ #include <sys/time.h> #include <string.h> #include <time.h> #include "hashfs.h" gchar * hashfs_basename (char *name) { - const char *base; + const char *base; for (base = name; *name; name++) { if (*name == '/') { base = name + 1; } } return (char *) base; } gchar * hashfs_current_time (void) { char buf[256]; time_t tv; struct tm st; tv = time(NULL); localtime_r(&tv, &st); strftime(buf, sizeof(buf), "%H:%M:%S", &st); return g_strdup(buf); } diff --git a/src/hashfs/wscript b/src/hashfs/wscript index 27e72f4..bb38a11 100644 --- a/src/hashfs/wscript +++ b/src/hashfs/wscript @@ -1,42 +1,42 @@ # vim: set fileencoding=utf-8 filetype=python : -hashfs = ['hashfs.c', 'db.c', 'ed2k.c', 'config.c', 'backend.c', 'util.c'] +hashfs = ['hashfs.c', 'db.c', 'ed2k.c', 'config.c', 'backend.c', 'util.c', 'set.c', 'file.c'] hashfsmount = ['hashfsmount.c', 'util.c'] def set_options(opt): pass def configure(conf): for pkg in ['fuse', 'glib-2.0', 'gmodule-2.0', 'openssl']: if not conf.check_cfg(package = pkg, args = '--cflags --libs', uselib_store = pkg): conf.fatal('Unable to find required library') def build(bld): import Options defines = [] if Options.options.debug: defines += ['DEBUG'] obj = bld.new_task_gen( features = 'cc cprogram', source = hashfs, target = 'hashfs', install_path = '${PREFIX}/bin', uselib = 'glib-2.0 gmodule-2.0 openssl', uselib_local = 'anidb', ccflags = ['-std=gnu99', '-g'], defines = defines ) obj = bld.new_task_gen( features = 'cc cprogram', source = hashfsmount, target = 'hashfsmount', uselib = 'fuse glib-2.0', install_path = '${PREFIX}/bin', ccflags = ['-std=gnu99', '-g'], defines = defines )
chrippa/hashfs
4195d42c05b271e68e64d9ce049844dabf072f2a
Fix memory leaks (valgrind ftw).
diff --git a/src/backends/anidb/anidb.c b/src/backends/anidb/anidb.c index f158392..7569c26 100644 --- a/src/backends/anidb/anidb.c +++ b/src/backends/anidb/anidb.c @@ -1,172 +1,176 @@ #include <stdio.h> #include <hashfs.h> #include <anidb.h> static void hashfs_anidb_setup (hashfs_backend_t *backend); static gboolean hashfs_anidb_init (hashfs_backend_t *backend); static void hashfs_anidb_destroy (hashfs_backend_t *backend); static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file); static void dump_result (anidb_result_t *result); HASHFS_BACKEND("anidb", "AniDB", "AniDB hashing backend", hashfs_anidb_setup); typedef struct hashfs_anidb_data_St { anidb_session_t *session; } hashfs_anidb_data_t; static void hashfs_anidb_setup (hashfs_backend_t *backend) { backend->funcs.init = hashfs_anidb_init; backend->funcs.file = hashfs_anidb_handle_file; backend->funcs.destroy = hashfs_anidb_destroy; hashfs_backend_config_register(backend, "username", ""); hashfs_backend_config_register(backend, "password", ""); hashfs_backend_config_register(backend, "local_port", "0"); } static gboolean hashfs_anidb_init (hashfs_backend_t *backend) { anidb_session_t *session; anidb_result_t *res; hashfs_anidb_data_t *data; gchar *username, *password, *port_s, *key; gint port; gboolean rval; HASHFS_DEBUG("Init func"); HASHFS_DEBUG("Connecting to AniDB"); hashfs_backend_config_lookup(backend, "username", &username); hashfs_backend_config_lookup(backend, "password", &password); hashfs_backend_config_lookup(backend, "local_port", &port_s); port = atoi(port_s); HASHFS_DEBUG("username=%s, password=%s, port=%d", username, password, port); session = anidb_session_new("anidbfuse", "1", port); data = g_new0(hashfs_anidb_data_t, 1); data->session = session; backend->data = data; res = anidb_session_authenticate(session, username, password); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); HASHFS_DEBUG("Successfully logged in"); rval = TRUE; } else { HASHFS_DEBUG("Failed to get session key"); rval = FALSE; } } else { HASHFS_DEBUG("Unable to login to AniDB servers"); rval = FALSE; } + g_free(username); + g_free(password); + g_free(port_s); anidb_result_unref(res); return rval; } static void hashfs_anidb_destroy (hashfs_backend_t *backend) { hashfs_anidb_data_t *data; HASHFS_DEBUG("Destroy func"); g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; if (data) { if (anidb_session_is_logged_in(data->session)) { HASHFS_DEBUG("Logging out"); - anidb_session_logout(data->session); + anidb_result_unref(anidb_session_logout(data->session)); } anidb_session_unref(data->session); g_free(data); } } static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file) { hashfs_anidb_data_t *data; gchar *hash; anidb_result_t *res; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; g_return_if_fail(data); if (anidb_session_is_logged_in(data->session)) { if (hashfs_file_hash_ed2k(file, &hash)) { HASHFS_DEBUG("ed2k hash: %s", hash); res = anidb_session_file_ed2k(data->session, file->size, hash); dump_result(res); anidb_result_unref(res); + g_free(hash); } } } static void dump_result (anidb_result_t *result) { gint n; gchar *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: HASHFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); HASHFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); HASHFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: HASHFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { HASHFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); } HASHFS_DEBUG(">"); break; } } diff --git a/src/hashfs/backend.c b/src/hashfs/backend.c index fd7baf3..8cdcd3f 100644 --- a/src/hashfs/backend.c +++ b/src/hashfs/backend.c @@ -1,194 +1,203 @@ #include <glib.h> #include <gmodule.h> #include "hashfs.h" static GList *backends; hashfs_backend_t * hashfs_backend_load (const gchar *path) { GModule *module; gpointer sym; hashfs_backend_t *backend; hashfs_backend_desc_t *desc; HASHFS_DEBUG("Loading module (%s)", path); module = g_module_open(path, 0); if (!module) { HASHFS_DEBUG("Failed to load module: %s", g_module_error()); return NULL; } if (!g_module_symbol(module, "HASHFS_BACKEND_DESC", (gpointer) &sym)) { HASHFS_DEBUG("Failed to lookup symbol: %s", g_module_error()); g_module_close(module); return NULL; } desc = (hashfs_backend_desc_t *) sym; if (!desc) { HASHFS_DEBUG("HASHFS_BACKEND_DESC == NULL"); g_module_close(module); return NULL; } if (hashfs_backends_lookup(desc->shortname)) { HASHFS_DEBUG("Already loaded backend %s", desc->shortname); g_module_close(module); return NULL; } backend = g_new0(hashfs_backend_t, 1); backend->desc = desc; + backend->module = module; desc->setup_func(backend); HASHFS_DEBUG("Backend successfully loaded: %s - %s - %s", desc->shortname, desc->name, desc->description); + return backend; } void -hashfs_backends_load (const gchar *path) +hashfs_backends_load (gchar *path) { GDir *dir; GError *error = NULL; const gchar *filename; - gchar *pattern, *glob, *fullpath; + gchar *pattern, *glob; hashfs_backend_t *backend; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } glob = g_module_build_path(path, "hashfs_*"); pattern = g_path_get_basename(glob); HASHFS_DEBUG("Loooking for backends in: %s", glob); while ((filename = g_dir_read_name(dir))) { if (!g_pattern_match_simple(pattern, filename)) continue; - fullpath = g_build_filename(path, filename, NULL); + gchar *fullpath = g_build_filename(path, filename, NULL); if (!g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { g_free(fullpath); continue; } backend = hashfs_backend_load(fullpath); if (backend) { backends = g_list_append(backends, backend); } + + g_free(fullpath); } g_dir_close(dir); + g_free(glob); + g_free(pattern); } hashfs_backend_t * hashfs_backends_lookup (const gchar *name) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; if (!g_strcmp0(name, backend->desc->shortname)) return backend; } return NULL; } void hashfs_backends_destroy (void) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; hashfs_backend_destroy(backend); } g_list_free(backends); } hashfs_file_t * hashfs_file_new (gchar *filename) { hashfs_file_t *file; struct stat info; stat(filename, &info); file = g_new0(hashfs_file_t, 1); file->filename = filename; file->size = (gint64) info.st_size; return file; } void hashfs_backend_init (hashfs_backend_t *backend) { if (backend->funcs.init) { backend->funcs.init(backend); } } void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file) { if (backend->funcs.file) { backend->funcs.file(backend, file); } } void hashfs_backend_destroy (hashfs_backend_t *backend) { if (backend->funcs.destroy) { backend->funcs.destroy(backend); } + if (backend->module) + g_module_close(backend->module); + g_free(backend); } void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, gchar *defaultval) { if (!hashfs_config_property_exists(backend->desc->shortname, key)) { hashfs_config_property_set(backend->desc->shortname, key, defaultval); } } void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out) { hashfs_config_property_lookup(backend->desc->shortname, key, out); } diff --git a/src/hashfs/config.c b/src/hashfs/config.c index b56bdfd..0590d39 100644 --- a/src/hashfs/config.c +++ b/src/hashfs/config.c @@ -1,91 +1,103 @@ #include <glib.h> #include "hashfs.h" static GKeyFile *config; static gboolean config_loaded; -static const gchar * hashfs_config_build_path (void); +static gchar * hashfs_config_build_path (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key) { if (g_key_file_has_group(config, group)) { return g_key_file_has_key(config, group, key, NULL); } return FALSE; } void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out) { *out = g_key_file_get_string(config, group, key, NULL); } void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value) { g_key_file_set_string(config, group, key, value); } GKeyFile * hashfs_config_keyfile (void) { return config; } void hashfs_config_load (void) { GError *error = NULL; - const gchar *configfile; + gchar *configfile; config = g_key_file_new(); configfile = hashfs_config_build_path(); g_key_file_load_from_file(config, configfile, G_KEY_FILE_NONE, &error); if (error) { /* Don't error when file doesn't exist or is empty */ if (error->code != 4 && error->code != 1) { HASHFS_ERROR("Unable to load config file (%s): %d %s", configfile, error->message); } g_error_free(error); } + + g_free(configfile); } void hashfs_config_save (void) { - const gchar *configfile; + gchar *configfile, *data; FILE *file; configfile = hashfs_config_build_path(); + data = g_key_file_to_data(config, NULL, NULL); + file = g_fopen(configfile, "w"); - fputs(g_key_file_to_data(config, NULL, NULL), file); + fputs(data, file); fclose(file); + + g_free(configfile); + g_free(data); + + g_key_file_free(config); } -static const gchar * +static gchar * hashfs_config_build_path (void) { - const gchar *configdir; - const gchar *configfile; + gchar *configdir, *configfile; + const gchar *userconfigdir; - configdir = g_build_filename(g_get_user_config_dir(), "hashfs", NULL); + userconfigdir = g_get_user_config_dir(); + configdir = g_build_filename(userconfigdir, "hashfs", NULL); configfile = g_build_filename(configdir, "hashfs.conf", NULL); if (g_file_test(configdir, G_FILE_TEST_EXISTS)) { if (!g_file_test(configdir, G_FILE_TEST_IS_DIR)) HASHFS_ERROR("Config directory already exists but is not a directory (%s)", configdir); } else { if (g_mkdir_with_parents(configdir, 0755) < 0) { HASHFS_ERROR("Unable to create config directory (%s)", configdir); } } + g_free(configdir); + return configfile; } diff --git a/src/hashfs/ed2k.c b/src/hashfs/ed2k.c index 6c8b358..0610b94 100644 --- a/src/hashfs/ed2k.c +++ b/src/hashfs/ed2k.c @@ -1,97 +1,97 @@ #define _FILE_OFFSET_BITS 64 #define _LARGEFILE_SOURCE 1 #define _LARGEFILE64_SOURCE 1 #define _LARGE_FILES 1 #define BLOCKSIZE (9500*1024) #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> #include <openssl/md4.h> #include <glib.h> #include <glib/gstdio.h> #include <glib/gprintf.h> #include "hashfs.h" static const gchar hexdigits[16] = "0123456789abcdef"; gint hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out) { gint blocks, fd, len; gint64 size, offset; guchar *hash_blocks, *hash_final; gchar *hash_str; MD4_CTX ctx; gpointer data; if ((fd = g_open(file->filename, O_RDONLY, "rb")) < 0) { HASHFS_DEBUG("Failed to open file (%s)", file->filename); return 0; } blocks = file->size / BLOCKSIZE; if ((file->size % BLOCKSIZE) > 0) blocks++; if (blocks < 1) return 0; hash_blocks = g_malloc(blocks * 16); - hash_final = g_malloc(16); hash_str = g_strnfill(33, 0); offset = 0; g_return_val_if_fail(hash_blocks != NULL, 0); - g_return_val_if_fail(hash_final != NULL, 0); g_return_val_if_fail(hash_str != NULL, 0); for (gint b = 0; b < blocks; b++) { len = (blocks - b) == 1 ? file->size % BLOCKSIZE : BLOCKSIZE; data = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, offset); g_return_val_if_fail(data != NULL, 0); MD4_Init(&ctx); MD4_Update(&ctx, data, len); MD4_Final(hash_blocks + (b * 16), &ctx); munmap(data, len); offset += len; } close(fd); /* If we have hashed more than one block, run MD4 on all the previous hashes */ if (blocks > 1) { + hash_final = g_malloc(16); + MD4_Init(&ctx); MD4_Update(&ctx, hash_blocks, 16 * blocks); MD4_Final(hash_final, &ctx); } else { hash_final = g_memdup(hash_blocks, 16); } /* Convert hash to hex string format */ for (gint i = 0; i < 16; i++) { hash_str[(i<<1)] = hexdigits[(((hash_final[i]) & 0xf0) >> 4)]; hash_str[(i<<1)+1] = hexdigits[(((hash_final[i]) & 0x0f))]; } g_free(hash_blocks); g_free(hash_final); *out = hash_str; return 1; } diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index 75058d9..f6ace86 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,205 +1,209 @@ #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { hashfs_file_t *file; HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); file = hashfs_file_new(path); hashfs_backend_file(backend, file); g_free(file); } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; HASHFS_LOG("Hashing dir: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { printf("%s.%s = %s\n", groups[i], keys[j], g_key_file_get_string(config, groups[i], keys[j], NULL)); } } } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; hashfs_config_load(); if (g_module_supported()) { - hashfs_backends_load(g_build_filename(g_get_user_config_dir(), "hashfs", "backends", NULL)); + gchar *backenddir = g_build_filename(g_get_user_config_dir(), "hashfs", "backends", NULL); + + hashfs_backends_load(backenddir); hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); + + g_free(backenddir); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); hashfs_config_save(); hashfs_backends_destroy(); return 0; } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index 621e9f8..675edc8 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,103 +1,111 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> +#include <gmodule.h> + struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_file_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_file_St hashfs_file_t; struct hashfs_file_St { gchar *filename; gint64 size; }; struct hashfs_backend_St { gpointer data; + GModule *module; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; gchar * hashfs_current_time (void); gchar * hashfs_basename (gchar *name); GKeyFile * hashfs_config_keyfile (void); void hashfs_config_load (void); void hashfs_config_save (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); hashfs_file_t * hashfs_file_new (gchar *filename); gint hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out); gint hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, gchar *value); hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); -void hashfs_backends_load (const gchar *path); +void hashfs_backends_load (gchar *path); void hashfs_backends_destroy (void); hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ - printf("%s LOG ", hashfs_current_time()); \ + gchar *log_time = hashfs_current_time(); \ + printf("%s LOG ", log_time); \ printf(fmt"\n", ## __VA_ARGS__); \ + g_free(log_time); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ - FILE *fd; \ - fd = g_fopen(g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL), "at"); \ - fprintf(fd, "%s DEBUG %s:%d: ", hashfs_current_time(), __FILE__, __LINE__); \ + gchar *log_path = g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL); \ + gchar *log_time = hashfs_current_time(); \ + FILE *fd = g_fopen(log_path, "at"); \ + fprintf(fd, "%s DEBUG %s:%d: ", log_time, __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ + g_free(log_path); \ + g_free(log_time); \ } #else #define HASHFS_DEBUG(...) #endif #endif diff --git a/src/hashfs/util.c b/src/hashfs/util.c index 070532d..c39c9d9 100644 --- a/src/hashfs/util.c +++ b/src/hashfs/util.c @@ -1,35 +1,35 @@ #include <sys/time.h> #include <string.h> #include <time.h> #include "hashfs.h" gchar * hashfs_basename (char *name) { const char *base; for (base = name; *name; name++) { if (*name == '/') { base = name + 1; } } return (char *) base; } gchar * hashfs_current_time (void) { char buf[256]; time_t tv; struct tm st; tv = time(NULL); localtime_r(&tv, &st); strftime(buf, sizeof(buf), "%H:%M:%S", &st); - return strdup(buf); + return g_strdup(buf); } diff --git a/src/lib/libanidb/tests/test01.c b/src/lib/libanidb/tests/test01.c index 284d33a..1429350 100644 --- a/src/lib/libanidb/tests/test01.c +++ b/src/lib/libanidb/tests/test01.c @@ -1,167 +1,169 @@ #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <anidb.h> static void dump_result (anidb_result_t *result) { int n; char *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: printf("<result %p null>\n", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); printf("<result %p (string) \"%s\">\n", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); printf("<result %p (int) \"%d\">\n", result, n); break; case ANIDB_RESULT_DICT: printf("<result %p (dict)\n", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { printf(" %s = \"%s\"", dict->key, dict->value); if (anidb_dict_next(dict)) printf(",\n"); } printf(">\n"); break; } } static void dump_anime (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_anime_name(session, name); if (anidb_result_get_code(res) == ANIDB_ANIME) { dump_result(res); } anidb_result_unref(res); } static void dump_animedesc (anidb_session_t *session, int id, int part) { anidb_result_t *res; res = anidb_session_animedesc(session, id, part); if (anidb_result_get_code(res) == ANIDB_ANIME_DESCRIPTION) { dump_result(res); } anidb_result_unref(res); } static void dump_episode (anidb_session_t *session, int id) { anidb_result_t *res; res = anidb_session_episode_id(session, id); if (anidb_result_get_code(res) == ANIDB_EPISODE) { dump_result(res); } anidb_result_unref(res); } static void dump_file (anidb_session_t *session, int id) { anidb_result_t *res; // res = anidb_session_file_ed2k(session, 44255118, "90033a52db54437dc4a6041348422d4b"); res = anidb_session_file_id(session, id); if (anidb_result_get_code(res) == ANIDB_FILE) { dump_result(res); } anidb_result_unref(res); } static void dump_group (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_group_name(session, name); if (anidb_result_get_code(res) == ANIDB_GROUP) { dump_result(res); } anidb_result_unref(res); } int main (int argc, char *argv[]) { anidb_session_t *session; anidb_result_t *res; char *key; - if (argc < 3) { - printf("Usage: %s <username> <password>\n", argv[0]); + if (argc < 4) { + printf("Usage: %s <username> <password> <port>\n", argv[0]); exit(0); } - session = anidb_session_new("anidbfs", "1", 9998); + session = anidb_session_new("anidbfs", "1", atoi(argv[3])); res = anidb_session_authenticate(session, argv[1], argv[2]); dump_result(res); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); } dump_anime(session, "Neon Genesis Evangelion"); dump_group(session, "Chrippa Crapsubs"); dump_animedesc(session, 23, 0); dump_episode(session, 21346); dump_file(session, 43698); - dump_result(anidb_session_logout(session)); + anidb_result_t *logout = anidb_session_logout(session); + dump_result(logout); + anidb_result_unref(logout); } anidb_result_unref(res); anidb_session_unref(session); return 0; }
chrippa/hashfs
28afc831090b3dc6b8218d33de5ff02f358880b6
Only throttle data retrieving commands.
diff --git a/src/lib/libanidb/anidb.c b/src/lib/libanidb/anidb.c index fc90f8c..bf917a7 100644 --- a/src/lib/libanidb/anidb.c +++ b/src/lib/libanidb/anidb.c @@ -1,739 +1,757 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include <time.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static int get_ms (void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } static void throttle_session (anidb_session_t *session) { int elapsed, needtosleep; elapsed = get_ms() - session->time; needtosleep = ANIDB_THROTTLE_MS - elapsed; if (needtosleep > 0) { usleep(needtosleep * 1000); } session->time = get_ms(); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; - printf("send: '%s'\n", msg); +// printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; - printf("recv: '%s'\n", out); +// printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version, int localport) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } if (localport > 0) { local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(localport); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:%d", localport); } } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; strncpy(session->clientname, name, sizeof(session->clientname)); strncpy(session->clientversion, version, sizeof(session->clientversion)); anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { strncpy(session->key, key, sizeof(session->key)); } int anidb_session_is_logged_in (anidb_session_t *session) { if (session->key[0]) return 1; return 0; } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); - throttle_session(session); - sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; + throttle_session(session); + res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); + throttle_session(session); + res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); + throttle_session(session); + res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); + throttle_session(session); + res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); + throttle_session(session); + res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); + throttle_session(session); + res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); + throttle_session(session); + res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k) { anidb_result_t *res; char siz[50]; sprintf(siz, "%d", size); + throttle_session(session); + res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); + throttle_session(session); + res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name) { anidb_result_t *res; + throttle_session(session); + res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { strncpy(dict->key, key, sizeof(dict->key)); strncpy(dict->value, value, sizeof(dict->value)); } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, char *string) { result->type = ANIDB_RESULT_STRING; strncpy(result->value.string, string, sizeof(result->value.string)); } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, char *key, char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } int anidb_result_dict_get (anidb_result_t *result, char *key, char **out) { anidb_dict_t *dict; if (result->type != ANIDB_RESULT_DICT) return 0; for (dict = result->value.dict; dict; dict = dict->next) { if (!strcmp(dict->key, key)) { return anidb_dict_get(dict, out); } } return 0; } anidb_dict_t * anidb_result_get_dict (anidb_result_t *result) { if (result->type != ANIDB_RESULT_DICT) return NULL; return result->value.dict; }
chrippa/hashfs
0fb32993106e872c491e55bd91b8d7308f6dc706
Refactor AniDB result parsing.
diff --git a/src/lib/libanidb/anidb.c b/src/lib/libanidb/anidb.c index 05eeac3..fc90f8c 100644 --- a/src/lib/libanidb/anidb.c +++ b/src/lib/libanidb/anidb.c @@ -1,739 +1,739 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include <time.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static int get_ms (void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } static void throttle_session (anidb_session_t *session) { int elapsed, needtosleep; elapsed = get_ms() - session->time; needtosleep = ANIDB_THROTTLE_MS - elapsed; if (needtosleep > 0) { usleep(needtosleep * 1000); } session->time = get_ms(); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; -// printf("send: '%s'\n", msg); + printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; -// printf("recv: '%s'\n", out); + printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version, int localport) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } if (localport > 0) { local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(localport); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:%d", localport); } } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; strncpy(session->clientname, name, sizeof(session->clientname)); strncpy(session->clientversion, version, sizeof(session->clientversion)); anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { strncpy(session->key, key, sizeof(session->key)); } int anidb_session_is_logged_in (anidb_session_t *session) { if (session->key[0]) return 1; return 0; } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); throttle_session(session); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k) { anidb_result_t *res; char siz[50]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { - dict->key = key; - dict->value = value; + strncpy(dict->key, key, sizeof(dict->key)); + strncpy(dict->value, value, sizeof(dict->value)); } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, char *string) { result->type = ANIDB_RESULT_STRING; - result->value.string = string; + strncpy(result->value.string, string, sizeof(result->value.string)); } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, char *key, char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } int anidb_result_dict_get (anidb_result_t *result, char *key, char **out) { anidb_dict_t *dict; if (result->type != ANIDB_RESULT_DICT) return 0; for (dict = result->value.dict; dict; dict = dict->next) { if (!strcmp(dict->key, key)) { return anidb_dict_get(dict, out); } } return 0; } anidb_dict_t * anidb_result_get_dict (anidb_result_t *result) { if (result->type != ANIDB_RESULT_DICT) return NULL; return result->value.dict; } diff --git a/src/lib/libanidb/anidb.h b/src/lib/libanidb/anidb.h index 6e3ef20..468a828 100644 --- a/src/lib/libanidb/anidb.h +++ b/src/lib/libanidb/anidb.h @@ -1,313 +1,312 @@ #ifndef _LIBANIDB_H #define _LIBANIDB_H #include <sys/time.h> enum anidb_result_type { ANIDB_RESULT_NULL, ANIDB_RESULT_NUMBER, ANIDB_RESULT_STRING, ANIDB_RESULT_DICT }; struct anidb_session_St { int socket; int time; char clientname[256]; char clientversion[256]; char key[10]; - int refcount; }; struct anidb_dict_St { - char *key; - char *value; + char key[50]; + char value[512]; struct anidb_dict_St *next; int refcount; }; struct anidb_result_St { struct anidb_error_St *error; int code; enum anidb_result_type type; union { int number; - char *string; + char string[256]; struct anidb_dict_St *dict; } value; int refcount; }; struct anidb_result_handler_St { int code; void (*func)(struct anidb_result_St *, char *); }; /* Types */ typedef enum anidb_result_type anidb_result_type_t; typedef struct anidb_session_St anidb_session_t; typedef struct anidb_dict_St anidb_dict_t; typedef struct anidb_result_St anidb_result_t; typedef struct anidb_result_handler_St anidb_result_handler_t; typedef struct anidb_error_St anidb_error_t; /* Session */ anidb_session_t * anidb_session_new (char *name, char *version, int localport); /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password); /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session); /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name); anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id); /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int ep); /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep); anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep); /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k); /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name); /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id); /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session); /* VOTE */ /* RANDOM */ /* MYLISTEXPORT */ /* PING */ anidb_result_t * anidb_session_ping (anidb_session_t *session); /* VERSION */ anidb_result_t * anidb_session_uptime (anidb_session_t *session); /* UPTIME */ anidb_result_t * anidb_session_version (anidb_session_t *session); /* ENCODING */ /* SENDMSG */ /* USER */ void anidb_session_set_key (anidb_session_t *session, char *key); int anidb_session_is_logged_in (anidb_session_t *session); void anidb_session_ref (anidb_session_t *session); void anidb_session_unref (anidb_session_t *session); /* Dict */ anidb_dict_t * anidb_dict_new (void); anidb_dict_t * anidb_dict_next (anidb_dict_t *dict); void anidb_dict_ref (anidb_dict_t *dict); void anidb_dict_unref (anidb_dict_t *dict); void anidb_dict_set (anidb_dict_t *dict, char *key, char *value); int anidb_dict_get (anidb_dict_t *dict, char **out); /* Result */ anidb_result_t * anidb_result_new (int code); void anidb_result_ref (anidb_result_t *result); void anidb_result_unref (anidb_result_t *result); void anidb_result_set_str (anidb_result_t *result, char *string); void anidb_result_set_int (anidb_result_t *result, int number); void anidb_result_dict_set (anidb_result_t *result, char *key, char *value); anidb_result_type_t anidb_result_get_type (anidb_result_t *result); int anidb_result_get_code (anidb_result_t *result); int anidb_result_get_str (anidb_result_t *result, char **out); int anidb_result_get_int (anidb_result_t *result, int *out); int anidb_result_dict_get (anidb_result_t *result, char *key, char **out); anidb_dict_t * anidb_result_get_dict (anidb_result_t *result); #define ANIDB_SERVER_HOST "api.anidb.net" #define ANIDB_SERVER_PORT 9000 #define ANIDB_PROTO_VERSION "3" #define ANIDB_THROTTLE_MS 2000 /* Positive responses 2XX */ #define ANIDB_LOGIN_ACCEPTED 200 #define ANIDB_LOGIN_ACCEPTED_NEW_VER 201 #define ANIDB_LOGGED_OUT 203 #define ANIDB_RESOURCE 205 #define ANIDB_STATS 206 #define ANIDB_TOP 207 #define ANIDB_UPTIME 208 #define ANIDB_ENCRYPTION_ENABLED 209 #define ANIDB_MYLIST_ENTRY_ADDED 210 #define ANIDB_MYLIST_ENTRY_DELETED 211 #define ANIDB_ADDED_FILE 214 #define ANIDB_ADDED_STREAM 215 #define ANIDB_ENCODING_CHANGED 219 #define ANIDB_FILE 220 #define ANIDB_MYLIST 221 #define ANIDB_MYLIST_STATS 222 #define ANIDB_ANIME 230 #define ANIDB_ANIME_BEST_MATCH 231 #define ANIDB_RANDOMANIME 232 #define ANIDB_ANIME_DESCRIPTION 233 #define ANIDB_EPISODE 240 #define ANIDB_PRODUCER 245 #define ANIDB_GROUP 250 #define ANIDB_BUDDY_LIST 253 #define ANIDB_BUDDY_STATE 254 #define ANIDB_BUDDY_ADDED 255 #define ANIDB_BUDDY_DELETED 256 #define ANIDB_BUDDY_ACCEPTED 257 #define ANIDB_BUDDY_DENIED 258 #define ANIDB_VOTED 260 #define ANIDB_VOTE_FOUND 261 #define ANIDB_VOTE_UPDATED 262 #define ANIDB_VOTE_REVOKED 263 #define ANIDB_NOTIFICATION_ENABLED 270 #define ANIDB_NOTIFICATION_NOTIFY 271 #define ANIDB_NOTIFICATION_MESSAGE 272 #define ANIDB_NOTIFICATION_BUDDY 273 #define ANIDB_NOTIFICATION_SHUTDOWN 274 #define ANIDB_PUSHACK_CONFIRMED 280 #define ANIDB_NOTIFYACK_SUCCESSFUL_M 281 #define ANIDB_NOTIFYACK_SUCCESSFUL_N 282 #define ANIDB_NOTIFICATION 290 #define ANIDB_NOTIFYLIST 291 #define ANIDB_NOTIFYGET_MESSAGE 292 #define ANIDB_NOTIFYGET_NOTIFY 293 #define ANIDB_SENDMSG_SUCCESSFUL 294 #define ANIDB_USER 295 /* Affirmative/Negative responses 3XX */ #define ANIDB_PONG 300 #define ANIDB_AUTHPONG 301 #define ANIDB_NO_SUCH_RESOURCE 305 #define ANIDB_API_PASSWORD_NOT_DEFINED 309 #define ANIDB_FILE_ALREADY_IN_MYLIST 310 #define ANIDB_MYLIST_ENTRY_EDITED 311 #define ANIDB_MULTIPLE_MYLIST_ENTRIES 312 #define ANIDB_SIZE_HASH_EXISTS 314 #define ANIDB_INVALID_DATA 315 #define ANIDB_STREAMNOID_USED 316 #define ANIDB_NO_SUCH_FILE 320 #define ANIDB_NO_SUCH_ENTRY 321 #define ANIDB_MULTIPLE_FILES_FOUND 322 #define ANIDB_NO_SUCH_ANIME 330 #define ANIDB_NO_SUCH_ANIME_DESCRIPTION 333 #define ANIDB_NO_SUCH_EPISODE 340 #define ANIDB_NO_SUCH_PRODUCER 345 #define ANIDB_NO_SUCH_GROUP 350 #define ANIDB_BUDDY_ALREADY_ADDED 355 #define ANIDB_NO_SUCH_BUDDY 356 #define ANIDB_BUDDY_ALREADY_ACCEPTED 357 #define ANIDB_BUDDY_ALREADY_DENIED 358 #define ANIDB_NO_SUCH_VOTE 360 #define ANIDB_INVALID_VOTE_TYPE 361 #define ANIDB_INVALID_VOTE_VALUE 362 #define ANIDB_PERMVOTE_NOT_ALLOWED 363 #define ANIDB_ALREADY_PERMVOTED 364 #define ANIDB_NOTIFICATION_DISABLED 370 #define ANIDB_NO_SUCH_PACKET_PENDING 380 #define ANIDB_NO_SUCH_ENTRY_M 381 #define ANIDB_NO_SUCH_ENTRY_N 382 #define ANIDB_NO_SUCH_MESSAGE 392 #define ANIDB_NO_SUCH_NOTIFY 393 #define ANIDB_NO_SUCH_USER 394 /* Negative responses 4XX */ #define ANIDB_NOT_LOGGED_IN 403 #define ANIDB_NO_SUCH_MYLIST_FILE 410 #define ANIDB_NO_SUCH_MYLIST_ENTRY 411 /* Client side failure 5XX */ #define ANIDB_LOGIN_FAILED 500 #define ANIDB_LOGIN_FIRST 501 #define ANIDB_ACCESS_DENIED 502 #define ANIDB_CLIENT_VERSION_OUTDATED 503 #define ANIDB_CLIENT_BANNED 504 #define ANIDB_ILLEGAL_INPUT_OR_ACCESS_DENIED 505 #define ANIDB_INVALID_SESSION 506 #define ANIDB_NO_SUCH_ENCRYPTION_TYPE 509 #define ANIDB_ENCODING_NOT_SUPPORTED 519 #define ANIDB_BANNED 555 #define ANIDB_UNKNOWN_COMMAND 598 /* Server side failure 6XX */ #define ANIDB_INTERNAL_SERVER_ERROR 600 #define ANIDB_ANIDB_OUT_OF_SERVICE 601 #define ANIDB_SERVER_BUSY 602 #define ANIDB_API_VIOLATION 666 #endif diff --git a/src/lib/libanidb/handlers.c b/src/lib/libanidb/handlers.c index 273ff53..d779085 100644 --- a/src/lib/libanidb/handlers.c +++ b/src/lib/libanidb/handlers.c @@ -1,213 +1,157 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "util.h" #include "anidb.h" -static char * -get_part(char *src, int delim, int idx) -{ - int i = 0, j = 0; - char buf[1024]; - while (*src != '\0') { - if (i == idx && *src != delim) { - buf[j] = *src; - j++; - } +static void get_part (char *buf, char *src, char *delim, int idx); - if (*src == delim) - i++; +#define PARSE_KEYS(result, src, keys) { \ + char buf[1024]; \ + for (int i = 0; i < LENGTH((keys)); i++) { \ + get_part((buf), (src), "|", i); \ + anidb_result_dict_set((result), (keys[i]), (buf)); \ + } \ +} - src++; - } +static void +get_part (char *buf, char *src, char *delim, int idx) +{ + char *ptr; + int len; - buf[j++] = '\0'; + ptr = src; - return strdup(buf); -} + for (int n = 0; n <= idx; n++) { + len = strstr(ptr, delim) - ptr; + + if (len < 0 || len > strlen(ptr)) + len = strlen(ptr); -#define DICT_PART_ADD(result, data, num, name) \ - anidb_result_dict_set((result), (name), get_part((data), '|', (num))) + strncpy(buf, ptr, len); + buf[len] = '\0'; + ptr += len + strlen(delim); + } +} static void handler_auth_accepted (anidb_result_t *result, char *data) { char buf[10]; sscanf(data, "200 %s", &buf); anidb_result_set_str(result, buf); } static void handler_auth_logout (anidb_result_t *result, char *data) { /* pass */ } static void handler_anime (anidb_result_t *result, char *data) { - char *anime; - - anime = data + 10; - - DICT_PART_ADD(result, anime, 0, "aid"); - DICT_PART_ADD(result, anime, 1, "eps"); - DICT_PART_ADD(result, anime, 2, "ep_count"); - DICT_PART_ADD(result, anime, 3, "special_cnt"); - DICT_PART_ADD(result, anime, 4, "rating"); - DICT_PART_ADD(result, anime, 5, "votes"); - DICT_PART_ADD(result, anime, 6, "tmprating"); - DICT_PART_ADD(result, anime, 7, "tmpvotes"); - DICT_PART_ADD(result, anime, 8, "rating_average"); - DICT_PART_ADD(result, anime, 9, "reviews"); - DICT_PART_ADD(result, anime, 10, "year"); - DICT_PART_ADD(result, anime, 11, "type"); - DICT_PART_ADD(result, anime, 12, "romaji"); - DICT_PART_ADD(result, anime, 13, "kanji"); - DICT_PART_ADD(result, anime, 14, "english"); - DICT_PART_ADD(result, anime, 15, "other"); - DICT_PART_ADD(result, anime, 16, "short_names"); - DICT_PART_ADD(result, anime, 17, "synonyms"); - DICT_PART_ADD(result, anime, 18, "category_list"); + char *keys[] = { "aid", "eps", "ep_count", "special_cnt", + "rating", "votes", "tmprating", "tmpvotes", + "rating_avg", "reviews", "year", "type", + "romaji", "kanji", "english", "other", + "short_names", "synonyms", "category_list" }; + + PARSE_KEYS(result, data + 10, keys); } static void handler_animedesc (anidb_result_t *result, char *data) { - char *desc; - - desc = data + 14; + char *keys[] = { "part", "max_parts", "description" }; - DICT_PART_ADD(result, desc, 0, "part"); - DICT_PART_ADD(result, desc, 1, "max_parts"); - DICT_PART_ADD(result, desc, 2, "description"); + PARSE_KEYS(result, data + 14, keys); } static void handler_episode (anidb_result_t *result, char *data) { - char *episode; - - episode = data + 12; - - DICT_PART_ADD(result, episode, 0, "eid"); - DICT_PART_ADD(result, episode, 1, "aid"); - DICT_PART_ADD(result, episode, 2, "length"); - DICT_PART_ADD(result, episode, 3, "rating"); - DICT_PART_ADD(result, episode, 4, "votes"); - DICT_PART_ADD(result, episode, 5, "epno"); - DICT_PART_ADD(result, episode, 6, "eng"); - DICT_PART_ADD(result, episode, 7, "romaji"); - DICT_PART_ADD(result, episode, 8, "kanji"); - DICT_PART_ADD(result, episode, 9, "aired"); + char *keys[] = { "eid", "aid", "length", "rating", + "votes", "epno", "eng", "romaji", + "kanji", "aired" }; + + PARSE_KEYS(result, data + 12, keys); } static void handler_file (anidb_result_t *result, char *data) { - char *file; - - file = data + 9; - - DICT_PART_ADD(result, file, 0, "fid"); - DICT_PART_ADD(result, file, 1, "aid"); - DICT_PART_ADD(result, file, 2, "eid"); - DICT_PART_ADD(result, file, 3, "gid"); - DICT_PART_ADD(result, file, 4, "lid"); - DICT_PART_ADD(result, file, 5, "state"); - DICT_PART_ADD(result, file, 6, "size"); - DICT_PART_ADD(result, file, 7, "ed2k"); - DICT_PART_ADD(result, file, 8, "md5"); - DICT_PART_ADD(result, file, 9, "sha1"); - DICT_PART_ADD(result, file, 10, "crc32"); - DICT_PART_ADD(result, file, 11, "dub"); - DICT_PART_ADD(result, file, 12, "sub"); - DICT_PART_ADD(result, file, 13, "quality"); - DICT_PART_ADD(result, file, 14, "source"); - DICT_PART_ADD(result, file, 15, "audio"); - DICT_PART_ADD(result, file, 16, "video"); - DICT_PART_ADD(result, file, 17, "resolution"); - DICT_PART_ADD(result, file, 18, "ext"); - DICT_PART_ADD(result, file, 19, "duration"); - - DICT_PART_ADD(result, file, 20, "group_name"); - DICT_PART_ADD(result, file, 21, "group_short"); - - DICT_PART_ADD(result, file, 22, "ep_number"); - DICT_PART_ADD(result, file, 23, "ep_eng"); - DICT_PART_ADD(result, file, 24, "ep_romaji"); - DICT_PART_ADD(result, file, 25, "ep_kanji"); - - DICT_PART_ADD(result, file, 26, "anime_totalep"); - DICT_PART_ADD(result, file, 27, "anime_lastep"); - DICT_PART_ADD(result, file, 28, "anime_year"); - DICT_PART_ADD(result, file, 29, "anime_type"); - DICT_PART_ADD(result, file, 30, "anime_romaji"); - DICT_PART_ADD(result, file, 31, "anime_kanji"); - DICT_PART_ADD(result, file, 32, "anime_eng"); - DICT_PART_ADD(result, file, 33, "anime_categories"); + char *keys[] = { "fid", "aid", "eid", "gid", + "lid", "state", "size", "ed2k", + "md5", "sha1", "crc32", "dub", + "sub", "quality", "source", + "audio", "video", "resolution", + "ext", "duration", + + "group_name", "group_short", + + "ep_number", "ep_eng", "ep_romaji", + "ep_kanji", + + "anime_totalep", "anime_lastep", + "anime_year", "anime_type", + "anime_romaji", "anime_kanji", + "anime_eng", "anime_categories" }; + + PARSE_KEYS(result, data + 9, keys); } static void handler_group (anidb_result_t *result, char *data) { - char *group; - - group = data + 10; - - DICT_PART_ADD(result, group, 0, "gid"); - DICT_PART_ADD(result, group, 1, "rating"); - DICT_PART_ADD(result, group, 2, "votes"); - DICT_PART_ADD(result, group, 3, "acount"); - DICT_PART_ADD(result, group, 4, "fcount"); - DICT_PART_ADD(result, group, 5, "name"); - DICT_PART_ADD(result, group, 6, "short"); - DICT_PART_ADD(result, group, 7, "irc_channel"); - DICT_PART_ADD(result, group, 8, "irc_server"); - DICT_PART_ADD(result, group, 9, "url"); + char *keys[] = { "gid", "rating", "votes", "acount", + "fcount", "name", "short", + "irc_channel", "irc_server", "url" }; + + PARSE_KEYS(result, data + 10, keys); } anidb_result_handler_t anidb_handlers[] = { /* AUTH */ { ANIDB_LOGIN_ACCEPTED, handler_auth_accepted }, { ANIDB_LOGGED_OUT, handler_auth_logout }, /* ANIME */ { ANIDB_ANIME, handler_anime }, /* ANIMEDESC */ { ANIDB_ANIME_DESCRIPTION, handler_animedesc }, /* EPISODE */ { ANIDB_EPISODE, handler_episode }, /* FILE */ { ANIDB_FILE, handler_file }, /* GROUP */ { ANIDB_GROUP, handler_group }, /* GROUPSTATUS */ /* MYLIST */ /* MYLISTADD */ /* MYLISTDEL */ /* MYLISTSTATS */ /* VOTE */ /* RANDOM */ /* PING */ /* UPTIME */ /* ENCODING */ /* SENDMSG */ /* USER */ }; diff --git a/src/hashfs/tests/test01.c b/src/lib/libanidb/tests/test01.c similarity index 94% rename from src/hashfs/tests/test01.c rename to src/lib/libanidb/tests/test01.c index f1e528b..284d33a 100644 --- a/src/hashfs/tests/test01.c +++ b/src/lib/libanidb/tests/test01.c @@ -1,167 +1,167 @@ #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <anidb.h> static void dump_result (anidb_result_t *result) { int n; char *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: printf("<result %p null>\n", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); printf("<result %p (string) \"%s\">\n", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); printf("<result %p (int) \"%d\">\n", result, n); break; case ANIDB_RESULT_DICT: printf("<result %p (dict)\n", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { printf(" %s = \"%s\"", dict->key, dict->value); if (anidb_dict_next(dict)) printf(",\n"); } printf(">\n"); break; } } static void dump_anime (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_anime_name(session, name); if (anidb_result_get_code(res) == ANIDB_ANIME) { dump_result(res); } anidb_result_unref(res); } static void dump_animedesc (anidb_session_t *session, int id, int part) { anidb_result_t *res; res = anidb_session_animedesc(session, id, part); if (anidb_result_get_code(res) == ANIDB_ANIME_DESCRIPTION) { dump_result(res); } anidb_result_unref(res); } static void dump_episode (anidb_session_t *session, int id) { anidb_result_t *res; res = anidb_session_episode_id(session, id); if (anidb_result_get_code(res) == ANIDB_EPISODE) { dump_result(res); } anidb_result_unref(res); } static void dump_file (anidb_session_t *session, int id) { anidb_result_t *res; - res = anidb_session_file_ed2k(session, 44255118, "90033a52db54437dc4a6041348422d4b"); -// res = anidb_session_file_id(session, id); +// res = anidb_session_file_ed2k(session, 44255118, "90033a52db54437dc4a6041348422d4b"); + res = anidb_session_file_id(session, id); if (anidb_result_get_code(res) == ANIDB_FILE) { dump_result(res); } anidb_result_unref(res); } static void dump_group (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_group_name(session, name); if (anidb_result_get_code(res) == ANIDB_GROUP) { dump_result(res); } anidb_result_unref(res); } int main (int argc, char *argv[]) { anidb_session_t *session; anidb_result_t *res; char *key; if (argc < 3) { printf("Usage: %s <username> <password>\n", argv[0]); exit(0); } - session = anidb_session_new("anidbfs", "1"); + session = anidb_session_new("anidbfs", "1", 9998); res = anidb_session_authenticate(session, argv[1], argv[2]); dump_result(res); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); } dump_anime(session, "Neon Genesis Evangelion"); dump_group(session, "Chrippa Crapsubs"); dump_animedesc(session, 23, 0); dump_episode(session, 21346); dump_file(session, 43698); dump_result(anidb_session_logout(session)); } anidb_result_unref(res); anidb_session_unref(session); return 0; } diff --git a/src/lib/libanidb/tests/wscript b/src/lib/libanidb/tests/wscript new file mode 100644 index 0000000..9e5b2d8 --- /dev/null +++ b/src/lib/libanidb/tests/wscript @@ -0,0 +1,27 @@ +# vim: set fileencoding=utf-8 filetype=python : + +tests = ['test01'] + +def set_options(opt): + pass + +def configure(conf): + pass + +def build(bld): + import Options + + defines = [] + + if Options.options.debug: + defines += ['DEBUG'] + + for test in tests: + obj = bld.new_task_gen( + features = 'cc cprogram', + source = test + '.c', + target = 'anidb_' + test, + uselib_local = 'anidb', + ccflags = ['-std=gnu99', '-g'], + defines = defines + ) diff --git a/wscript b/wscript index aed32c0..a6ce7e4 100644 --- a/wscript +++ b/wscript @@ -1,36 +1,36 @@ # vim: set fileencoding=utf-8 filetype=python : from logging import fatal, info import os srcdir = '.' blddir = '_build_' bckenddir = 'src/backends' def is_backend(x): return os.path.exists(os.path.join(bckenddir, x, 'wscript')) hashfs = ['src/hashfs'] -libs = ['src/lib/libanidb'] +libs = ['src/lib/libanidb', 'src/lib/libanidb/tests'] backends = [os.path.join(bckenddir, p) for p in os.listdir(bckenddir) if is_backend(p)] subdirs = hashfs + libs + backends def set_options(opt): opt.add_option('--debug', action = 'store_true', default = True, help = 'Enable debug') for dir in subdirs: opt.sub_options(dir) def configure(conf): import Options conf.check_tool('gcc') for dir in subdirs: conf.sub_config(dir) def build(bld): bld.add_subdirs(subdirs)
chrippa/hashfs
7f1b3314e515a9976d03a72b08d0e76ebe2b9cc6
Throttle AniDB commands and fix memory leak.
diff --git a/README b/README index b57d29e..04a4818 100644 --- a/README +++ b/README @@ -1,5 +1,5 @@ hashfs is meant to create virtual filesystems based on metadata. Metadata is primarily gathered from hashing files and looking up -metadata in different databases. +metadata in different online databases, such as AniDB and hashdb.com. hashfs is not usable at this time. diff --git a/src/lib/libanidb/anidb.c b/src/lib/libanidb/anidb.c index db23fab..05eeac3 100644 --- a/src/lib/libanidb/anidb.c +++ b/src/lib/libanidb/anidb.c @@ -1,689 +1,714 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> +#include <time.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } + +static int +get_ms (void) +{ + struct timespec ts; + + clock_gettime(CLOCK_MONOTONIC, &ts); + + return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + +static void +throttle_session (anidb_session_t *session) +{ + int elapsed, needtosleep; + + elapsed = get_ms() - session->time; + needtosleep = ANIDB_THROTTLE_MS - elapsed; + + if (needtosleep > 0) { + usleep(needtosleep * 1000); + } + + session->time = get_ms(); +} + static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; // printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; // printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version, int localport) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } if (localport > 0) { local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(localport); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:%d", localport); } } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; - session->clientname = name; - session->clientversion = version; - session->key = NULL; + strncpy(session->clientname, name, sizeof(session->clientname)); + strncpy(session->clientversion, version, sizeof(session->clientversion)); anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); - if (session->key) - free(session->key); - free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { - session->key = (char *) strdup(key); + strncpy(session->key, key, sizeof(session->key)); } int anidb_session_is_logged_in (anidb_session_t *session) { - if (session->key) + if (session->key[0]) return 1; return 0; } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); + throttle_session(session); + sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k) { anidb_result_t *res; char siz[50]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { dict->key = key; dict->value = value; } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, char *string) { result->type = ANIDB_RESULT_STRING; result->value.string = string; } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, char *key, char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } diff --git a/src/lib/libanidb/anidb.h b/src/lib/libanidb/anidb.h index b705d69..6e3ef20 100644 --- a/src/lib/libanidb/anidb.h +++ b/src/lib/libanidb/anidb.h @@ -1,310 +1,313 @@ #ifndef _LIBANIDB_H #define _LIBANIDB_H #include <sys/time.h> enum anidb_result_type { ANIDB_RESULT_NULL, ANIDB_RESULT_NUMBER, ANIDB_RESULT_STRING, ANIDB_RESULT_DICT }; struct anidb_session_St { int socket; - char *clientname; - char *clientversion; - char *key; + int time; + char clientname[256]; + char clientversion[256]; + char key[10]; + int refcount; }; struct anidb_dict_St { char *key; char *value; struct anidb_dict_St *next; int refcount; }; struct anidb_result_St { struct anidb_error_St *error; int code; enum anidb_result_type type; union { int number; char *string; struct anidb_dict_St *dict; } value; int refcount; }; struct anidb_result_handler_St { int code; void (*func)(struct anidb_result_St *, char *); }; /* Types */ typedef enum anidb_result_type anidb_result_type_t; typedef struct anidb_session_St anidb_session_t; typedef struct anidb_dict_St anidb_dict_t; typedef struct anidb_result_St anidb_result_t; typedef struct anidb_result_handler_St anidb_result_handler_t; typedef struct anidb_error_St anidb_error_t; /* Session */ anidb_session_t * anidb_session_new (char *name, char *version, int localport); /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password); /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session); /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name); anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id); /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int ep); /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep); anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep); /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k); /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name); /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id); /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session); /* VOTE */ /* RANDOM */ /* MYLISTEXPORT */ /* PING */ anidb_result_t * anidb_session_ping (anidb_session_t *session); /* VERSION */ anidb_result_t * anidb_session_uptime (anidb_session_t *session); /* UPTIME */ anidb_result_t * anidb_session_version (anidb_session_t *session); /* ENCODING */ /* SENDMSG */ /* USER */ void anidb_session_set_key (anidb_session_t *session, char *key); int anidb_session_is_logged_in (anidb_session_t *session); void anidb_session_ref (anidb_session_t *session); void anidb_session_unref (anidb_session_t *session); /* Dict */ anidb_dict_t * anidb_dict_new (void); anidb_dict_t * anidb_dict_next (anidb_dict_t *dict); void anidb_dict_ref (anidb_dict_t *dict); void anidb_dict_unref (anidb_dict_t *dict); void anidb_dict_set (anidb_dict_t *dict, char *key, char *value); int anidb_dict_get (anidb_dict_t *dict, char **out); /* Result */ anidb_result_t * anidb_result_new (int code); void anidb_result_ref (anidb_result_t *result); void anidb_result_unref (anidb_result_t *result); void anidb_result_set_str (anidb_result_t *result, char *string); void anidb_result_set_int (anidb_result_t *result, int number); void anidb_result_dict_set (anidb_result_t *result, char *key, char *value); anidb_result_type_t anidb_result_get_type (anidb_result_t *result); int anidb_result_get_code (anidb_result_t *result); int anidb_result_get_str (anidb_result_t *result, char **out); int anidb_result_get_int (anidb_result_t *result, int *out); int anidb_result_dict_get (anidb_result_t *result, char *key, char **out); anidb_dict_t * anidb_result_get_dict (anidb_result_t *result); #define ANIDB_SERVER_HOST "api.anidb.net" #define ANIDB_SERVER_PORT 9000 #define ANIDB_PROTO_VERSION "3" +#define ANIDB_THROTTLE_MS 2000 /* Positive responses 2XX */ #define ANIDB_LOGIN_ACCEPTED 200 #define ANIDB_LOGIN_ACCEPTED_NEW_VER 201 #define ANIDB_LOGGED_OUT 203 #define ANIDB_RESOURCE 205 #define ANIDB_STATS 206 #define ANIDB_TOP 207 #define ANIDB_UPTIME 208 #define ANIDB_ENCRYPTION_ENABLED 209 #define ANIDB_MYLIST_ENTRY_ADDED 210 #define ANIDB_MYLIST_ENTRY_DELETED 211 #define ANIDB_ADDED_FILE 214 #define ANIDB_ADDED_STREAM 215 #define ANIDB_ENCODING_CHANGED 219 #define ANIDB_FILE 220 #define ANIDB_MYLIST 221 #define ANIDB_MYLIST_STATS 222 #define ANIDB_ANIME 230 #define ANIDB_ANIME_BEST_MATCH 231 #define ANIDB_RANDOMANIME 232 #define ANIDB_ANIME_DESCRIPTION 233 #define ANIDB_EPISODE 240 #define ANIDB_PRODUCER 245 #define ANIDB_GROUP 250 #define ANIDB_BUDDY_LIST 253 #define ANIDB_BUDDY_STATE 254 #define ANIDB_BUDDY_ADDED 255 #define ANIDB_BUDDY_DELETED 256 #define ANIDB_BUDDY_ACCEPTED 257 #define ANIDB_BUDDY_DENIED 258 #define ANIDB_VOTED 260 #define ANIDB_VOTE_FOUND 261 #define ANIDB_VOTE_UPDATED 262 #define ANIDB_VOTE_REVOKED 263 #define ANIDB_NOTIFICATION_ENABLED 270 #define ANIDB_NOTIFICATION_NOTIFY 271 #define ANIDB_NOTIFICATION_MESSAGE 272 #define ANIDB_NOTIFICATION_BUDDY 273 #define ANIDB_NOTIFICATION_SHUTDOWN 274 #define ANIDB_PUSHACK_CONFIRMED 280 #define ANIDB_NOTIFYACK_SUCCESSFUL_M 281 #define ANIDB_NOTIFYACK_SUCCESSFUL_N 282 #define ANIDB_NOTIFICATION 290 #define ANIDB_NOTIFYLIST 291 #define ANIDB_NOTIFYGET_MESSAGE 292 #define ANIDB_NOTIFYGET_NOTIFY 293 #define ANIDB_SENDMSG_SUCCESSFUL 294 #define ANIDB_USER 295 /* Affirmative/Negative responses 3XX */ #define ANIDB_PONG 300 #define ANIDB_AUTHPONG 301 #define ANIDB_NO_SUCH_RESOURCE 305 #define ANIDB_API_PASSWORD_NOT_DEFINED 309 #define ANIDB_FILE_ALREADY_IN_MYLIST 310 #define ANIDB_MYLIST_ENTRY_EDITED 311 #define ANIDB_MULTIPLE_MYLIST_ENTRIES 312 #define ANIDB_SIZE_HASH_EXISTS 314 #define ANIDB_INVALID_DATA 315 #define ANIDB_STREAMNOID_USED 316 #define ANIDB_NO_SUCH_FILE 320 #define ANIDB_NO_SUCH_ENTRY 321 #define ANIDB_MULTIPLE_FILES_FOUND 322 #define ANIDB_NO_SUCH_ANIME 330 #define ANIDB_NO_SUCH_ANIME_DESCRIPTION 333 #define ANIDB_NO_SUCH_EPISODE 340 #define ANIDB_NO_SUCH_PRODUCER 345 #define ANIDB_NO_SUCH_GROUP 350 #define ANIDB_BUDDY_ALREADY_ADDED 355 #define ANIDB_NO_SUCH_BUDDY 356 #define ANIDB_BUDDY_ALREADY_ACCEPTED 357 #define ANIDB_BUDDY_ALREADY_DENIED 358 #define ANIDB_NO_SUCH_VOTE 360 #define ANIDB_INVALID_VOTE_TYPE 361 #define ANIDB_INVALID_VOTE_VALUE 362 #define ANIDB_PERMVOTE_NOT_ALLOWED 363 #define ANIDB_ALREADY_PERMVOTED 364 #define ANIDB_NOTIFICATION_DISABLED 370 #define ANIDB_NO_SUCH_PACKET_PENDING 380 #define ANIDB_NO_SUCH_ENTRY_M 381 #define ANIDB_NO_SUCH_ENTRY_N 382 #define ANIDB_NO_SUCH_MESSAGE 392 #define ANIDB_NO_SUCH_NOTIFY 393 #define ANIDB_NO_SUCH_USER 394 /* Negative responses 4XX */ #define ANIDB_NOT_LOGGED_IN 403 #define ANIDB_NO_SUCH_MYLIST_FILE 410 #define ANIDB_NO_SUCH_MYLIST_ENTRY 411 /* Client side failure 5XX */ #define ANIDB_LOGIN_FAILED 500 #define ANIDB_LOGIN_FIRST 501 #define ANIDB_ACCESS_DENIED 502 #define ANIDB_CLIENT_VERSION_OUTDATED 503 #define ANIDB_CLIENT_BANNED 504 #define ANIDB_ILLEGAL_INPUT_OR_ACCESS_DENIED 505 #define ANIDB_INVALID_SESSION 506 #define ANIDB_NO_SUCH_ENCRYPTION_TYPE 509 #define ANIDB_ENCODING_NOT_SUPPORTED 519 #define ANIDB_BANNED 555 #define ANIDB_UNKNOWN_COMMAND 598 /* Server side failure 6XX */ #define ANIDB_INTERNAL_SERVER_ERROR 600 #define ANIDB_ANIDB_OUT_OF_SERVICE 601 #define ANIDB_SERVER_BUSY 602 #define ANIDB_API_VIOLATION 666 #endif diff --git a/src/lib/libanidb/wscript b/src/lib/libanidb/wscript index 56d2e76..8cf18d5 100644 --- a/src/lib/libanidb/wscript +++ b/src/lib/libanidb/wscript @@ -1,27 +1,30 @@ # vim: set fileencoding=utf-8 filetype=python : files = ['handlers.c', 'anidb.c'] def set_options(opt): pass def configure(conf): - pass + for lib in ['rt']: + if not conf.check_cc(lib = lib, uselib_store = lib): + conf.fatal('Unable to find required library') def build(bld): import Options defines = [] if Options.options.debug: defines += ['DEBUG'] obj = bld.new_task_gen( features = 'cc cstaticlib', target = 'anidb', source = files, defines = defines, ccflags = ['-std=gnu99', '-g'], + uselib = 'rt', install_path = False, export_incdirs = '.' )
chrippa/hashfs
5bffbd2c6ba655992b2cf81c037475cb3dd48ab0
Add LICENSE and TODO. Updated README.
diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f249654 --- /dev/null +++ b/LICENSE @@ -0,0 +1,28 @@ + Copyright (c) 2009 hashfs development team + 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 its author 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 COPYRIGHT + OWNER 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. diff --git a/README b/README index 9f29a93..b57d29e 100644 --- a/README +++ b/README @@ -1 +1,5 @@ -Creates a virtual file system based on data from AniDB using FUSE. +hashfs is meant to create virtual filesystems based on metadata. +Metadata is primarily gathered from hashing files and looking up +metadata in different databases. + +hashfs is not usable at this time. diff --git a/TODO b/TODO new file mode 100644 index 0000000..13d2809 --- /dev/null +++ b/TODO @@ -0,0 +1,8 @@ +hashfs is a work in progress + +TODO: + +* Add database support +* Add commands to manipulate mounts +* Add hashfsmount +* More backends, hashdb.com etc
chrippa/hashfs
23865ab1df8a30017bcf3ee9e474e02ba981f0eb
hashfs: Make HASHFS_DEBUG output to $XDG_CONFIG_HOME/hashfs/debug.log
diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index 3a867f0..75058d9 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,205 +1,205 @@ #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { hashfs_file_t *file; HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); file = hashfs_file_new(path); hashfs_backend_file(backend, file); g_free(file); } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; HASHFS_LOG("Hashing dir: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { printf("%s.%s = %s\n", groups[i], keys[j], g_key_file_get_string(config, groups[i], keys[j], NULL)); } } } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; hashfs_config_load(); if (g_module_supported()) { - hashfs_backends_load(g_build_filename(g_get_user_config_dir(), "hashfs/backends", NULL)); + hashfs_backends_load(g_build_filename(g_get_user_config_dir(), "hashfs", "backends", NULL)); hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); hashfs_config_save(); hashfs_backends_destroy(); return 0; } diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h index 000a121..621e9f8 100644 --- a/src/hashfs/hashfs.h +++ b/src/hashfs/hashfs.h @@ -1,103 +1,103 @@ #ifndef _HASHFS_H #define _HASHFS_H #include <stdio.h> #include <stdlib.h> #include <glib.h> #include <glib/gstdio.h> struct hashfs_backend_St; struct hashfs_backend_desc_St; struct hashfs_file_St; typedef struct hashfs_backend_St hashfs_backend_t; typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; typedef struct hashfs_file_St hashfs_file_t; struct hashfs_file_St { gchar *filename; gint64 size; }; struct hashfs_backend_St { gpointer data; struct { gboolean (*init)(hashfs_backend_t *); void (*file)(hashfs_backend_t *, hashfs_file_t *); void (*destroy)(hashfs_backend_t *); } funcs; hashfs_backend_desc_t *desc; }; struct hashfs_backend_desc_St { const gchar *shortname; const gchar *name; const gchar *description; void (*setup_func)(hashfs_backend_t *); }; gchar * hashfs_current_time (void); gchar * hashfs_basename (gchar *name); GKeyFile * hashfs_config_keyfile (void); void hashfs_config_load (void); void hashfs_config_save (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); hashfs_file_t * hashfs_file_new (gchar *filename); gint hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out); -gint hashfs_file_prop_get (hashfs_file_t *file, const gchar *key, gchar **out); +gint hashfs_file_prop_lookup (hashfs_file_t *file, const gchar *key, gchar **out); void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, gchar *value); hashfs_backend_t * hashfs_backends_lookup (const gchar *name); hashfs_backend_t * hashfs_backends_get (gint idx); gint hashfs_backends_count (void); void hashfs_backends_load (const gchar *path); void hashfs_backends_destroy (void); hashfs_backend_t * hashfs_backend_load (const gchar *path); void hashfs_backend_init (hashfs_backend_t *backend); void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); void hashfs_backend_destroy (hashfs_backend_t *backend); void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, gchar *defaultval); void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); #define HASHFS_BACKEND(shname, name, desc, setupfunc) \ hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ shname, \ name, \ desc, \ (void (*)(hashfs_backend_t *))setupfunc, \ }; #define HASHFS_LOG(fmt, ...) { \ printf("%s LOG ", hashfs_current_time()); \ printf(fmt"\n", ## __VA_ARGS__); \ } #define HASHFS_ERROR(fmt, ...) { \ fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ exit(EXIT_FAILURE); \ } #ifdef DEBUG #define HASHFS_DEBUG(fmt, ...) { \ FILE *fd; \ - fd = g_fopen("/tmp/hashfs_debug.log", "at"); \ + fd = g_fopen(g_build_filename(g_get_user_config_dir(), "hashfs", "debug.log", NULL), "at"); \ fprintf(fd, "%s DEBUG %s:%d: ", hashfs_current_time(), __FILE__, __LINE__); \ fprintf(fd, fmt"\n", ## __VA_ARGS__); \ fclose(fd); \ } #else #define HASHFS_DEBUG(...) #endif #endif
chrippa/hashfs
46fe3b34357aabce9a9d07c725e684209da26071
libanidb: Use int64_t instead of double when dealing with filesizes.
diff --git a/src/backends/anidb/anidb.c b/src/backends/anidb/anidb.c index f9e081b..f158392 100644 --- a/src/backends/anidb/anidb.c +++ b/src/backends/anidb/anidb.c @@ -1,173 +1,172 @@ #include <stdio.h> #include <hashfs.h> #include <anidb.h> static void hashfs_anidb_setup (hashfs_backend_t *backend); static gboolean hashfs_anidb_init (hashfs_backend_t *backend); static void hashfs_anidb_destroy (hashfs_backend_t *backend); static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file); static void dump_result (anidb_result_t *result); HASHFS_BACKEND("anidb", "AniDB", "AniDB hashing backend", hashfs_anidb_setup); typedef struct hashfs_anidb_data_St { anidb_session_t *session; } hashfs_anidb_data_t; static void hashfs_anidb_setup (hashfs_backend_t *backend) { backend->funcs.init = hashfs_anidb_init; backend->funcs.file = hashfs_anidb_handle_file; backend->funcs.destroy = hashfs_anidb_destroy; hashfs_backend_config_register(backend, "username", ""); hashfs_backend_config_register(backend, "password", ""); hashfs_backend_config_register(backend, "local_port", "0"); } static gboolean hashfs_anidb_init (hashfs_backend_t *backend) { anidb_session_t *session; anidb_result_t *res; hashfs_anidb_data_t *data; gchar *username, *password, *port_s, *key; gint port; gboolean rval; HASHFS_DEBUG("Init func"); HASHFS_DEBUG("Connecting to AniDB"); hashfs_backend_config_lookup(backend, "username", &username); hashfs_backend_config_lookup(backend, "password", &password); hashfs_backend_config_lookup(backend, "local_port", &port_s); port = atoi(port_s); HASHFS_DEBUG("username=%s, password=%s, port=%d", username, password, port); session = anidb_session_new("anidbfuse", "1", port); data = g_new0(hashfs_anidb_data_t, 1); data->session = session; backend->data = data; res = anidb_session_authenticate(session, username, password); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); HASHFS_DEBUG("Successfully logged in"); rval = TRUE; } else { HASHFS_DEBUG("Failed to get session key"); rval = FALSE; } } else { HASHFS_DEBUG("Unable to login to AniDB servers"); rval = FALSE; } anidb_result_unref(res); return rval; } static void hashfs_anidb_destroy (hashfs_backend_t *backend) { hashfs_anidb_data_t *data; HASHFS_DEBUG("Destroy func"); g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; if (data) { if (anidb_session_is_logged_in(data->session)) { HASHFS_DEBUG("Logging out"); anidb_session_logout(data->session); } anidb_session_unref(data->session); g_free(data); } } static void hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file) { - hashfs_anidb_data_t *data -; + hashfs_anidb_data_t *data; gchar *hash; anidb_result_t *res; g_return_if_fail(backend); data = (hashfs_anidb_data_t *) backend->data; g_return_if_fail(data); if (anidb_session_is_logged_in(data->session)) { if (hashfs_file_hash_ed2k(file, &hash)) { HASHFS_DEBUG("ed2k hash: %s", hash); -/* res = anidb_session_file_ed2k(data->session, (gdouble) file->size, hash); + res = anidb_session_file_ed2k(data->session, file->size, hash); dump_result(res); - anidb_result_unref(res);*/ + anidb_result_unref(res); } } } static void dump_result (anidb_result_t *result) { gint n; gchar *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: HASHFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); HASHFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); HASHFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: HASHFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { HASHFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); } HASHFS_DEBUG(">"); break; } } diff --git a/src/hashfs/backend.c b/src/hashfs/backend.c index 5d54a4c..fd7baf3 100644 --- a/src/hashfs/backend.c +++ b/src/hashfs/backend.c @@ -1,197 +1,194 @@ -#include <sys/stat.h> -#include <string.h> #include <glib.h> -#include <glib/gstdio.h> #include <gmodule.h> #include "hashfs.h" static GList *backends; hashfs_backend_t * hashfs_backend_load (const gchar *path) { GModule *module; gpointer sym; hashfs_backend_t *backend; hashfs_backend_desc_t *desc; HASHFS_DEBUG("Loading module (%s)", path); module = g_module_open(path, 0); if (!module) { HASHFS_DEBUG("Failed to load module: %s", g_module_error()); return NULL; } if (!g_module_symbol(module, "HASHFS_BACKEND_DESC", (gpointer) &sym)) { HASHFS_DEBUG("Failed to lookup symbol: %s", g_module_error()); g_module_close(module); return NULL; } desc = (hashfs_backend_desc_t *) sym; if (!desc) { HASHFS_DEBUG("HASHFS_BACKEND_DESC == NULL"); g_module_close(module); return NULL; } if (hashfs_backends_lookup(desc->shortname)) { HASHFS_DEBUG("Already loaded backend %s", desc->shortname); g_module_close(module); return NULL; } backend = g_new0(hashfs_backend_t, 1); backend->desc = desc; desc->setup_func(backend); HASHFS_DEBUG("Backend successfully loaded: %s - %s - %s", desc->shortname, desc->name, desc->description); return backend; } void hashfs_backends_load (const gchar *path) { GDir *dir; GError *error = NULL; const gchar *filename; gchar *pattern, *glob, *fullpath; hashfs_backend_t *backend; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } glob = g_module_build_path(path, "hashfs_*"); pattern = g_path_get_basename(glob); HASHFS_DEBUG("Loooking for backends in: %s", glob); while ((filename = g_dir_read_name(dir))) { if (!g_pattern_match_simple(pattern, filename)) continue; fullpath = g_build_filename(path, filename, NULL); if (!g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { g_free(fullpath); continue; } backend = hashfs_backend_load(fullpath); if (backend) { backends = g_list_append(backends, backend); } } g_dir_close(dir); } hashfs_backend_t * hashfs_backends_lookup (const gchar *name) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; if (!g_strcmp0(name, backend->desc->shortname)) return backend; } return NULL; } void hashfs_backends_destroy (void) { hashfs_backend_t *backend; GList *item; for (item = g_list_first(backends); item; item = g_list_next(item)) { backend = item->data; hashfs_backend_destroy(backend); } g_list_free(backends); } hashfs_file_t * hashfs_file_new (gchar *filename) { hashfs_file_t *file; struct stat info; stat(filename, &info); file = g_new0(hashfs_file_t, 1); file->filename = filename; file->size = (gint64) info.st_size; return file; } void hashfs_backend_init (hashfs_backend_t *backend) { if (backend->funcs.init) { backend->funcs.init(backend); } } void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file) { if (backend->funcs.file) { backend->funcs.file(backend, file); } } void hashfs_backend_destroy (hashfs_backend_t *backend) { if (backend->funcs.destroy) { backend->funcs.destroy(backend); } g_free(backend); } void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, gchar *defaultval) { if (!hashfs_config_property_exists(backend->desc->shortname, key)) { hashfs_config_property_set(backend->desc->shortname, key, defaultval); } } void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out) { hashfs_config_property_lookup(backend->desc->shortname, key, out); } diff --git a/src/hashfs/config.c b/src/hashfs/config.c index 5f4cd52..b56bdfd 100644 --- a/src/hashfs/config.c +++ b/src/hashfs/config.c @@ -1,96 +1,91 @@ - -#include <sys/stat.h> -#include <string.h> #include <glib.h> -#include <glib/gstdio.h> -#include <gmodule.h> #include "hashfs.h" static GKeyFile *config; static gboolean config_loaded; static const gchar * hashfs_config_build_path (void); gboolean hashfs_config_property_exists (const gchar *group, const gchar *key) { if (g_key_file_has_group(config, group)) { return g_key_file_has_key(config, group, key, NULL); } return FALSE; } void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out) { *out = g_key_file_get_string(config, group, key, NULL); } void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value) { g_key_file_set_string(config, group, key, value); } GKeyFile * hashfs_config_keyfile (void) { return config; } void hashfs_config_load (void) { GError *error = NULL; const gchar *configfile; config = g_key_file_new(); configfile = hashfs_config_build_path(); g_key_file_load_from_file(config, configfile, G_KEY_FILE_NONE, &error); if (error) { /* Don't error when file doesn't exist or is empty */ if (error->code != 4 && error->code != 1) { HASHFS_ERROR("Unable to load config file (%s): %d %s", configfile, error->message); } g_error_free(error); } } void hashfs_config_save (void) { const gchar *configfile; FILE *file; configfile = hashfs_config_build_path(); file = g_fopen(configfile, "w"); fputs(g_key_file_to_data(config, NULL, NULL), file); fclose(file); } static const gchar * hashfs_config_build_path (void) { const gchar *configdir; const gchar *configfile; configdir = g_build_filename(g_get_user_config_dir(), "hashfs", NULL); configfile = g_build_filename(configdir, "hashfs.conf", NULL); if (g_file_test(configdir, G_FILE_TEST_EXISTS)) { if (!g_file_test(configdir, G_FILE_TEST_IS_DIR)) HASHFS_ERROR("Config directory already exists but is not a directory (%s)", configdir); } else { if (g_mkdir_with_parents(configdir, 0755) < 0) { HASHFS_ERROR("Unable to create config directory (%s)", configdir); } } return configfile; } diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c index b27e58b..3a867f0 100644 --- a/src/hashfs/hashfs.c +++ b/src/hashfs/hashfs.c @@ -1,209 +1,205 @@ - -#include <sys/stat.h> -#include <string.h> #include <glib.h> #include <glib/gstdio.h> #include <gmodule.h> - #include "hashfs.h" typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); typedef struct hashfs_cmd_St { gchar *name; hashfs_cmd_func func; gchar *description; } hashfs_cmd_t; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); static void hashfs_cmd_config (gint argc, gchar **argv); static void hashfs_cmd_help (gint argc, gchar **argv); static void hashfs_cmd_update (gint argc, gchar **argv); static hashfs_cmd_t main_cmds[] = { { "config", hashfs_cmd_config, "Manipulate configuration" }, { "help", hashfs_cmd_help, "Show available commands and description" }, { "update", hashfs_cmd_update, "Scan directory and add metadata" }, { NULL, NULL, NULL}, }; static hashfs_cmd_t config_cmds[] = { { NULL, NULL, NULL}, }; static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path) { hashfs_file_t *file; HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); file = hashfs_file_new(path); hashfs_backend_file(backend, file); g_free(file); } static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) { GDir *dir; GError *error; const gchar *filename; gchar *fullpath; HASHFS_LOG("Hashing dir: %s", path); error = NULL; dir = g_dir_open(path, 0, &error); if (error) { HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); g_error_free(error); return; } while ((filename = g_dir_read_name(dir))) { if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) continue; fullpath = g_build_filename(path, filename, NULL); if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { hashfs_hash_file(backend, fullpath); } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { hashfs_hash_dir(backend, fullpath); } g_free(fullpath); } g_dir_close(dir); } static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) { for (gint i = 0; cmds[i].name; i++) { if (!g_strcmp0(cmd, cmds[i].name)) { cmds[i].func(argv - 2, args + 2); } } } static void hashfs_cmd_config (gint argc, gchar **argv) { GKeyFile *config; config = hashfs_config_keyfile(); if (argc == 0) { gint numgroups; gchar **groups; groups = g_key_file_get_groups(config, &numgroups); for (gint i = 0; i < numgroups; i++) { gint numkeys; gchar **keys; keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); for (gint j = 0; j < numkeys; j++) { printf("%s.%s = %s\n", groups[i], keys[j], g_key_file_get_string(config, groups[i], keys[j], NULL)); } } } else if (argc == 1) { gchar *val; gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_lookup(split[0], split[1], &val); printf("%s\n", val); } } else if (argc == 2) { gchar **split; split = g_strsplit(argv[0], ".", 2); if (g_strv_length(split) < 2) { HASHFS_ERROR("Invalid key format"); } else { hashfs_config_property_set(split[0], split[1], argv[1]); printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); } } } static void hashfs_cmd_help (gint argc, gchar **argv) { printf("Available commands:\n"); for (gint i = 0; main_cmds[i].name; i++) { printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); } } static void hashfs_cmd_update (gint argc, gchar **argv) { hashfs_backend_t *backend; if (argc == 0) { } else if (argc == 2) { backend = hashfs_backends_lookup(argv[0]); if (backend) { hashfs_backend_init(backend); hashfs_hash_dir(backend, argv[1]); } } } gint main (gint argc, gchar **argv) { hashfs_backend_t *backend; hashfs_config_load(); if (g_module_supported()) { hashfs_backends_load(g_build_filename(g_get_user_config_dir(), "hashfs/backends", NULL)); hashfs_backends_load("/usr/local/lib/hashfs"); hashfs_backends_load("./_build_/default/src/backends/anidb/"); } else { HASHFS_LOG("This platform does not support loading modules"); return 0; } if (argc > 1) hashfs_cmd(main_cmds, argv[1], argc, argv); else hashfs_cmd(main_cmds, "help", argc, argv); hashfs_config_save(); hashfs_backends_destroy(); return 0; } diff --git a/src/lib/libanidb/anidb.c b/src/lib/libanidb/anidb.c index ee83a49..db23fab 100644 --- a/src/lib/libanidb/anidb.c +++ b/src/lib/libanidb/anidb.c @@ -1,714 +1,714 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; // printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; // printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version, int localport) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } if (localport > 0) { local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(localport); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:%d", localport); } } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; session->clientname = name; session->clientversion = version; session->key = NULL; anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); if (session->key) free(session->key); free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { session->key = (char *) strdup(key); } int anidb_session_is_logged_in (anidb_session_t *session) { if (session->key) return 1; return 0; } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * -anidb_session_file_ed2k (anidb_session_t *session, double size, char *ed2k) +anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k) { anidb_result_t *res; char siz[50]; - sprintf(siz, "%0.0f", size); + sprintf(siz, "%d", size); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { dict->key = key; dict->value = value; } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, char *string) { result->type = ANIDB_RESULT_STRING; result->value.string = string; } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, char *key, char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } int anidb_result_dict_get (anidb_result_t *result, char *key, char **out) { anidb_dict_t *dict; if (result->type != ANIDB_RESULT_DICT) return 0; for (dict = result->value.dict; dict; dict = dict->next) { if (!strcmp(dict->key, key)) { return anidb_dict_get(dict, out); } } return 0; } anidb_dict_t * anidb_result_get_dict (anidb_result_t *result) { if (result->type != ANIDB_RESULT_DICT) return NULL; return result->value.dict; } diff --git a/src/lib/libanidb/anidb.h b/src/lib/libanidb/anidb.h index 02b59cb..b705d69 100644 --- a/src/lib/libanidb/anidb.h +++ b/src/lib/libanidb/anidb.h @@ -1,309 +1,310 @@ #ifndef _LIBANIDB_H #define _LIBANIDB_H #include <sys/time.h> + enum anidb_result_type { ANIDB_RESULT_NULL, ANIDB_RESULT_NUMBER, ANIDB_RESULT_STRING, ANIDB_RESULT_DICT }; struct anidb_session_St { int socket; char *clientname; char *clientversion; char *key; int refcount; }; struct anidb_dict_St { char *key; char *value; struct anidb_dict_St *next; int refcount; }; struct anidb_result_St { struct anidb_error_St *error; int code; enum anidb_result_type type; union { int number; char *string; struct anidb_dict_St *dict; } value; int refcount; }; struct anidb_result_handler_St { int code; void (*func)(struct anidb_result_St *, char *); }; /* Types */ typedef enum anidb_result_type anidb_result_type_t; typedef struct anidb_session_St anidb_session_t; typedef struct anidb_dict_St anidb_dict_t; typedef struct anidb_result_St anidb_result_t; typedef struct anidb_result_handler_St anidb_result_handler_t; typedef struct anidb_error_St anidb_error_t; /* Session */ anidb_session_t * anidb_session_new (char *name, char *version, int localport); /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password); /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session); /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name); anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id); /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int ep); /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep); anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep); /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id); -anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, double size, char *ed2k); +anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int64_t size, char *ed2k); /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name); /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id); /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session); /* VOTE */ /* RANDOM */ /* MYLISTEXPORT */ /* PING */ anidb_result_t * anidb_session_ping (anidb_session_t *session); /* VERSION */ anidb_result_t * anidb_session_uptime (anidb_session_t *session); /* UPTIME */ anidb_result_t * anidb_session_version (anidb_session_t *session); /* ENCODING */ /* SENDMSG */ /* USER */ void anidb_session_set_key (anidb_session_t *session, char *key); int anidb_session_is_logged_in (anidb_session_t *session); void anidb_session_ref (anidb_session_t *session); void anidb_session_unref (anidb_session_t *session); /* Dict */ anidb_dict_t * anidb_dict_new (void); anidb_dict_t * anidb_dict_next (anidb_dict_t *dict); void anidb_dict_ref (anidb_dict_t *dict); void anidb_dict_unref (anidb_dict_t *dict); void anidb_dict_set (anidb_dict_t *dict, char *key, char *value); int anidb_dict_get (anidb_dict_t *dict, char **out); /* Result */ anidb_result_t * anidb_result_new (int code); void anidb_result_ref (anidb_result_t *result); void anidb_result_unref (anidb_result_t *result); void anidb_result_set_str (anidb_result_t *result, char *string); void anidb_result_set_int (anidb_result_t *result, int number); void anidb_result_dict_set (anidb_result_t *result, char *key, char *value); anidb_result_type_t anidb_result_get_type (anidb_result_t *result); int anidb_result_get_code (anidb_result_t *result); int anidb_result_get_str (anidb_result_t *result, char **out); int anidb_result_get_int (anidb_result_t *result, int *out); int anidb_result_dict_get (anidb_result_t *result, char *key, char **out); anidb_dict_t * anidb_result_get_dict (anidb_result_t *result); #define ANIDB_SERVER_HOST "api.anidb.net" #define ANIDB_SERVER_PORT 9000 #define ANIDB_PROTO_VERSION "3" /* Positive responses 2XX */ #define ANIDB_LOGIN_ACCEPTED 200 #define ANIDB_LOGIN_ACCEPTED_NEW_VER 201 #define ANIDB_LOGGED_OUT 203 #define ANIDB_RESOURCE 205 #define ANIDB_STATS 206 #define ANIDB_TOP 207 #define ANIDB_UPTIME 208 #define ANIDB_ENCRYPTION_ENABLED 209 #define ANIDB_MYLIST_ENTRY_ADDED 210 #define ANIDB_MYLIST_ENTRY_DELETED 211 #define ANIDB_ADDED_FILE 214 #define ANIDB_ADDED_STREAM 215 #define ANIDB_ENCODING_CHANGED 219 #define ANIDB_FILE 220 #define ANIDB_MYLIST 221 #define ANIDB_MYLIST_STATS 222 #define ANIDB_ANIME 230 #define ANIDB_ANIME_BEST_MATCH 231 #define ANIDB_RANDOMANIME 232 #define ANIDB_ANIME_DESCRIPTION 233 #define ANIDB_EPISODE 240 #define ANIDB_PRODUCER 245 #define ANIDB_GROUP 250 #define ANIDB_BUDDY_LIST 253 #define ANIDB_BUDDY_STATE 254 #define ANIDB_BUDDY_ADDED 255 #define ANIDB_BUDDY_DELETED 256 #define ANIDB_BUDDY_ACCEPTED 257 #define ANIDB_BUDDY_DENIED 258 #define ANIDB_VOTED 260 #define ANIDB_VOTE_FOUND 261 #define ANIDB_VOTE_UPDATED 262 #define ANIDB_VOTE_REVOKED 263 #define ANIDB_NOTIFICATION_ENABLED 270 #define ANIDB_NOTIFICATION_NOTIFY 271 #define ANIDB_NOTIFICATION_MESSAGE 272 #define ANIDB_NOTIFICATION_BUDDY 273 #define ANIDB_NOTIFICATION_SHUTDOWN 274 #define ANIDB_PUSHACK_CONFIRMED 280 #define ANIDB_NOTIFYACK_SUCCESSFUL_M 281 #define ANIDB_NOTIFYACK_SUCCESSFUL_N 282 #define ANIDB_NOTIFICATION 290 #define ANIDB_NOTIFYLIST 291 #define ANIDB_NOTIFYGET_MESSAGE 292 #define ANIDB_NOTIFYGET_NOTIFY 293 #define ANIDB_SENDMSG_SUCCESSFUL 294 #define ANIDB_USER 295 /* Affirmative/Negative responses 3XX */ #define ANIDB_PONG 300 #define ANIDB_AUTHPONG 301 #define ANIDB_NO_SUCH_RESOURCE 305 #define ANIDB_API_PASSWORD_NOT_DEFINED 309 #define ANIDB_FILE_ALREADY_IN_MYLIST 310 #define ANIDB_MYLIST_ENTRY_EDITED 311 #define ANIDB_MULTIPLE_MYLIST_ENTRIES 312 #define ANIDB_SIZE_HASH_EXISTS 314 #define ANIDB_INVALID_DATA 315 #define ANIDB_STREAMNOID_USED 316 #define ANIDB_NO_SUCH_FILE 320 #define ANIDB_NO_SUCH_ENTRY 321 #define ANIDB_MULTIPLE_FILES_FOUND 322 #define ANIDB_NO_SUCH_ANIME 330 #define ANIDB_NO_SUCH_ANIME_DESCRIPTION 333 #define ANIDB_NO_SUCH_EPISODE 340 #define ANIDB_NO_SUCH_PRODUCER 345 #define ANIDB_NO_SUCH_GROUP 350 #define ANIDB_BUDDY_ALREADY_ADDED 355 #define ANIDB_NO_SUCH_BUDDY 356 #define ANIDB_BUDDY_ALREADY_ACCEPTED 357 #define ANIDB_BUDDY_ALREADY_DENIED 358 #define ANIDB_NO_SUCH_VOTE 360 #define ANIDB_INVALID_VOTE_TYPE 361 #define ANIDB_INVALID_VOTE_VALUE 362 #define ANIDB_PERMVOTE_NOT_ALLOWED 363 #define ANIDB_ALREADY_PERMVOTED 364 #define ANIDB_NOTIFICATION_DISABLED 370 #define ANIDB_NO_SUCH_PACKET_PENDING 380 #define ANIDB_NO_SUCH_ENTRY_M 381 #define ANIDB_NO_SUCH_ENTRY_N 382 #define ANIDB_NO_SUCH_MESSAGE 392 #define ANIDB_NO_SUCH_NOTIFY 393 #define ANIDB_NO_SUCH_USER 394 /* Negative responses 4XX */ #define ANIDB_NOT_LOGGED_IN 403 #define ANIDB_NO_SUCH_MYLIST_FILE 410 #define ANIDB_NO_SUCH_MYLIST_ENTRY 411 /* Client side failure 5XX */ #define ANIDB_LOGIN_FAILED 500 #define ANIDB_LOGIN_FIRST 501 #define ANIDB_ACCESS_DENIED 502 #define ANIDB_CLIENT_VERSION_OUTDATED 503 #define ANIDB_CLIENT_BANNED 504 #define ANIDB_ILLEGAL_INPUT_OR_ACCESS_DENIED 505 #define ANIDB_INVALID_SESSION 506 #define ANIDB_NO_SUCH_ENCRYPTION_TYPE 509 #define ANIDB_ENCODING_NOT_SUPPORTED 519 #define ANIDB_BANNED 555 #define ANIDB_UNKNOWN_COMMAND 598 /* Server side failure 6XX */ #define ANIDB_INTERNAL_SERVER_ERROR 600 #define ANIDB_ANIDB_OUT_OF_SERVICE 601 #define ANIDB_SERVER_BUSY 602 #define ANIDB_API_VIOLATION 666 #endif
chrippa/hashfs
cde05de1d458ed8d7d8b44140a11bba6446b2f45
Large update:
diff --git a/src/anidbfs/anidbfs-update.c b/src/anidbfs/anidbfs-update.c deleted file mode 100644 index 77c15b5..0000000 --- a/src/anidbfs/anidbfs-update.c +++ /dev/null @@ -1,255 +0,0 @@ -#define _FILE_OFFSET_BITS 64 -#define _LARGEFILE64_SOURCE -#define BLOCKSIZE (9500*1024) - -#include <stdio.h> -#include <malloc.h> -#include <stdlib.h> -#include <stdio.h> -#include <string.h> -#include <errno.h> - -#include <unistd.h> -#include <sys/mman.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> -#include <dirent.h> -#include <math.h> - -#include <openssl/md4.h> -#include <anidb.h> - -#include "util.h" - -static void anidbfs_hash_file (anidb_session_t *session, char *path, struct stat *info); -static void anidbfs_hash_dir (anidb_session_t *session, char *path); - -static char * ed2k_hash (char *filename); -static void dump_result (anidb_result_t *result); -static const char hexdigits[16] = "0123456789abcdef"; - -static char * -ed2k_hash (char *filename) -{ - int fd, blocks; - off_t size; - struct stat stat; - char *hash_str; - unsigned char *hashes, *hash; - - if ((fd = open(filename, O_RDONLY)) < 0) { - ANIDBFS_DEBUG("Failed to open file (%s)", filename); - - return NULL; - } - - if (fstat(fd, &stat) < 0) { - ANIDBFS_DEBUG("Failed to stat file (%s)", filename); - - return NULL; - } - - size = stat.st_size; - - blocks = (double) size / (double) BLOCKSIZE; - - if (fmod((double) size, (double) BLOCKSIZE) > 0) - blocks++; - - hash = (unsigned char *) malloc(16); - hash_str = (char *) malloc(33); - hashes = (unsigned char *) malloc(blocks * 16); - - if (!hash || !hashes || !hash_str || !filename) { - ANIDBFS_DEBUG("Failed to allocate memory (%s)", filename); - - return NULL; - } - - for (int b = 0; b < blocks; b++) { - MD4_CTX ctx; - int len; - void *data; - off_t offset; - - len = BLOCKSIZE; - if (b == blocks - 1) /* Last block is smaller than BLOCKSIZE */ - len = ceil(fmod((double) size, (double) BLOCKSIZE)); - - offset = (off_t) ((double) b * (double) BLOCKSIZE); - - data = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, offset); - if (!data) { - ANIDBFS_DEBUG("mmap failed to read data (%s)", filename); - return NULL; - } - - MD4_Init(&ctx); - MD4_Update(&ctx, data, len); - MD4_Final(hashes + (b * 16), &ctx); - - munmap(data, len); - } - - close(fd); - - /* If we have hashed more than one block, - run MD4 on all the previous hashes */ - if (blocks > 1) { - MD4_CTX ctx; - - MD4_Init(&ctx); - MD4_Update(&ctx, hashes, 16 * blocks); - MD4_Final(hash, &ctx); - } else { - memcpy(hash, hashes, 16); - } - - /* Convert hash to hex string format */ - memset(hash_str, 0x00, 33 * sizeof(char)); - for (int i = 0; i < 16; i++) { - hash_str[(i<<1)] = hexdigits[(((hash[i]) & 0xf0) >> 4)]; - hash_str[(i<<1)+1] = hexdigits[(((hash[i]) & 0x0f))]; - } - - free(hash); - free(hashes); - - return hash_str; -} - -static void -dump_result (anidb_result_t *result) -{ - int n; - char *str; - anidb_dict_t *dict; - - switch (anidb_result_get_type(result)) { - case ANIDB_RESULT_NULL: - ANIDBFS_DEBUG("<result %p null>", result); - break; - - case ANIDB_RESULT_STRING: - anidb_result_get_str(result, &str); - ANIDBFS_DEBUG("<result %p (string) \"%s\">", result, str); - - break; - - case ANIDB_RESULT_NUMBER: - anidb_result_get_int(result, &n); - ANIDBFS_DEBUG("<result %p (int) \"%d\">", result, n); - - break; - - case ANIDB_RESULT_DICT: - ANIDBFS_DEBUG("<result %p (dict)", result); - - for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { - ANIDBFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); - - } - - ANIDBFS_DEBUG(">"); - - break; - } -} - -static void -anidbfs_hash_file (anidb_session_t *session, char *path, struct stat *info) -{ - char *hash; - - ANIDBFS_LOG("Hashing file: %s", anidbfs_basename(path)); - - hash = ed2k_hash(path); - - if (hash) { - ANIDBFS_DEBUG("Hash: %s", hash) - - anidb_result_t *res; - - res = anidb_session_file_ed2k(session, (double) info->st_size, hash); - - dump_result(res); - - anidb_result_unref(res); - - free(hash); - } -} - -static void -anidbfs_hash_dir (anidb_session_t *session, char *path) -{ - DIR *dir; - char fullpath[9999]; - struct stat info; - struct dirent *entry; - - ANIDBFS_LOG("Hashing dir: %s", path); - - dir = opendir(path); - - if (dir) { - while (entry = readdir(dir)) { - - if (!strcmp (entry->d_name, ".") || !strcmp (entry->d_name, "..")) - continue; - - sprintf(fullpath, "%s%s%s", path, - (path[strlen(path)-1] == '/') ? "" : "/", - entry->d_name); - - stat(fullpath, &info); - - if (S_ISDIR(info.st_mode)) { - anidbfs_hash_dir(session, fullpath); - } else if (S_ISREG(info.st_mode) || S_ISLNK(info.st_mode)) { - anidbfs_hash_file(session, fullpath, &info); - } - } - - closedir(dir); - } - -} - -int -main (int argc, char *argv[]) -{ - anidb_session_t *session; - anidb_result_t *res; - char *key; - - if (argc < 4) { - fprintf(stderr, "Usage: %s <username> <password> <path>\n", argv[0]); - exit(0); - } - - session = anidb_session_new("anidbfuse", "1"); - - ANIDBFS_DEBUG("Connecting to AniDB"); - res = anidb_session_authenticate(session, argv[1], argv[2]); - dump_result(res); - - if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { - if (anidb_result_get_str(res, &key)) { - anidb_session_set_key(session, key); - } - - anidbfs_hash_dir(session, argv[3]); - - ANIDBFS_DEBUG("Logging out"); - anidb_session_logout(session); - } - - anidb_result_unref(res); - anidb_session_unref(session); - - return 1; -} - - diff --git a/src/anidbfs/anidbfs.h b/src/anidbfs/anidbfs.h deleted file mode 100644 index e69de29..0000000 diff --git a/src/anidbfs/db.h b/src/anidbfs/db.h deleted file mode 100644 index e69de29..0000000 diff --git a/src/anidbfs/util.h b/src/anidbfs/util.h deleted file mode 100644 index cc0c52a..0000000 --- a/src/anidbfs/util.h +++ /dev/null @@ -1,22 +0,0 @@ -#ifndef _ANIDBFS_UTIL_H -#define _ANIDBFS_UTIL_H - -char * anidbfs_current_time(void); -char * anidbfs_basename (char *name); - - -#define ANIDBFS_LOG(fmt, ...) { \ - printf("%s LOG ", anidbfs_current_time()); \ - printf(fmt"\n", ## __VA_ARGS__); \ -} - -#ifdef DEBUG - #define ANIDBFS_DEBUG(fmt, ...) { \ - printf("%s DEBUG %s:%d: ", anidbfs_current_time(), __FILE__, __LINE__); \ - printf(fmt"\n", ## __VA_ARGS__); \ - } -#else - #define ANIDBFS_DEBUG(...) -#endif - -#endif diff --git a/src/backends/anidb/anidb.c b/src/backends/anidb/anidb.c new file mode 100644 index 0000000..f9e081b --- /dev/null +++ b/src/backends/anidb/anidb.c @@ -0,0 +1,173 @@ +#include <stdio.h> + +#include <hashfs.h> +#include <anidb.h> + +static void hashfs_anidb_setup (hashfs_backend_t *backend); +static gboolean hashfs_anidb_init (hashfs_backend_t *backend); +static void hashfs_anidb_destroy (hashfs_backend_t *backend); +static void hashfs_anidb_handle_file (hashfs_backend_t *backend, + hashfs_file_t *file); + +static void dump_result (anidb_result_t *result); + +HASHFS_BACKEND("anidb", "AniDB", + "AniDB hashing backend", + hashfs_anidb_setup); + +typedef struct hashfs_anidb_data_St { + anidb_session_t *session; +} hashfs_anidb_data_t; + + +static void +hashfs_anidb_setup (hashfs_backend_t *backend) +{ + backend->funcs.init = hashfs_anidb_init; + backend->funcs.file = hashfs_anidb_handle_file; + backend->funcs.destroy = hashfs_anidb_destroy; + + hashfs_backend_config_register(backend, "username", ""); + hashfs_backend_config_register(backend, "password", ""); + hashfs_backend_config_register(backend, "local_port", "0"); +} + +static gboolean +hashfs_anidb_init (hashfs_backend_t *backend) +{ + anidb_session_t *session; + anidb_result_t *res; + hashfs_anidb_data_t *data; + gchar *username, *password, *port_s, *key; + gint port; + gboolean rval; + + HASHFS_DEBUG("Init func"); + HASHFS_DEBUG("Connecting to AniDB"); + + hashfs_backend_config_lookup(backend, "username", &username); + hashfs_backend_config_lookup(backend, "password", &password); + hashfs_backend_config_lookup(backend, "local_port", &port_s); + + port = atoi(port_s); + + HASHFS_DEBUG("username=%s, password=%s, port=%d", username, password, port); + + session = anidb_session_new("anidbfuse", "1", port); + data = g_new0(hashfs_anidb_data_t, 1); + data->session = session; + backend->data = data; + + res = anidb_session_authenticate(session, username, password); + + if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { + if (anidb_result_get_str(res, &key)) { + anidb_session_set_key(session, key); + + HASHFS_DEBUG("Successfully logged in"); + + rval = TRUE; + } else { + HASHFS_DEBUG("Failed to get session key"); + + rval = FALSE; + } + } else { + HASHFS_DEBUG("Unable to login to AniDB servers"); + + rval = FALSE; + } + + anidb_result_unref(res); + + return rval; +} + +static void +hashfs_anidb_destroy (hashfs_backend_t *backend) +{ + hashfs_anidb_data_t *data; + + HASHFS_DEBUG("Destroy func"); + + g_return_if_fail(backend); + + data = (hashfs_anidb_data_t *) backend->data; + + if (data) { + if (anidb_session_is_logged_in(data->session)) { + HASHFS_DEBUG("Logging out"); + + anidb_session_logout(data->session); + } + + anidb_session_unref(data->session); + + g_free(data); + } +} + +static void +hashfs_anidb_handle_file (hashfs_backend_t *backend, hashfs_file_t *file) +{ + hashfs_anidb_data_t *data +; + gchar *hash; + anidb_result_t *res; + + g_return_if_fail(backend); + + data = (hashfs_anidb_data_t *) backend->data; + + g_return_if_fail(data); + + if (anidb_session_is_logged_in(data->session)) { + if (hashfs_file_hash_ed2k(file, &hash)) { + HASHFS_DEBUG("ed2k hash: %s", hash); + +/* res = anidb_session_file_ed2k(data->session, (gdouble) file->size, hash); + + dump_result(res); + + anidb_result_unref(res);*/ + } + } +} + +static void +dump_result (anidb_result_t *result) +{ + gint n; + gchar *str; + anidb_dict_t *dict; + + switch (anidb_result_get_type(result)) { + case ANIDB_RESULT_NULL: + HASHFS_DEBUG("<result %p null>", result); + break; + + case ANIDB_RESULT_STRING: + anidb_result_get_str(result, &str); + HASHFS_DEBUG("<result %p (string) \"%s\">", result, str); + + break; + + case ANIDB_RESULT_NUMBER: + anidb_result_get_int(result, &n); + HASHFS_DEBUG("<result %p (int) \"%d\">", result, n); + + break; + + case ANIDB_RESULT_DICT: + HASHFS_DEBUG("<result %p (dict)", result); + + for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { + HASHFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); + + } + + HASHFS_DEBUG(">"); + + break; + } +} diff --git a/src/backends/anidb/wscript b/src/backends/anidb/wscript new file mode 100644 index 0000000..3f38dd6 --- /dev/null +++ b/src/backends/anidb/wscript @@ -0,0 +1,29 @@ +# vim: set fileencoding=utf-8 filetype=python : + +files = ['anidb.c'] + +def set_options(opt): + pass + +def configure(conf): + pass + +def build(bld): + import Options + + defines = [] + + if Options.options.debug: + defines += ['DEBUG'] + + obj = bld.new_task_gen( + features = 'cc cshlib', + source = files, + target = 'hashfs_anidb', + includes = '. ../../hashfs', + install_path = '${PREFIX}/lib/hashfs', + ccflags = ['-std=gnu99', '-g'], + defines = defines, + uselib = 'glib-2.0', + uselib_local = 'anidb', + ) diff --git a/src/hashfs/backend.c b/src/hashfs/backend.c new file mode 100644 index 0000000..5d54a4c --- /dev/null +++ b/src/hashfs/backend.c @@ -0,0 +1,197 @@ +#include <sys/stat.h> +#include <string.h> +#include <glib.h> +#include <glib/gstdio.h> +#include <gmodule.h> + +#include "hashfs.h" + +static GList *backends; + +hashfs_backend_t * +hashfs_backend_load (const gchar *path) +{ + GModule *module; + gpointer sym; + hashfs_backend_t *backend; + hashfs_backend_desc_t *desc; + + HASHFS_DEBUG("Loading module (%s)", path); + + module = g_module_open(path, 0); + + if (!module) { + HASHFS_DEBUG("Failed to load module: %s", g_module_error()); + + return NULL; + } + + if (!g_module_symbol(module, "HASHFS_BACKEND_DESC", (gpointer) &sym)) { + HASHFS_DEBUG("Failed to lookup symbol: %s", g_module_error()); + + g_module_close(module); + + return NULL; + } + + + desc = (hashfs_backend_desc_t *) sym; + + if (!desc) { + HASHFS_DEBUG("HASHFS_BACKEND_DESC == NULL"); + + g_module_close(module); + + return NULL; + } + + if (hashfs_backends_lookup(desc->shortname)) { + HASHFS_DEBUG("Already loaded backend %s", desc->shortname); + + g_module_close(module); + + return NULL; + } + + backend = g_new0(hashfs_backend_t, 1); + backend->desc = desc; + + desc->setup_func(backend); + + HASHFS_DEBUG("Backend successfully loaded: %s - %s - %s", desc->shortname, + desc->name, desc->description); + + return backend; +} + +void +hashfs_backends_load (const gchar *path) +{ + GDir *dir; + GError *error = NULL; + const gchar *filename; + gchar *pattern, *glob, *fullpath; + hashfs_backend_t *backend; + + dir = g_dir_open(path, 0, &error); + + if (error) { + HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); + g_error_free(error); + + return; + } + + glob = g_module_build_path(path, "hashfs_*"); + pattern = g_path_get_basename(glob); + + HASHFS_DEBUG("Loooking for backends in: %s", glob); + + while ((filename = g_dir_read_name(dir))) { + + if (!g_pattern_match_simple(pattern, filename)) + continue; + + fullpath = g_build_filename(path, filename, NULL); + + if (!g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { + g_free(fullpath); + continue; + } + + backend = hashfs_backend_load(fullpath); + + if (backend) { + backends = g_list_append(backends, backend); + } + } + + g_dir_close(dir); +} + +hashfs_backend_t * +hashfs_backends_lookup (const gchar *name) +{ + hashfs_backend_t *backend; + GList *item; + + for (item = g_list_first(backends); item; item = g_list_next(item)) { + backend = item->data; + + if (!g_strcmp0(name, backend->desc->shortname)) + return backend; + } + + return NULL; +} + +void +hashfs_backends_destroy (void) +{ + hashfs_backend_t *backend; + GList *item; + + for (item = g_list_first(backends); item; item = g_list_next(item)) { + backend = item->data; + + hashfs_backend_destroy(backend); + } + + g_list_free(backends); +} + +hashfs_file_t * +hashfs_file_new (gchar *filename) +{ + hashfs_file_t *file; + struct stat info; + + stat(filename, &info); + + file = g_new0(hashfs_file_t, 1); + file->filename = filename; + file->size = (gint64) info.st_size; + + return file; +} +void +hashfs_backend_init (hashfs_backend_t *backend) +{ + if (backend->funcs.init) { + backend->funcs.init(backend); + } +} + +void +hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file) +{ + if (backend->funcs.file) { + backend->funcs.file(backend, file); + } +} + +void +hashfs_backend_destroy (hashfs_backend_t *backend) +{ + if (backend->funcs.destroy) { + backend->funcs.destroy(backend); + } + + g_free(backend); +} + +void +hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, + gchar *defaultval) +{ + if (!hashfs_config_property_exists(backend->desc->shortname, key)) { + hashfs_config_property_set(backend->desc->shortname, key, defaultval); + } +} + +void +hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, + gchar **out) +{ + hashfs_config_property_lookup(backend->desc->shortname, key, out); +} diff --git a/src/hashfs/config.c b/src/hashfs/config.c new file mode 100644 index 0000000..5f4cd52 --- /dev/null +++ b/src/hashfs/config.c @@ -0,0 +1,96 @@ + +#include <sys/stat.h> +#include <string.h> +#include <glib.h> +#include <glib/gstdio.h> +#include <gmodule.h> + +#include "hashfs.h" + +static GKeyFile *config; +static gboolean config_loaded; +static const gchar * hashfs_config_build_path (void); + + +gboolean +hashfs_config_property_exists (const gchar *group, const gchar *key) +{ + if (g_key_file_has_group(config, group)) { + return g_key_file_has_key(config, group, key, NULL); + } + + return FALSE; +} + +void +hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out) +{ + *out = g_key_file_get_string(config, group, key, NULL); +} + +void +hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value) +{ + g_key_file_set_string(config, group, key, value); +} + +GKeyFile * +hashfs_config_keyfile (void) +{ + return config; +} + +void +hashfs_config_load (void) +{ + GError *error = NULL; + const gchar *configfile; + + config = g_key_file_new(); + configfile = hashfs_config_build_path(); + + g_key_file_load_from_file(config, configfile, G_KEY_FILE_NONE, &error); + + if (error) { + /* Don't error when file doesn't exist or is empty */ + if (error->code != 4 && error->code != 1) { + HASHFS_ERROR("Unable to load config file (%s): %d %s", configfile, error->message); + } + + g_error_free(error); + } +} + +void +hashfs_config_save (void) +{ + const gchar *configfile; + FILE *file; + + configfile = hashfs_config_build_path(); + file = g_fopen(configfile, "w"); + fputs(g_key_file_to_data(config, NULL, NULL), file); + + fclose(file); +} + +static const gchar * +hashfs_config_build_path (void) +{ + const gchar *configdir; + const gchar *configfile; + + configdir = g_build_filename(g_get_user_config_dir(), "hashfs", NULL); + configfile = g_build_filename(configdir, "hashfs.conf", NULL); + + if (g_file_test(configdir, G_FILE_TEST_EXISTS)) { + if (!g_file_test(configdir, G_FILE_TEST_IS_DIR)) + HASHFS_ERROR("Config directory already exists but is not a directory (%s)", configdir); + } else { + if (g_mkdir_with_parents(configdir, 0755) < 0) { + HASHFS_ERROR("Unable to create config directory (%s)", configdir); + } + } + + return configfile; +} diff --git a/src/anidbfs/db.c b/src/hashfs/db.c similarity index 100% rename from src/anidbfs/db.c rename to src/hashfs/db.c diff --git a/src/hashfs/ed2k.c b/src/hashfs/ed2k.c new file mode 100644 index 0000000..6c8b358 --- /dev/null +++ b/src/hashfs/ed2k.c @@ -0,0 +1,97 @@ +#define _FILE_OFFSET_BITS 64 +#define _LARGEFILE_SOURCE 1 +#define _LARGEFILE64_SOURCE 1 +#define _LARGE_FILES 1 + +#define BLOCKSIZE (9500*1024) + +#include <unistd.h> +#include <fcntl.h> +#include <sys/mman.h> +#include <sys/types.h> + +#include <openssl/md4.h> +#include <glib.h> +#include <glib/gstdio.h> +#include <glib/gprintf.h> + +#include "hashfs.h" + + +static const gchar hexdigits[16] = "0123456789abcdef"; + +gint +hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out) +{ + gint blocks, fd, len; + gint64 size, offset; + guchar *hash_blocks, *hash_final; + gchar *hash_str; + MD4_CTX ctx; + gpointer data; + + if ((fd = g_open(file->filename, O_RDONLY, "rb")) < 0) { + HASHFS_DEBUG("Failed to open file (%s)", file->filename); + + return 0; + } + + blocks = file->size / BLOCKSIZE; + + if ((file->size % BLOCKSIZE) > 0) + blocks++; + + + if (blocks < 1) + return 0; + + + hash_blocks = g_malloc(blocks * 16); + hash_final = g_malloc(16); + hash_str = g_strnfill(33, 0); + offset = 0; + + g_return_val_if_fail(hash_blocks != NULL, 0); + g_return_val_if_fail(hash_final != NULL, 0); + g_return_val_if_fail(hash_str != NULL, 0); + + for (gint b = 0; b < blocks; b++) { + len = (blocks - b) == 1 ? file->size % BLOCKSIZE : BLOCKSIZE; + data = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, offset); + + g_return_val_if_fail(data != NULL, 0); + + MD4_Init(&ctx); + MD4_Update(&ctx, data, len); + MD4_Final(hash_blocks + (b * 16), &ctx); + + munmap(data, len); + + offset += len; + } + + close(fd); + + /* If we have hashed more than one block, + run MD4 on all the previous hashes */ + if (blocks > 1) { + MD4_Init(&ctx); + MD4_Update(&ctx, hash_blocks, 16 * blocks); + MD4_Final(hash_final, &ctx); + } else { + hash_final = g_memdup(hash_blocks, 16); + } + + /* Convert hash to hex string format */ + for (gint i = 0; i < 16; i++) { + hash_str[(i<<1)] = hexdigits[(((hash_final[i]) & 0xf0) >> 4)]; + hash_str[(i<<1)+1] = hexdigits[(((hash_final[i]) & 0x0f))]; + } + + g_free(hash_blocks); + g_free(hash_final); + + *out = hash_str; + + return 1; +} diff --git a/src/hashfs/hashfs.c b/src/hashfs/hashfs.c new file mode 100644 index 0000000..b27e58b --- /dev/null +++ b/src/hashfs/hashfs.c @@ -0,0 +1,209 @@ + +#include <sys/stat.h> +#include <string.h> +#include <glib.h> +#include <glib/gstdio.h> +#include <gmodule.h> + + +#include "hashfs.h" + +typedef void (*hashfs_cmd_func) (gint argc, gchar **argv); + +typedef struct hashfs_cmd_St { + gchar *name; + hashfs_cmd_func func; + gchar *description; +} hashfs_cmd_t; + + +static void hashfs_hash_file (hashfs_backend_t *backend, gchar *path); +static void hashfs_hash_dir (hashfs_backend_t *backend, gchar *path); + +static void hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args); +static void hashfs_cmd_config (gint argc, gchar **argv); +static void hashfs_cmd_help (gint argc, gchar **argv); +static void hashfs_cmd_update (gint argc, gchar **argv); + +static +hashfs_cmd_t main_cmds[] = { + { "config", hashfs_cmd_config, "Manipulate configuration" }, + { "help", hashfs_cmd_help, "Show available commands and description" }, + { "update", hashfs_cmd_update, "Scan directory and add metadata" }, + + { NULL, NULL, NULL}, +}; + +static +hashfs_cmd_t config_cmds[] = { + + { NULL, NULL, NULL}, +}; + + +static void +hashfs_hash_file (hashfs_backend_t *backend, gchar *path) +{ + hashfs_file_t *file; + + HASHFS_LOG("Hashing file: %s", hashfs_basename(path)); + + file = hashfs_file_new(path); + + hashfs_backend_file(backend, file); + + g_free(file); +} + +static void +hashfs_hash_dir (hashfs_backend_t *backend, gchar *path) +{ + GDir *dir; + GError *error; + const gchar *filename; + gchar *fullpath; + + HASHFS_LOG("Hashing dir: %s", path); + + error = NULL; + dir = g_dir_open(path, 0, &error); + + if (error) { + HASHFS_DEBUG("Failed to open directory (%s): %s", path, error->message); + g_error_free(error); + + return; + } + + while ((filename = g_dir_read_name(dir))) { + if (!g_strcmp0(filename, ".") || !g_strcmp0(filename, "..")) + continue; + + fullpath = g_build_filename(path, filename, NULL); + + if (g_file_test(fullpath, G_FILE_TEST_IS_REGULAR)) { + hashfs_hash_file(backend, fullpath); + } else if (g_file_test(fullpath, G_FILE_TEST_IS_DIR)) { + hashfs_hash_dir(backend, fullpath); + } + + g_free(fullpath); + } + + g_dir_close(dir); +} + +static void +hashfs_cmd (hashfs_cmd_t *cmds, gchar *cmd, gint argv, gchar **args) +{ + for (gint i = 0; cmds[i].name; i++) { + if (!g_strcmp0(cmd, cmds[i].name)) { + cmds[i].func(argv - 2, args + 2); + } + } +} + +static void +hashfs_cmd_config (gint argc, gchar **argv) +{ + GKeyFile *config; + + config = hashfs_config_keyfile(); + + if (argc == 0) { + gint numgroups; + gchar **groups; + + groups = g_key_file_get_groups(config, &numgroups); + + for (gint i = 0; i < numgroups; i++) { + gint numkeys; + gchar **keys; + + keys = g_key_file_get_keys(config, groups[i], &numkeys, NULL); + + for (gint j = 0; j < numkeys; j++) { + printf("%s.%s = %s\n", groups[i], keys[j], g_key_file_get_string(config, + groups[i], keys[j], NULL)); + } + } + } else if (argc == 1) { + gchar *val; + gchar **split; + + split = g_strsplit(argv[0], ".", 2); + + if (g_strv_length(split) < 2) { + HASHFS_ERROR("Invalid key format"); + } else { + hashfs_config_property_lookup(split[0], split[1], &val); + printf("%s\n", val); + } + } else if (argc == 2) { + gchar **split; + + split = g_strsplit(argv[0], ".", 2); + + if (g_strv_length(split) < 2) { + HASHFS_ERROR("Invalid key format"); + } else { + hashfs_config_property_set(split[0], split[1], argv[1]); + printf("Config value %s.%s set to %s\n", split[0], split[1], argv[1]); + } + } +} + +static void +hashfs_cmd_help (gint argc, gchar **argv) +{ + printf("Available commands:\n"); + + for (gint i = 0; main_cmds[i].name; i++) { + printf(" %-15s %s\n", main_cmds[i].name, main_cmds[i].description); + } +} + +static void +hashfs_cmd_update (gint argc, gchar **argv) +{ + hashfs_backend_t *backend; + + if (argc == 0) { + } else if (argc == 2) { + backend = hashfs_backends_lookup(argv[0]); + + if (backend) { + hashfs_backend_init(backend); + hashfs_hash_dir(backend, argv[1]); + } + } +} + +gint +main (gint argc, gchar **argv) +{ + hashfs_backend_t *backend; + + hashfs_config_load(); + + if (g_module_supported()) { + hashfs_backends_load(g_build_filename(g_get_user_config_dir(), "hashfs/backends", NULL)); + hashfs_backends_load("/usr/local/lib/hashfs"); + hashfs_backends_load("./_build_/default/src/backends/anidb/"); + } else { + HASHFS_LOG("This platform does not support loading modules"); + + return 0; + } + + if (argc > 1) + hashfs_cmd(main_cmds, argv[1], argc, argv); + else + hashfs_cmd(main_cmds, "help", argc, argv); + + + hashfs_config_save(); + hashfs_backends_destroy(); + + return 0; +} diff --git a/src/hashfs/hashfs.h b/src/hashfs/hashfs.h new file mode 100644 index 0000000..000a121 --- /dev/null +++ b/src/hashfs/hashfs.h @@ -0,0 +1,103 @@ +#ifndef _HASHFS_H +#define _HASHFS_H + +#include <stdio.h> +#include <stdlib.h> +#include <glib.h> +#include <glib/gstdio.h> + +struct hashfs_backend_St; +struct hashfs_backend_desc_St; +struct hashfs_file_St; + +typedef struct hashfs_backend_St hashfs_backend_t; +typedef struct hashfs_backend_desc_St hashfs_backend_desc_t; +typedef struct hashfs_file_St hashfs_file_t; + + +struct hashfs_file_St { + gchar *filename; + gint64 size; +}; + +struct hashfs_backend_St { + gpointer data; + + struct { + gboolean (*init)(hashfs_backend_t *); + void (*file)(hashfs_backend_t *, hashfs_file_t *); + void (*destroy)(hashfs_backend_t *); + } funcs; + + hashfs_backend_desc_t *desc; +}; + +struct hashfs_backend_desc_St { + const gchar *shortname; + const gchar *name; + const gchar *description; + void (*setup_func)(hashfs_backend_t *); +}; + +gchar * hashfs_current_time (void); +gchar * hashfs_basename (gchar *name); + + +GKeyFile * hashfs_config_keyfile (void); +void hashfs_config_load (void); +void hashfs_config_save (void); +gboolean hashfs_config_property_exists (const gchar *group, const gchar *key); +void hashfs_config_property_lookup (const gchar *group, const gchar *key, gchar **out); +void hashfs_config_property_set (const gchar *group, const gchar *key, const gchar *value); + +hashfs_file_t * hashfs_file_new (gchar *filename); +gint hashfs_file_hash_ed2k (hashfs_file_t *file, gchar **out); +gint hashfs_file_prop_get (hashfs_file_t *file, const gchar *key, gchar **out); +void hashfs_file_prop_set (hashfs_file_t *file, const gchar *key, gchar *value); + +hashfs_backend_t * hashfs_backends_lookup (const gchar *name); +hashfs_backend_t * hashfs_backends_get (gint idx); +gint hashfs_backends_count (void); +void hashfs_backends_load (const gchar *path); +void hashfs_backends_destroy (void); + +hashfs_backend_t * hashfs_backend_load (const gchar *path); +void hashfs_backend_init (hashfs_backend_t *backend); +void hashfs_backend_file (hashfs_backend_t *backend, hashfs_file_t *file); +void hashfs_backend_destroy (hashfs_backend_t *backend); + +void hashfs_backend_config_register (hashfs_backend_t *backend, const gchar *key, gchar *defaultval); +void hashfs_backend_config_lookup (hashfs_backend_t *backend, const gchar *key, gchar **out); + +#define HASHFS_BACKEND(shname, name, desc, setupfunc) \ + hashfs_backend_desc_t HASHFS_BACKEND_DESC = { \ + shname, \ + name, \ + desc, \ + (void (*)(hashfs_backend_t *))setupfunc, \ + }; + +#define HASHFS_LOG(fmt, ...) { \ + printf("%s LOG ", hashfs_current_time()); \ + printf(fmt"\n", ## __VA_ARGS__); \ +} + +#define HASHFS_ERROR(fmt, ...) { \ + fprintf(stderr, "ERROR "fmt"\n", ## __VA_ARGS__); \ + exit(EXIT_FAILURE); \ +} + +#ifdef DEBUG + #define HASHFS_DEBUG(fmt, ...) { \ + FILE *fd; \ + fd = g_fopen("/tmp/hashfs_debug.log", "at"); \ + fprintf(fd, "%s DEBUG %s:%d: ", hashfs_current_time(), __FILE__, __LINE__); \ + fprintf(fd, fmt"\n", ## __VA_ARGS__); \ + fclose(fd); \ + } +#else + #define HASHFS_DEBUG(...) +#endif + + +#endif diff --git a/src/anidbfs/anidbfs.c b/src/hashfs/hashfsmount.c similarity index 87% rename from src/anidbfs/anidbfs.c rename to src/hashfs/hashfsmount.c index 48ea97c..7c3885f 100644 --- a/src/anidbfs/anidbfs.c +++ b/src/hashfs/hashfsmount.c @@ -1,17 +1,16 @@ #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <fuse.h> -#include "anidbfs.h" int main(int argc, char *argv[]) { return 0; } diff --git a/src/hashfs/tests/test01.c b/src/hashfs/tests/test01.c new file mode 100644 index 0000000..f1e528b --- /dev/null +++ b/src/hashfs/tests/test01.c @@ -0,0 +1,167 @@ +#include <stdio.h> +#include <malloc.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> + +#include <unistd.h> +#include <sys/mman.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +#include <anidb.h> + +static void +dump_result (anidb_result_t *result) +{ + int n; + char *str; + anidb_dict_t *dict; + + switch (anidb_result_get_type(result)) { + case ANIDB_RESULT_NULL: + printf("<result %p null>\n", result); + break; + + case ANIDB_RESULT_STRING: + anidb_result_get_str(result, &str); + printf("<result %p (string) \"%s\">\n", result, str); + + break; + + case ANIDB_RESULT_NUMBER: + anidb_result_get_int(result, &n); + printf("<result %p (int) \"%d\">\n", result, n); + + break; + + case ANIDB_RESULT_DICT: + printf("<result %p (dict)\n", result); + + for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { + printf(" %s = \"%s\"", dict->key, dict->value); + + if (anidb_dict_next(dict)) + printf(",\n"); + } + + printf(">\n"); + + break; + } +} + + +static void +dump_anime (anidb_session_t *session, char *name) +{ + anidb_result_t *res; + + res = anidb_session_anime_name(session, name); + + if (anidb_result_get_code(res) == ANIDB_ANIME) { + dump_result(res); + } + + anidb_result_unref(res); +} + +static void +dump_animedesc (anidb_session_t *session, int id, int part) +{ + anidb_result_t *res; + + res = anidb_session_animedesc(session, id, part); + + if (anidb_result_get_code(res) == ANIDB_ANIME_DESCRIPTION) { + dump_result(res); + } + + anidb_result_unref(res); +} + +static void +dump_episode (anidb_session_t *session, int id) +{ + anidb_result_t *res; + + res = anidb_session_episode_id(session, id); + + if (anidb_result_get_code(res) == ANIDB_EPISODE) { + dump_result(res); + } + + anidb_result_unref(res); +} + +static void +dump_file (anidb_session_t *session, int id) +{ + anidb_result_t *res; + + res = anidb_session_file_ed2k(session, 44255118, "90033a52db54437dc4a6041348422d4b"); +// res = anidb_session_file_id(session, id); + + if (anidb_result_get_code(res) == ANIDB_FILE) { + dump_result(res); + } + + anidb_result_unref(res); +} + + +static void +dump_group (anidb_session_t *session, char *name) +{ + anidb_result_t *res; + + res = anidb_session_group_name(session, name); + + if (anidb_result_get_code(res) == ANIDB_GROUP) { + dump_result(res); + } + + anidb_result_unref(res); +} + + +int +main (int argc, char *argv[]) +{ + anidb_session_t *session; + anidb_result_t *res; + char *key; + + if (argc < 3) { + printf("Usage: %s <username> <password>\n", argv[0]); + exit(0); + } + + session = anidb_session_new("anidbfs", "1"); + + res = anidb_session_authenticate(session, argv[1], argv[2]); + dump_result(res); + + if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { + if (anidb_result_get_str(res, &key)) { + anidb_session_set_key(session, key); + } + + dump_anime(session, "Neon Genesis Evangelion"); + dump_group(session, "Chrippa Crapsubs"); + dump_animedesc(session, 23, 0); + dump_episode(session, 21346); + dump_file(session, 43698); + + dump_result(anidb_session_logout(session)); + } + + anidb_result_unref(res); + anidb_session_unref(session); + + return 0; +} + + diff --git a/src/anidbfs/util.c b/src/hashfs/util.c similarity index 79% rename from src/anidbfs/util.c rename to src/hashfs/util.c index 32794cd..070532d 100644 --- a/src/anidbfs/util.c +++ b/src/hashfs/util.c @@ -1,34 +1,35 @@ -#include "util.h" + #include <sys/time.h> #include <string.h> #include <time.h> +#include "hashfs.h" -char * -anidbfs_basename (char *name) +gchar * +hashfs_basename (char *name) { const char *base; for (base = name; *name; name++) { if (*name == '/') { base = name + 1; } } return (char *) base; } -char * -anidbfs_current_time (void) +gchar * +hashfs_current_time (void) { char buf[256]; time_t tv; struct tm st; tv = time(NULL); localtime_r(&tv, &st); strftime(buf, sizeof(buf), "%H:%M:%S", &st); return strdup(buf); } diff --git a/src/anidbfs/wscript b/src/hashfs/wscript similarity index 53% rename from src/anidbfs/wscript rename to src/hashfs/wscript index afd0293..27e72f4 100644 --- a/src/anidbfs/wscript +++ b/src/hashfs/wscript @@ -1,49 +1,42 @@ # vim: set fileencoding=utf-8 filetype=python : -anidbfs = ['anidbfs.c', 'util.c'] -anidbfs_update = ['anidbfs-update.c', 'util.c'] +hashfs = ['hashfs.c', 'db.c', 'ed2k.c', 'config.c', 'backend.c', 'util.c'] +hashfsmount = ['hashfsmount.c', 'util.c'] def set_options(opt): pass def configure(conf): - for pkg in ['fuse', 'openssl']: + for pkg in ['fuse', 'glib-2.0', 'gmodule-2.0', 'openssl']: if not conf.check_cfg(package = pkg, args = '--cflags --libs', uselib_store = pkg): - return False - - for lib in ['m']: - if not conf.check_cc(lib = lib, uselib_store = lib): - return False - - - return True + conf.fatal('Unable to find required library') def build(bld): import Options defines = [] if Options.options.debug: defines += ['DEBUG'] obj = bld.new_task_gen( features = 'cc cprogram', - source = anidbfs, - target = 'anidbfs', - uselib = 'fuse', + source = hashfs, + target = 'hashfs', install_path = '${PREFIX}/bin', - ccflags = ['-std=gnu99'], + uselib = 'glib-2.0 gmodule-2.0 openssl', + uselib_local = 'anidb', + ccflags = ['-std=gnu99', '-g'], defines = defines ) obj = bld.new_task_gen( features = 'cc cprogram', - source = anidbfs_update, - target = 'anidbfs-update', - includes = '. ../libanidb', + source = hashfsmount, + target = 'hashfsmount', + uselib = 'fuse glib-2.0', install_path = '${PREFIX}/bin', - uselib = 'openssl m', - uselib_local = 'anidb', - ccflags = ['-std=gnu99'], + ccflags = ['-std=gnu99', '-g'], defines = defines ) + diff --git a/src/libanidb/anidb.c b/src/lib/libanidb/anidb.c similarity index 96% rename from src/libanidb/anidb.c rename to src/lib/libanidb/anidb.c index 9f61e28..ee83a49 100644 --- a/src/libanidb/anidb.c +++ b/src/lib/libanidb/anidb.c @@ -1,673 +1,682 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } - static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; // printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; // printf("recv: '%s'\n", out); } anidb_session_t * -anidb_session_new (char *name, char *version) +anidb_session_new (char *name, char *version, int localport) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } - local.sin_addr.s_addr = INADDR_ANY; - local.sin_family = AF_INET; - local.sin_port = htons(9999); + if (localport > 0) { + local.sin_addr.s_addr = INADDR_ANY; + local.sin_family = AF_INET; + local.sin_port = htons(localport); - rval = bind(sock, (struct sockaddr *) &local, - sizeof(struct sockaddr_in)); + rval = bind(sock, (struct sockaddr *) &local, + sizeof(struct sockaddr_in)); - if (rval < 0) { - ANIDB_ERROR("Unable to bind local port 0.0.0.0:9999"); + if (rval < 0) { + ANIDB_ERROR("Unable to bind local port 0.0.0.0:%d", localport); + } } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; session->clientname = name; session->clientversion = version; session->key = NULL; anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); if (session->key) free(session->key); free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { session->key = (char *) strdup(key); } +int +anidb_session_is_logged_in (anidb_session_t *session) +{ + if (session->key) + return 1; + + return 0; +} + static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; - sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, double size, char *ed2k) { anidb_result_t *res; char siz[50]; sprintf(siz, "%0.0f", size); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { dict->key = key; dict->value = value; } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, char *string) { result->type = ANIDB_RESULT_STRING; result->value.string = string; } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, char *key, char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) diff --git a/src/libanidb/anidb.h b/src/lib/libanidb/anidb.h similarity index 98% rename from src/libanidb/anidb.h rename to src/lib/libanidb/anidb.h index 703ae34..02b59cb 100644 --- a/src/libanidb/anidb.h +++ b/src/lib/libanidb/anidb.h @@ -1,306 +1,309 @@ #ifndef _LIBANIDB_H #define _LIBANIDB_H +#include <sys/time.h> + enum anidb_result_type { ANIDB_RESULT_NULL, ANIDB_RESULT_NUMBER, ANIDB_RESULT_STRING, ANIDB_RESULT_DICT }; struct anidb_session_St { int socket; char *clientname; char *clientversion; char *key; int refcount; }; struct anidb_dict_St { char *key; char *value; struct anidb_dict_St *next; int refcount; }; struct anidb_result_St { struct anidb_error_St *error; int code; enum anidb_result_type type; union { int number; char *string; struct anidb_dict_St *dict; } value; int refcount; }; struct anidb_result_handler_St { int code; void (*func)(struct anidb_result_St *, char *); }; /* Types */ typedef enum anidb_result_type anidb_result_type_t; typedef struct anidb_session_St anidb_session_t; typedef struct anidb_dict_St anidb_dict_t; typedef struct anidb_result_St anidb_result_t; typedef struct anidb_result_handler_St anidb_result_handler_t; typedef struct anidb_error_St anidb_error_t; /* Session */ -anidb_session_t * anidb_session_new (char *name, char *version); +anidb_session_t * anidb_session_new (char *name, char *version, int localport); /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password); /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session); /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name); anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id); /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int ep); /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep); anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep); /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, double size, char *ed2k); /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name); /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id); /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session); /* VOTE */ /* RANDOM */ /* MYLISTEXPORT */ /* PING */ anidb_result_t * anidb_session_ping (anidb_session_t *session); /* VERSION */ anidb_result_t * anidb_session_uptime (anidb_session_t *session); /* UPTIME */ anidb_result_t * anidb_session_version (anidb_session_t *session); /* ENCODING */ /* SENDMSG */ /* USER */ void anidb_session_set_key (anidb_session_t *session, char *key); +int anidb_session_is_logged_in (anidb_session_t *session); void anidb_session_ref (anidb_session_t *session); void anidb_session_unref (anidb_session_t *session); /* Dict */ anidb_dict_t * anidb_dict_new (void); anidb_dict_t * anidb_dict_next (anidb_dict_t *dict); void anidb_dict_ref (anidb_dict_t *dict); void anidb_dict_unref (anidb_dict_t *dict); void anidb_dict_set (anidb_dict_t *dict, char *key, char *value); int anidb_dict_get (anidb_dict_t *dict, char **out); /* Result */ anidb_result_t * anidb_result_new (int code); void anidb_result_ref (anidb_result_t *result); void anidb_result_unref (anidb_result_t *result); void anidb_result_set_str (anidb_result_t *result, char *string); void anidb_result_set_int (anidb_result_t *result, int number); void anidb_result_dict_set (anidb_result_t *result, char *key, char *value); anidb_result_type_t anidb_result_get_type (anidb_result_t *result); int anidb_result_get_code (anidb_result_t *result); int anidb_result_get_str (anidb_result_t *result, char **out); int anidb_result_get_int (anidb_result_t *result, int *out); int anidb_result_dict_get (anidb_result_t *result, char *key, char **out); anidb_dict_t * anidb_result_get_dict (anidb_result_t *result); #define ANIDB_SERVER_HOST "api.anidb.net" #define ANIDB_SERVER_PORT 9000 #define ANIDB_PROTO_VERSION "3" /* Positive responses 2XX */ #define ANIDB_LOGIN_ACCEPTED 200 #define ANIDB_LOGIN_ACCEPTED_NEW_VER 201 #define ANIDB_LOGGED_OUT 203 #define ANIDB_RESOURCE 205 #define ANIDB_STATS 206 #define ANIDB_TOP 207 #define ANIDB_UPTIME 208 #define ANIDB_ENCRYPTION_ENABLED 209 #define ANIDB_MYLIST_ENTRY_ADDED 210 #define ANIDB_MYLIST_ENTRY_DELETED 211 #define ANIDB_ADDED_FILE 214 #define ANIDB_ADDED_STREAM 215 #define ANIDB_ENCODING_CHANGED 219 #define ANIDB_FILE 220 #define ANIDB_MYLIST 221 #define ANIDB_MYLIST_STATS 222 #define ANIDB_ANIME 230 #define ANIDB_ANIME_BEST_MATCH 231 #define ANIDB_RANDOMANIME 232 #define ANIDB_ANIME_DESCRIPTION 233 #define ANIDB_EPISODE 240 #define ANIDB_PRODUCER 245 #define ANIDB_GROUP 250 #define ANIDB_BUDDY_LIST 253 #define ANIDB_BUDDY_STATE 254 #define ANIDB_BUDDY_ADDED 255 #define ANIDB_BUDDY_DELETED 256 #define ANIDB_BUDDY_ACCEPTED 257 #define ANIDB_BUDDY_DENIED 258 #define ANIDB_VOTED 260 #define ANIDB_VOTE_FOUND 261 #define ANIDB_VOTE_UPDATED 262 #define ANIDB_VOTE_REVOKED 263 #define ANIDB_NOTIFICATION_ENABLED 270 #define ANIDB_NOTIFICATION_NOTIFY 271 #define ANIDB_NOTIFICATION_MESSAGE 272 #define ANIDB_NOTIFICATION_BUDDY 273 #define ANIDB_NOTIFICATION_SHUTDOWN 274 #define ANIDB_PUSHACK_CONFIRMED 280 #define ANIDB_NOTIFYACK_SUCCESSFUL_M 281 #define ANIDB_NOTIFYACK_SUCCESSFUL_N 282 #define ANIDB_NOTIFICATION 290 #define ANIDB_NOTIFYLIST 291 #define ANIDB_NOTIFYGET_MESSAGE 292 #define ANIDB_NOTIFYGET_NOTIFY 293 #define ANIDB_SENDMSG_SUCCESSFUL 294 #define ANIDB_USER 295 /* Affirmative/Negative responses 3XX */ #define ANIDB_PONG 300 #define ANIDB_AUTHPONG 301 #define ANIDB_NO_SUCH_RESOURCE 305 #define ANIDB_API_PASSWORD_NOT_DEFINED 309 #define ANIDB_FILE_ALREADY_IN_MYLIST 310 #define ANIDB_MYLIST_ENTRY_EDITED 311 #define ANIDB_MULTIPLE_MYLIST_ENTRIES 312 #define ANIDB_SIZE_HASH_EXISTS 314 #define ANIDB_INVALID_DATA 315 #define ANIDB_STREAMNOID_USED 316 #define ANIDB_NO_SUCH_FILE 320 #define ANIDB_NO_SUCH_ENTRY 321 #define ANIDB_MULTIPLE_FILES_FOUND 322 #define ANIDB_NO_SUCH_ANIME 330 #define ANIDB_NO_SUCH_ANIME_DESCRIPTION 333 #define ANIDB_NO_SUCH_EPISODE 340 #define ANIDB_NO_SUCH_PRODUCER 345 #define ANIDB_NO_SUCH_GROUP 350 #define ANIDB_BUDDY_ALREADY_ADDED 355 #define ANIDB_NO_SUCH_BUDDY 356 #define ANIDB_BUDDY_ALREADY_ACCEPTED 357 #define ANIDB_BUDDY_ALREADY_DENIED 358 #define ANIDB_NO_SUCH_VOTE 360 #define ANIDB_INVALID_VOTE_TYPE 361 #define ANIDB_INVALID_VOTE_VALUE 362 #define ANIDB_PERMVOTE_NOT_ALLOWED 363 #define ANIDB_ALREADY_PERMVOTED 364 #define ANIDB_NOTIFICATION_DISABLED 370 #define ANIDB_NO_SUCH_PACKET_PENDING 380 #define ANIDB_NO_SUCH_ENTRY_M 381 #define ANIDB_NO_SUCH_ENTRY_N 382 #define ANIDB_NO_SUCH_MESSAGE 392 #define ANIDB_NO_SUCH_NOTIFY 393 #define ANIDB_NO_SUCH_USER 394 /* Negative responses 4XX */ #define ANIDB_NOT_LOGGED_IN 403 #define ANIDB_NO_SUCH_MYLIST_FILE 410 #define ANIDB_NO_SUCH_MYLIST_ENTRY 411 /* Client side failure 5XX */ #define ANIDB_LOGIN_FAILED 500 #define ANIDB_LOGIN_FIRST 501 #define ANIDB_ACCESS_DENIED 502 #define ANIDB_CLIENT_VERSION_OUTDATED 503 #define ANIDB_CLIENT_BANNED 504 #define ANIDB_ILLEGAL_INPUT_OR_ACCESS_DENIED 505 #define ANIDB_INVALID_SESSION 506 #define ANIDB_NO_SUCH_ENCRYPTION_TYPE 509 #define ANIDB_ENCODING_NOT_SUPPORTED 519 #define ANIDB_BANNED 555 #define ANIDB_UNKNOWN_COMMAND 598 /* Server side failure 6XX */ #define ANIDB_INTERNAL_SERVER_ERROR 600 #define ANIDB_ANIDB_OUT_OF_SERVICE 601 #define ANIDB_SERVER_BUSY 602 #define ANIDB_API_VIOLATION 666 #endif diff --git a/src/libanidb/handlers.c b/src/lib/libanidb/handlers.c similarity index 100% rename from src/libanidb/handlers.c rename to src/lib/libanidb/handlers.c diff --git a/src/libanidb/util.h b/src/lib/libanidb/util.h similarity index 100% rename from src/libanidb/util.h rename to src/lib/libanidb/util.h diff --git a/src/libanidb/wscript b/src/lib/libanidb/wscript similarity index 81% rename from src/libanidb/wscript rename to src/lib/libanidb/wscript index a37c19a..56d2e76 100644 --- a/src/libanidb/wscript +++ b/src/lib/libanidb/wscript @@ -1,26 +1,27 @@ # vim: set fileencoding=utf-8 filetype=python : files = ['handlers.c', 'anidb.c'] def set_options(opt): pass def configure(conf): - return True + pass def build(bld): import Options defines = [] if Options.options.debug: defines += ['DEBUG'] obj = bld.new_task_gen( - features = 'cc cshlib', + features = 'cc cstaticlib', target = 'anidb', source = files, defines = defines, ccflags = ['-std=gnu99', '-g'], - install_path = '${PREFIX}/lib' + install_path = False, + export_incdirs = '.' ) diff --git a/test.sh b/test.sh deleted file mode 100755 index 8fcd566..0000000 --- a/test.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -export LD_LIBRARY_PATH=./_build_/default/src/libanidb/ - -./_build_/default/src/anidbfs/anidbfs-update fusetest testuser /storage/ch01/anime/hdtv diff --git a/waf b/waf index da49e8d..549a346 100755 Binary files a/waf and b/waf differ diff --git a/wscript b/wscript index de5886b..aed32c0 100644 --- a/wscript +++ b/wscript @@ -1,27 +1,36 @@ # vim: set fileencoding=utf-8 filetype=python : from logging import fatal, info import os srcdir = '.' blddir = '_build_' +bckenddir = 'src/backends' + +def is_backend(x): + return os.path.exists(os.path.join(bckenddir, x, 'wscript')) + +hashfs = ['src/hashfs'] +libs = ['src/lib/libanidb'] +backends = [os.path.join(bckenddir, p) for p in os.listdir(bckenddir) if is_backend(p)] + +subdirs = hashfs + libs + backends -subdirs = ['src/libanidb', 'src/anidbfs'] def set_options(opt): opt.add_option('--debug', action = 'store_true', default = True, help = 'Enable debug') for dir in subdirs: opt.sub_options(dir) def configure(conf): import Options conf.check_tool('gcc') for dir in subdirs: conf.sub_config(dir) def build(bld): bld.add_subdirs(subdirs)
chrippa/hashfs
1bd693f4b65c5ca718227c7dc46d7be62f578a9d
Fix hashing of files larger than 2GB.
diff --git a/src/anidbfs/anidbfs-update.c b/src/anidbfs/anidbfs-update.c index d71889f..77c15b5 100644 --- a/src/anidbfs/anidbfs-update.c +++ b/src/anidbfs/anidbfs-update.c @@ -1,248 +1,255 @@ +#define _FILE_OFFSET_BITS 64 +#define _LARGEFILE64_SOURCE +#define BLOCKSIZE (9500*1024) + #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> -#define __USE_LARGEFILE64 -#define BLOCKSIZE (9500*1024) - #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> +#include <math.h> #include <openssl/md4.h> #include <anidb.h> #include "util.h" -static void anidbfs_hash_file (anidb_session_t *session, char *path); +static void anidbfs_hash_file (anidb_session_t *session, char *path, struct stat *info); static void anidbfs_hash_dir (anidb_session_t *session, char *path); -static int anidbfs_dir_list (const char *name, const struct stat *status, int flag); -static unsigned long get_file_size (int fd); static char * ed2k_hash (char *filename); static void dump_result (anidb_result_t *result); static const char hexdigits[16] = "0123456789abcdef"; - -static unsigned long -get_file_size (int fd) -{ - struct stat64 info; - - fstat64(fd, &info); - - return (unsigned long) info.st_size; -} - static char * ed2k_hash (char *filename) { - unsigned long size; - int fd, b, j, blocks; - unsigned char *parthashes, *ed2k_hash; - char *ed2k_hash_str; + int fd, blocks; + off_t size; + struct stat stat; + char *hash_str; + unsigned char *hashes, *hash; if ((fd = open(filename, O_RDONLY)) < 0) { ANIDBFS_DEBUG("Failed to open file (%s)", filename); + return NULL; } - size = get_file_size(fd); + if (fstat(fd, &stat) < 0) { + ANIDBFS_DEBUG("Failed to stat file (%s)", filename); - if (size <= 0) { - ANIDBFS_DEBUG("Error getting filesize (%s)", filename); return NULL; } - blocks = size / BLOCKSIZE; + size = stat.st_size; - if (size % BLOCKSIZE > 0) + blocks = (double) size / (double) BLOCKSIZE; + + if (fmod((double) size, (double) BLOCKSIZE) > 0) blocks++; - ed2k_hash = (unsigned char *) malloc(16); - ed2k_hash_str = (char *) malloc(33); - parthashes = (unsigned char *) malloc(blocks * 16); + hash = (unsigned char *) malloc(16); + hash_str = (char *) malloc(33); + hashes = (unsigned char *) malloc(blocks * 16); - if ((!parthashes) || (!ed2k_hash) || (!ed2k_hash_str) || (!filename)) { + if (!hash || !hashes || !hash_str || !filename) { ANIDBFS_DEBUG("Failed to allocate memory (%s)", filename); + return NULL; } - for (b = 0; b < blocks; b++) { - MD4_CTX context; - int len, start; - void *map; + for (int b = 0; b < blocks; b++) { + MD4_CTX ctx; + int len; + void *data; + off_t offset; len = BLOCKSIZE; - if (b == blocks - 1) - len = size % BLOCKSIZE; + if (b == blocks - 1) /* Last block is smaller than BLOCKSIZE */ + len = ceil(fmod((double) size, (double) BLOCKSIZE)); - start = b * BLOCKSIZE; - map = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, b * BLOCKSIZE); + offset = (off_t) ((double) b * (double) BLOCKSIZE); - if (map == NULL) { - ANIDBFS_DEBUG("mmap failed (%s)", filename); + data = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, offset); + if (!data) { + ANIDBFS_DEBUG("mmap failed to read data (%s)", filename); + return NULL; } - MD4_Init(&context); - MD4_Update(&context, map, len); - MD4_Final(parthashes + (b * 16), &context); - - munmap(map, len); + MD4_Init(&ctx); + MD4_Update(&ctx, data, len); + MD4_Final(hashes + (b * 16), &ctx); -/* int percent = (int) (((float) (b+1) / (float) blocks) * 100); - ANIDBFS_DEBUG("Hashing %s %d%%", filename, percent);*/ + munmap(data, len); } close(fd); + /* If we have hashed more than one block, + run MD4 on all the previous hashes */ if (blocks > 1) { - MD4_CTX context; + MD4_CTX ctx; - MD4_Init(&context); - MD4_Update(&context, parthashes, 16 * b); - MD4_Final(ed2k_hash, &context); + MD4_Init(&ctx); + MD4_Update(&ctx, hashes, 16 * blocks); + MD4_Final(hash, &ctx); } else { - memcpy(ed2k_hash, parthashes, 16); + memcpy(hash, hashes, 16); } - memset(ed2k_hash_str, 0x00, 33 * sizeof(char)); - for (j = 0; j < 16; j++) { - ed2k_hash_str[(j<<1)] = hexdigits[(((ed2k_hash[j]) & 0xf0) >> 4)]; - ed2k_hash_str[(j<<1)+1] = hexdigits[(((ed2k_hash[j]) & 0x0f))]; + /* Convert hash to hex string format */ + memset(hash_str, 0x00, 33 * sizeof(char)); + for (int i = 0; i < 16; i++) { + hash_str[(i<<1)] = hexdigits[(((hash[i]) & 0xf0) >> 4)]; + hash_str[(i<<1)+1] = hexdigits[(((hash[i]) & 0x0f))]; } - free(ed2k_hash); - free(parthashes); + free(hash); + free(hashes); - return ed2k_hash_str; + return hash_str; } static void dump_result (anidb_result_t *result) { int n; char *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: ANIDBFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); ANIDBFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); ANIDBFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: ANIDBFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { ANIDBFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); } - ANIDBFS_DEBUG(">\n"); + ANIDBFS_DEBUG(">"); break; } } static void -anidbfs_hash_file (anidb_session_t *session, char *path) +anidbfs_hash_file (anidb_session_t *session, char *path, struct stat *info) { char *hash; ANIDBFS_LOG("Hashing file: %s", anidbfs_basename(path)); hash = ed2k_hash(path); - ANIDBFS_DEBUG("Hash: %s", hash) + if (hash) { + ANIDBFS_DEBUG("Hash: %s", hash) - free(hash); + anidb_result_t *res; + + res = anidb_session_file_ed2k(session, (double) info->st_size, hash); + + dump_result(res); + + anidb_result_unref(res); + + free(hash); + } } static void anidbfs_hash_dir (anidb_session_t *session, char *path) { DIR *dir; char fullpath[9999]; - struct stat64 info; + struct stat info; struct dirent *entry; ANIDBFS_LOG("Hashing dir: %s", path); dir = opendir(path); if (dir) { while (entry = readdir(dir)) { - if (entry->d_name && entry->d_name[0] != '.') { - sprintf(fullpath, "%s%s%s", path, - (path[strlen(path)-1]=='/') ? "" : "/", - entry->d_name); - - stat64(fullpath, &info); - - if (S_ISDIR(info.st_mode)) { - anidbfs_hash_dir(session, fullpath); - } else if (S_ISREG(info.st_mode) || S_ISLNK(info.st_mode)) { - anidbfs_hash_file(session, fullpath); - } + + if (!strcmp (entry->d_name, ".") || !strcmp (entry->d_name, "..")) + continue; + + sprintf(fullpath, "%s%s%s", path, + (path[strlen(path)-1] == '/') ? "" : "/", + entry->d_name); + + stat(fullpath, &info); + + if (S_ISDIR(info.st_mode)) { + anidbfs_hash_dir(session, fullpath); + } else if (S_ISREG(info.st_mode) || S_ISLNK(info.st_mode)) { + anidbfs_hash_file(session, fullpath, &info); } } closedir(dir); } } int main (int argc, char *argv[]) { anidb_session_t *session; anidb_result_t *res; char *key; if (argc < 4) { - printf("Usage: %s <username> <password> <path>\n", argv[0]); + fprintf(stderr, "Usage: %s <username> <password> <path>\n", argv[0]); exit(0); } - session = anidb_session_new("anidbfs", "1"); + session = anidb_session_new("anidbfuse", "1"); ANIDBFS_DEBUG("Connecting to AniDB"); res = anidb_session_authenticate(session, argv[1], argv[2]); dump_result(res); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); } anidbfs_hash_dir(session, argv[3]); ANIDBFS_DEBUG("Logging out"); anidb_session_logout(session); } anidb_result_unref(res); anidb_session_unref(session); return 1; } diff --git a/src/anidbfs/wscript b/src/anidbfs/wscript index 043fea0..afd0293 100644 --- a/src/anidbfs/wscript +++ b/src/anidbfs/wscript @@ -1,44 +1,49 @@ # vim: set fileencoding=utf-8 filetype=python : anidbfs = ['anidbfs.c', 'util.c'] anidbfs_update = ['anidbfs-update.c', 'util.c'] def set_options(opt): pass def configure(conf): for pkg in ['fuse', 'openssl']: if not conf.check_cfg(package = pkg, args = '--cflags --libs', uselib_store = pkg): return False + for lib in ['m']: + if not conf.check_cc(lib = lib, uselib_store = lib): + return False + + return True def build(bld): import Options defines = [] if Options.options.debug: defines += ['DEBUG'] obj = bld.new_task_gen( features = 'cc cprogram', source = anidbfs, target = 'anidbfs', uselib = 'fuse', install_path = '${PREFIX}/bin', ccflags = ['-std=gnu99'], defines = defines ) obj = bld.new_task_gen( features = 'cc cprogram', source = anidbfs_update, target = 'anidbfs-update', includes = '. ../libanidb', install_path = '${PREFIX}/bin', - uselib = 'openssl', + uselib = 'openssl m', uselib_local = 'anidb', ccflags = ['-std=gnu99'], defines = defines ) diff --git a/src/libanidb/anidb.c b/src/libanidb/anidb.c index eeaa694..9f61e28 100644 --- a/src/libanidb/anidb.c +++ b/src/libanidb/anidb.c @@ -1,705 +1,705 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; // printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; // printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(9999); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:9999"); } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; session->clientname = name; session->clientversion = version; session->key = NULL; anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); if (session->key) free(session->key); free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { session->key = (char *) strdup(key); } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * -anidb_session_file_ed2k (anidb_session_t *session, int size, char *ed2k) +anidb_session_file_ed2k (anidb_session_t *session, double size, char *ed2k) { anidb_result_t *res; - char siz[20]; + char siz[50]; - sprintf(siz, "%d", size); + sprintf(siz, "%0.0f", size); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { dict->key = key; dict->value = value; } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, char *string) { result->type = ANIDB_RESULT_STRING; result->value.string = string; } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, char *key, char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } int anidb_result_dict_get (anidb_result_t *result, char *key, char **out) { anidb_dict_t *dict; if (result->type != ANIDB_RESULT_DICT) return 0; for (dict = result->value.dict; dict; dict = dict->next) { if (!strcmp(dict->key, key)) { return anidb_dict_get(dict, out); } } return 0; } anidb_dict_t * anidb_result_get_dict (anidb_result_t *result) { if (result->type != ANIDB_RESULT_DICT) return NULL; return result->value.dict; } diff --git a/src/libanidb/anidb.h b/src/libanidb/anidb.h index 075fded..703ae34 100644 --- a/src/libanidb/anidb.h +++ b/src/libanidb/anidb.h @@ -1,322 +1,306 @@ #ifndef _LIBANIDB_H #define _LIBANIDB_H enum anidb_result_type { ANIDB_RESULT_NULL, ANIDB_RESULT_NUMBER, ANIDB_RESULT_STRING, ANIDB_RESULT_DICT }; struct anidb_session_St { int socket; char *clientname; char *clientversion; char *key; int refcount; }; -struct anidb_error_St -{ - int errcode; - char *errmsg; -}; - struct anidb_dict_St { char *key; char *value; struct anidb_dict_St *next; int refcount; }; struct anidb_result_St { struct anidb_error_St *error; int code; enum anidb_result_type type; union { int number; char *string; struct anidb_dict_St *dict; } value; int refcount; }; struct anidb_result_handler_St { int code; void (*func)(struct anidb_result_St *, char *); }; /* Types */ typedef enum anidb_result_type anidb_result_type_t; typedef struct anidb_session_St anidb_session_t; typedef struct anidb_dict_St anidb_dict_t; typedef struct anidb_result_St anidb_result_t; typedef struct anidb_result_handler_St anidb_result_handler_t; typedef struct anidb_error_St anidb_error_t; /* Session */ anidb_session_t * anidb_session_new (char *name, char *version); /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password); /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session); /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name); anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id); /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int ep); /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep); anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep); /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id); -anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int size, char *ed2k); +anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, double size, char *ed2k); /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name); /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id); /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id); anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session); /* VOTE */ /* RANDOM */ /* MYLISTEXPORT */ /* PING */ anidb_result_t * anidb_session_ping (anidb_session_t *session); /* VERSION */ anidb_result_t * anidb_session_uptime (anidb_session_t *session); /* UPTIME */ anidb_result_t * anidb_session_version (anidb_session_t *session); /* ENCODING */ /* SENDMSG */ /* USER */ void anidb_session_set_key (anidb_session_t *session, char *key); void anidb_session_ref (anidb_session_t *session); void anidb_session_unref (anidb_session_t *session); /* Dict */ anidb_dict_t * anidb_dict_new (void); anidb_dict_t * anidb_dict_next (anidb_dict_t *dict); void anidb_dict_ref (anidb_dict_t *dict); void anidb_dict_unref (anidb_dict_t *dict); void anidb_dict_set (anidb_dict_t *dict, char *key, char *value); int anidb_dict_get (anidb_dict_t *dict, char **out); /* Result */ anidb_result_t * anidb_result_new (int code); void anidb_result_ref (anidb_result_t *result); void anidb_result_unref (anidb_result_t *result); void anidb_result_set_str (anidb_result_t *result, char *string); void anidb_result_set_int (anidb_result_t *result, int number); void anidb_result_dict_set (anidb_result_t *result, char *key, char *value); anidb_result_type_t anidb_result_get_type (anidb_result_t *result); int anidb_result_get_code (anidb_result_t *result); int anidb_result_get_str (anidb_result_t *result, char **out); int anidb_result_get_int (anidb_result_t *result, int *out); int anidb_result_dict_get (anidb_result_t *result, char *key, char **out); anidb_dict_t * anidb_result_get_dict (anidb_result_t *result); -/* Error */ -anidb_error_t * anidb_error_new (void); -void anidb_error_get_code (anidb_error_t *error, int *out); -void anidb_error_get_str (anidb_error_t *error, char *out); -void anidb_error_set_code (anidb_error_t *error, int code); -void anidb_error_set_str (anidb_error_t *error, char *str); -void anidb_session_ref (anidb_session_t *session); -void anidb_session_unref (anidb_session_t *session); - - #define ANIDB_SERVER_HOST "api.anidb.net" #define ANIDB_SERVER_PORT 9000 #define ANIDB_PROTO_VERSION "3" /* Positive responses 2XX */ #define ANIDB_LOGIN_ACCEPTED 200 #define ANIDB_LOGIN_ACCEPTED_NEW_VER 201 #define ANIDB_LOGGED_OUT 203 #define ANIDB_RESOURCE 205 #define ANIDB_STATS 206 #define ANIDB_TOP 207 #define ANIDB_UPTIME 208 #define ANIDB_ENCRYPTION_ENABLED 209 #define ANIDB_MYLIST_ENTRY_ADDED 210 #define ANIDB_MYLIST_ENTRY_DELETED 211 #define ANIDB_ADDED_FILE 214 #define ANIDB_ADDED_STREAM 215 #define ANIDB_ENCODING_CHANGED 219 #define ANIDB_FILE 220 #define ANIDB_MYLIST 221 #define ANIDB_MYLIST_STATS 222 #define ANIDB_ANIME 230 #define ANIDB_ANIME_BEST_MATCH 231 #define ANIDB_RANDOMANIME 232 #define ANIDB_ANIME_DESCRIPTION 233 #define ANIDB_EPISODE 240 #define ANIDB_PRODUCER 245 #define ANIDB_GROUP 250 #define ANIDB_BUDDY_LIST 253 #define ANIDB_BUDDY_STATE 254 #define ANIDB_BUDDY_ADDED 255 #define ANIDB_BUDDY_DELETED 256 #define ANIDB_BUDDY_ACCEPTED 257 #define ANIDB_BUDDY_DENIED 258 #define ANIDB_VOTED 260 #define ANIDB_VOTE_FOUND 261 #define ANIDB_VOTE_UPDATED 262 #define ANIDB_VOTE_REVOKED 263 #define ANIDB_NOTIFICATION_ENABLED 270 #define ANIDB_NOTIFICATION_NOTIFY 271 #define ANIDB_NOTIFICATION_MESSAGE 272 #define ANIDB_NOTIFICATION_BUDDY 273 #define ANIDB_NOTIFICATION_SHUTDOWN 274 #define ANIDB_PUSHACK_CONFIRMED 280 #define ANIDB_NOTIFYACK_SUCCESSFUL_M 281 #define ANIDB_NOTIFYACK_SUCCESSFUL_N 282 #define ANIDB_NOTIFICATION 290 #define ANIDB_NOTIFYLIST 291 #define ANIDB_NOTIFYGET_MESSAGE 292 #define ANIDB_NOTIFYGET_NOTIFY 293 #define ANIDB_SENDMSG_SUCCESSFUL 294 #define ANIDB_USER 295 /* Affirmative/Negative responses 3XX */ #define ANIDB_PONG 300 #define ANIDB_AUTHPONG 301 #define ANIDB_NO_SUCH_RESOURCE 305 #define ANIDB_API_PASSWORD_NOT_DEFINED 309 #define ANIDB_FILE_ALREADY_IN_MYLIST 310 #define ANIDB_MYLIST_ENTRY_EDITED 311 #define ANIDB_MULTIPLE_MYLIST_ENTRIES 312 #define ANIDB_SIZE_HASH_EXISTS 314 #define ANIDB_INVALID_DATA 315 #define ANIDB_STREAMNOID_USED 316 #define ANIDB_NO_SUCH_FILE 320 #define ANIDB_NO_SUCH_ENTRY 321 #define ANIDB_MULTIPLE_FILES_FOUND 322 #define ANIDB_NO_SUCH_ANIME 330 #define ANIDB_NO_SUCH_ANIME_DESCRIPTION 333 #define ANIDB_NO_SUCH_EPISODE 340 #define ANIDB_NO_SUCH_PRODUCER 345 #define ANIDB_NO_SUCH_GROUP 350 #define ANIDB_BUDDY_ALREADY_ADDED 355 #define ANIDB_NO_SUCH_BUDDY 356 #define ANIDB_BUDDY_ALREADY_ACCEPTED 357 #define ANIDB_BUDDY_ALREADY_DENIED 358 #define ANIDB_NO_SUCH_VOTE 360 #define ANIDB_INVALID_VOTE_TYPE 361 #define ANIDB_INVALID_VOTE_VALUE 362 #define ANIDB_PERMVOTE_NOT_ALLOWED 363 #define ANIDB_ALREADY_PERMVOTED 364 #define ANIDB_NOTIFICATION_DISABLED 370 #define ANIDB_NO_SUCH_PACKET_PENDING 380 #define ANIDB_NO_SUCH_ENTRY_M 381 #define ANIDB_NO_SUCH_ENTRY_N 382 #define ANIDB_NO_SUCH_MESSAGE 392 #define ANIDB_NO_SUCH_NOTIFY 393 #define ANIDB_NO_SUCH_USER 394 /* Negative responses 4XX */ #define ANIDB_NOT_LOGGED_IN 403 #define ANIDB_NO_SUCH_MYLIST_FILE 410 #define ANIDB_NO_SUCH_MYLIST_ENTRY 411 /* Client side failure 5XX */ #define ANIDB_LOGIN_FAILED 500 #define ANIDB_LOGIN_FIRST 501 #define ANIDB_ACCESS_DENIED 502 #define ANIDB_CLIENT_VERSION_OUTDATED 503 #define ANIDB_CLIENT_BANNED 504 #define ANIDB_ILLEGAL_INPUT_OR_ACCESS_DENIED 505 #define ANIDB_INVALID_SESSION 506 #define ANIDB_NO_SUCH_ENCRYPTION_TYPE 509 #define ANIDB_ENCODING_NOT_SUPPORTED 519 #define ANIDB_BANNED 555 #define ANIDB_UNKNOWN_COMMAND 598 /* Server side failure 6XX */ #define ANIDB_INTERNAL_SERVER_ERROR 600 #define ANIDB_ANIDB_OUT_OF_SERVICE 601 #define ANIDB_SERVER_BUSY 602 #define ANIDB_API_VIOLATION 666 #endif
chrippa/hashfs
788b4b41f85af14ca54326ce53695d376b644848
Started work on the real anidbfs-update.
diff --git a/src/anidbfs/anidbfs-update.c b/src/anidbfs/anidbfs-update.c index edc008a..d71889f 100644 --- a/src/anidbfs/anidbfs-update.c +++ b/src/anidbfs/anidbfs-update.c @@ -1,155 +1,248 @@ #include <stdio.h> +#include <malloc.h> #include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <errno.h> + +#define __USE_LARGEFILE64 +#define BLOCKSIZE (9500*1024) + +#include <unistd.h> +#include <sys/mman.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <dirent.h> +#include <openssl/md4.h> #include <anidb.h> -void +#include "util.h" + +static void anidbfs_hash_file (anidb_session_t *session, char *path); +static void anidbfs_hash_dir (anidb_session_t *session, char *path); +static int anidbfs_dir_list (const char *name, const struct stat *status, int flag); + +static unsigned long get_file_size (int fd); +static char * ed2k_hash (char *filename); +static void dump_result (anidb_result_t *result); +static const char hexdigits[16] = "0123456789abcdef"; + + +static unsigned long +get_file_size (int fd) +{ + struct stat64 info; + + fstat64(fd, &info); + + return (unsigned long) info.st_size; +} + +static char * +ed2k_hash (char *filename) +{ + unsigned long size; + int fd, b, j, blocks; + unsigned char *parthashes, *ed2k_hash; + char *ed2k_hash_str; + + if ((fd = open(filename, O_RDONLY)) < 0) { + ANIDBFS_DEBUG("Failed to open file (%s)", filename); + return NULL; + } + + size = get_file_size(fd); + + if (size <= 0) { + ANIDBFS_DEBUG("Error getting filesize (%s)", filename); + return NULL; + } + + blocks = size / BLOCKSIZE; + + if (size % BLOCKSIZE > 0) + blocks++; + + ed2k_hash = (unsigned char *) malloc(16); + ed2k_hash_str = (char *) malloc(33); + parthashes = (unsigned char *) malloc(blocks * 16); + + if ((!parthashes) || (!ed2k_hash) || (!ed2k_hash_str) || (!filename)) { + ANIDBFS_DEBUG("Failed to allocate memory (%s)", filename); + return NULL; + } + + for (b = 0; b < blocks; b++) { + MD4_CTX context; + int len, start; + void *map; + + len = BLOCKSIZE; + if (b == blocks - 1) + len = size % BLOCKSIZE; + + start = b * BLOCKSIZE; + map = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, b * BLOCKSIZE); + + if (map == NULL) { + ANIDBFS_DEBUG("mmap failed (%s)", filename); + } + + MD4_Init(&context); + MD4_Update(&context, map, len); + MD4_Final(parthashes + (b * 16), &context); + + munmap(map, len); + +/* int percent = (int) (((float) (b+1) / (float) blocks) * 100); + ANIDBFS_DEBUG("Hashing %s %d%%", filename, percent);*/ + } + + close(fd); + + if (blocks > 1) { + MD4_CTX context; + + MD4_Init(&context); + MD4_Update(&context, parthashes, 16 * b); + MD4_Final(ed2k_hash, &context); + } else { + memcpy(ed2k_hash, parthashes, 16); + } + + memset(ed2k_hash_str, 0x00, 33 * sizeof(char)); + for (j = 0; j < 16; j++) { + ed2k_hash_str[(j<<1)] = hexdigits[(((ed2k_hash[j]) & 0xf0) >> 4)]; + ed2k_hash_str[(j<<1)+1] = hexdigits[(((ed2k_hash[j]) & 0x0f))]; + } + + free(ed2k_hash); + free(parthashes); + + return ed2k_hash_str; +} + +static void dump_result (anidb_result_t *result) { int n; char *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: - printf("<result %p null>\n", result); + ANIDBFS_DEBUG("<result %p null>", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); - printf("<result %p (string) \"%s\">\n", result, str); + ANIDBFS_DEBUG("<result %p (string) \"%s\">", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); - printf("<result %p (int) \"%d\">\n", result, n); + ANIDBFS_DEBUG("<result %p (int) \"%d\">", result, n); break; case ANIDB_RESULT_DICT: - printf("<result %p (dict)\n", result); + ANIDBFS_DEBUG("<result %p (dict)", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { - printf(" %s = \"%s\"", dict->key, dict->value); + ANIDBFS_DEBUG(" %s = \"%s\"", dict->key, dict->value); - if (anidb_dict_next(dict)) - printf(",\n"); } - printf(">\n"); + ANIDBFS_DEBUG(">\n"); break; } } - -void -dump_anime (anidb_session_t *session, char *name) +static void +anidbfs_hash_file (anidb_session_t *session, char *path) { - anidb_result_t *res; + char *hash; - res = anidb_session_anime_name(session, name); + ANIDBFS_LOG("Hashing file: %s", anidbfs_basename(path)); - if (anidb_result_get_code(res) == ANIDB_ANIME) { - dump_result(res); - } + hash = ed2k_hash(path); - anidb_result_unref(res); -} + ANIDBFS_DEBUG("Hash: %s", hash) -void -dump_animedesc (anidb_session_t *session, int id, int part) -{ - anidb_result_t *res; - - res = anidb_session_animedesc(session, id, part); - - if (anidb_result_get_code(res) == ANIDB_ANIME_DESCRIPTION) { - dump_result(res); - } - - anidb_result_unref(res); + free(hash); } -void -dump_episode (anidb_session_t *session, int id) +static void +anidbfs_hash_dir (anidb_session_t *session, char *path) { - anidb_result_t *res; + DIR *dir; + char fullpath[9999]; + struct stat64 info; + struct dirent *entry; - res = anidb_session_episode_id(session, id); + ANIDBFS_LOG("Hashing dir: %s", path); - if (anidb_result_get_code(res) == ANIDB_EPISODE) { - dump_result(res); - } + dir = opendir(path); - anidb_result_unref(res); -} - -void -dump_file (anidb_session_t *session, int id) -{ - anidb_result_t *res; - -// res = anidb_session_file_ed2k(session, 44255118, "fa8313487b58f37f72500e8c5afeb3bf"); - res = anidb_session_file_id(session, id); - - if (anidb_result_get_code(res) == ANIDB_FILE) { - dump_result(res); - } - - anidb_result_unref(res); -} + if (dir) { + while (entry = readdir(dir)) { + if (entry->d_name && entry->d_name[0] != '.') { + sprintf(fullpath, "%s%s%s", path, + (path[strlen(path)-1]=='/') ? "" : "/", + entry->d_name); + stat64(fullpath, &info); -void -dump_group (anidb_session_t *session, char *name) -{ - anidb_result_t *res; - - res = anidb_session_group_name(session, name); + if (S_ISDIR(info.st_mode)) { + anidbfs_hash_dir(session, fullpath); + } else if (S_ISREG(info.st_mode) || S_ISLNK(info.st_mode)) { + anidbfs_hash_file(session, fullpath); + } + } + } - if (anidb_result_get_code(res) == ANIDB_GROUP) { - dump_result(res); + closedir(dir); } - anidb_result_unref(res); } - int main (int argc, char *argv[]) { anidb_session_t *session; anidb_result_t *res; char *key; - if (argc < 3) { - printf("Usage: %s <username> <password>\n", argv[0]); + if (argc < 4) { + printf("Usage: %s <username> <password> <path>\n", argv[0]); exit(0); } session = anidb_session_new("anidbfs", "1"); + ANIDBFS_DEBUG("Connecting to AniDB"); res = anidb_session_authenticate(session, argv[1], argv[2]); dump_result(res); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); } - dump_anime(session, "Neon Genesis Evangelion"); - dump_group(session, "Chrippa Crapsubs"); - dump_animedesc(session, 23, 0); - dump_episode(session, 21346); - dump_file(session, 43698); + anidbfs_hash_dir(session, argv[3]); - dump_result(anidb_session_logout(session)); + ANIDBFS_DEBUG("Logging out"); + anidb_session_logout(session); } anidb_result_unref(res); anidb_session_unref(session); - return 0; + return 1; } + + diff --git a/src/anidbfs/anidbfs.c b/src/anidbfs/anidbfs.c index 302819d..48ea97c 100644 --- a/src/anidbfs/anidbfs.c +++ b/src/anidbfs/anidbfs.c @@ -1,21 +1,17 @@ #include <stdio.h> #include <string.h> #include <errno.h> #include <fcntl.h> -#define __USE_POSIX199309 -#define __need_timespec -#define __USE_MISC - #include <fuse.h> #include "anidbfs.h" int main(int argc, char *argv[]) { return 0; } diff --git a/src/anidbfs/db.c b/src/anidbfs/db.c new file mode 100644 index 0000000..e69de29 diff --git a/src/anidbfs/db.h b/src/anidbfs/db.h new file mode 100644 index 0000000..e69de29 diff --git a/src/anidbfs/util.c b/src/anidbfs/util.c new file mode 100644 index 0000000..32794cd --- /dev/null +++ b/src/anidbfs/util.c @@ -0,0 +1,34 @@ +#include "util.h" +#include <sys/time.h> +#include <string.h> +#include <time.h> + + +char * +anidbfs_basename (char *name) +{ + const char *base; + + for (base = name; *name; name++) { + if (*name == '/') { + base = name + 1; + } + } + + return (char *) base; +} + +char * +anidbfs_current_time (void) +{ + char buf[256]; + time_t tv; + struct tm st; + + tv = time(NULL); + localtime_r(&tv, &st); + strftime(buf, sizeof(buf), "%H:%M:%S", &st); + + return strdup(buf); +} + diff --git a/src/anidbfs/util.h b/src/anidbfs/util.h new file mode 100644 index 0000000..cc0c52a --- /dev/null +++ b/src/anidbfs/util.h @@ -0,0 +1,22 @@ +#ifndef _ANIDBFS_UTIL_H +#define _ANIDBFS_UTIL_H + +char * anidbfs_current_time(void); +char * anidbfs_basename (char *name); + + +#define ANIDBFS_LOG(fmt, ...) { \ + printf("%s LOG ", anidbfs_current_time()); \ + printf(fmt"\n", ## __VA_ARGS__); \ +} + +#ifdef DEBUG + #define ANIDBFS_DEBUG(fmt, ...) { \ + printf("%s DEBUG %s:%d: ", anidbfs_current_time(), __FILE__, __LINE__); \ + printf(fmt"\n", ## __VA_ARGS__); \ + } +#else + #define ANIDBFS_DEBUG(...) +#endif + +#endif diff --git a/src/anidbfs/wscript b/src/anidbfs/wscript index fe58cc7..043fea0 100644 --- a/src/anidbfs/wscript +++ b/src/anidbfs/wscript @@ -1,43 +1,44 @@ # vim: set fileencoding=utf-8 filetype=python : -anidbfs = ['anidbfs.c'] -anidbfs_update = ['anidbfs-update.c'] +anidbfs = ['anidbfs.c', 'util.c'] +anidbfs_update = ['anidbfs-update.c', 'util.c'] def set_options(opt): pass def configure(conf): - for pkg in ['fuse']: + for pkg in ['fuse', 'openssl']: if not conf.check_cfg(package = pkg, args = '--cflags --libs', uselib_store = pkg): return False return True def build(bld): import Options defines = [] if Options.options.debug: defines += ['DEBUG'] obj = bld.new_task_gen( features = 'cc cprogram', source = anidbfs, target = 'anidbfs', uselib = 'fuse', install_path = '${PREFIX}/bin', - ccflags = ['-std=c99'], + ccflags = ['-std=gnu99'], defines = defines ) obj = bld.new_task_gen( features = 'cc cprogram', source = anidbfs_update, target = 'anidbfs-update', includes = '. ../libanidb', install_path = '${PREFIX}/bin', + uselib = 'openssl', uselib_local = 'anidb', - ccflags = ['-std=c99'], + ccflags = ['-std=gnu99'], defines = defines ) diff --git a/src/libanidb/anidb.c b/src/libanidb/anidb.c index e912310..eeaa694 100644 --- a/src/libanidb/anidb.c +++ b/src/libanidb/anidb.c @@ -1,574 +1,572 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; - printf("send: '%s'\n", msg); +// printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; -// strcpy(out, "200 fsdf LOGIN ACCEPTED"); - - printf("recv: '%s'\n", out); +// printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(9999); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:9999"); } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; session->clientname = name; session->clientversion = version; session->key = NULL; anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); if (session->key) free(session->key); free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { session->key = (char *) strdup(key); } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "FILE", "fid", fid, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, "fcode", "123682590", "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { dict->key = key; dict->value = value; } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); diff --git a/src/libanidb/wscript b/src/libanidb/wscript index 5c69866..a37c19a 100644 --- a/src/libanidb/wscript +++ b/src/libanidb/wscript @@ -1,29 +1,26 @@ # vim: set fileencoding=utf-8 filetype=python : -files = """ -handlers.c -anidb.c -""".split() +files = ['handlers.c', 'anidb.c'] def set_options(opt): pass def configure(conf): return True def build(bld): import Options defines = [] if Options.options.debug: defines += ['DEBUG'] obj = bld.new_task_gen( features = 'cc cshlib', target = 'anidb', source = files, defines = defines, ccflags = ['-std=gnu99', '-g'], install_path = '${PREFIX}/lib' ) diff --git a/test.sh b/test.sh index 8687c39..8fcd566 100755 --- a/test.sh +++ b/test.sh @@ -1,5 +1,5 @@ #!/bin/sh export LD_LIBRARY_PATH=./_build_/default/src/libanidb/ -./_build_/default/src/anidbfs/anidbfs-update fusetest testuser +./_build_/default/src/anidbfs/anidbfs-update fusetest testuser /storage/ch01/anime/hdtv diff --git a/wscript b/wscript index 5af2ef3..de5886b 100644 --- a/wscript +++ b/wscript @@ -1,27 +1,27 @@ # vim: set fileencoding=utf-8 filetype=python : from logging import fatal, info import os srcdir = '.' blddir = '_build_' subdirs = ['src/libanidb', 'src/anidbfs'] def set_options(opt): opt.add_option('--debug', action = 'store_true', default = True, help = 'Enable debug') for dir in subdirs: opt.sub_options(dir) def configure(conf): import Options conf.check_tool('gcc') for dir in subdirs: - print conf.sub_config(dir) + conf.sub_config(dir) def build(bld): bld.add_subdirs(subdirs)
chrippa/hashfs
f131de0433403ab3ab1c17e6c5c2c241dc2f9d23
Fix broken FILE commands.
diff --git a/src/anidbfs/anidbfs-update.c b/src/anidbfs/anidbfs-update.c index a1a828e..edc008a 100644 --- a/src/anidbfs/anidbfs-update.c +++ b/src/anidbfs/anidbfs-update.c @@ -1,154 +1,155 @@ #include <stdio.h> #include <stdlib.h> #include <anidb.h> void dump_result (anidb_result_t *result) { int n; char *str; anidb_dict_t *dict; switch (anidb_result_get_type(result)) { case ANIDB_RESULT_NULL: printf("<result %p null>\n", result); break; case ANIDB_RESULT_STRING: anidb_result_get_str(result, &str); printf("<result %p (string) \"%s\">\n", result, str); break; case ANIDB_RESULT_NUMBER: anidb_result_get_int(result, &n); printf("<result %p (int) \"%d\">\n", result, n); break; case ANIDB_RESULT_DICT: printf("<result %p (dict)\n", result); for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { printf(" %s = \"%s\"", dict->key, dict->value); if (anidb_dict_next(dict)) printf(",\n"); } printf(">\n"); break; } } void dump_anime (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_anime_name(session, name); if (anidb_result_get_code(res) == ANIDB_ANIME) { dump_result(res); } anidb_result_unref(res); } void dump_animedesc (anidb_session_t *session, int id, int part) { anidb_result_t *res; res = anidb_session_animedesc(session, id, part); if (anidb_result_get_code(res) == ANIDB_ANIME_DESCRIPTION) { dump_result(res); } anidb_result_unref(res); } void dump_episode (anidb_session_t *session, int id) { anidb_result_t *res; res = anidb_session_episode_id(session, id); if (anidb_result_get_code(res) == ANIDB_EPISODE) { dump_result(res); } anidb_result_unref(res); } void dump_file (anidb_session_t *session, int id) { anidb_result_t *res; - res = anidb_session_file_ed2k(session, 44255118, "fa8313487b58f37f72500e8c5afeb3bf"); +// res = anidb_session_file_ed2k(session, 44255118, "fa8313487b58f37f72500e8c5afeb3bf"); + res = anidb_session_file_id(session, id); if (anidb_result_get_code(res) == ANIDB_FILE) { dump_result(res); } anidb_result_unref(res); } void dump_group (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_group_name(session, name); if (anidb_result_get_code(res) == ANIDB_GROUP) { dump_result(res); } anidb_result_unref(res); } int main (int argc, char *argv[]) { anidb_session_t *session; anidb_result_t *res; char *key; if (argc < 3) { printf("Usage: %s <username> <password>\n", argv[0]); exit(0); } session = anidb_session_new("anidbfs", "1"); res = anidb_session_authenticate(session, argv[1], argv[2]); dump_result(res); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); } dump_anime(session, "Neon Genesis Evangelion"); dump_group(session, "Chrippa Crapsubs"); dump_animedesc(session, 23, 0); dump_episode(session, 21346); - dump_file(session, 92739); + dump_file(session, 43698); dump_result(anidb_session_logout(session)); } anidb_result_unref(res); anidb_session_unref(session); return 0; } diff --git a/src/libanidb/anidb.c b/src/libanidb/anidb.c index c1d4a49..e912310 100644 --- a/src/libanidb/anidb.c +++ b/src/libanidb/anidb.c @@ -1,703 +1,707 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); out[n-1] = '\0'; // strcpy(out, "200 fsdf LOGIN ACCEPTED"); printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(9999); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:9999"); } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; session->clientname = name; session->clientversion = version; session->key = NULL; anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); if (session->key) free(session->key); free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { session->key = (char *) strdup(key); } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, "nat", "1", "enc", "UTF8", NULL); return res; } /* ANIME */ anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int n) { anidb_result_t *res; char aid[10]; char part[10]; sprintf(aid, "%d", id); sprintf(part, "%d", n); res = anidb_session_cmd(session, "ANIMEDESC", "aid", aid, "part", part, "s", session->key, NULL); return res; } /* EPISODE */ anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id) { anidb_result_t *res; char eid[10]; sprintf(eid, "%d", id); res = anidb_session_cmd(session, "EPISODE", "eid", eid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep) { anidb_result_t *res; char epno[10]; sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aname", name, "epno", epno, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep) { anidb_result_t *res; char aid[10]; char epno[10]; sprintf(aid, "%d", id); sprintf(epno, "%d", ep); res = anidb_session_cmd(session, "EPISODE", "aid", aid, "epno", epno, "s", session->key, NULL); return res; } /* FILE */ anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "FILE", "fid", fid, + "fcode", "123682590", + "acode", "75435779", "s", session->key, NULL); return res; } anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "FILE", "size", siz, "ed2k", ed2k, + "fcode", "123682590", + "acode", "75435779", "s", session->key, NULL); return res; } /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id) { anidb_result_t *res; char gid[10]; sprintf(gid, "%d", id); res = anidb_session_cmd(session, "GROUP", "gid", gid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "GROUP", "gname", name, "s", session->key, NULL); return res; } /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id) { } /* MYLIST */ /* MYLISTADD */ anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTADD", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTADD", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTDEL */ anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id) { anidb_result_t *res; char lid[10]; sprintf(lid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "lid", lid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id) { anidb_result_t *res; char fid[10]; sprintf(fid, "%d", id); res = anidb_session_cmd(session, "MYLISTDEL", "fid", fid, "s", session->key, NULL); return res; } anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) { anidb_result_t *res; char siz[20]; sprintf(siz, "%d", size); res = anidb_session_cmd(session, "MYLISTDEL", "size", siz, "ed2k", ed2k, "s", session->key, NULL); return res; } /* MYLISTSTATS */ anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session) { } /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { dict->key = key; dict->value = value; } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } anidb_dict_t * anidb_dict_next (anidb_dict_t *dict) { return dict->next; } anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, char *string) { result->type = ANIDB_RESULT_STRING; result->value.string = string; } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, char *key, char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } int anidb_result_dict_get (anidb_result_t *result, char *key, char **out) { anidb_dict_t *dict; if (result->type != ANIDB_RESULT_DICT) return 0; for (dict = result->value.dict; dict; dict = dict->next) { if (!strcmp(dict->key, key)) { return anidb_dict_get(dict, out); } } return 0; } anidb_dict_t * anidb_result_get_dict (anidb_result_t *result) { if (result->type != ANIDB_RESULT_DICT) return NULL; return result->value.dict; } diff --git a/src/libanidb/handlers.c b/src/libanidb/handlers.c index feead7b..273ff53 100644 --- a/src/libanidb/handlers.c +++ b/src/libanidb/handlers.c @@ -1,184 +1,213 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "util.h" #include "anidb.h" static char * get_part(char *src, int delim, int idx) { int i = 0, j = 0; char buf[1024]; while (*src != '\0') { if (i == idx && *src != delim) { buf[j] = *src; j++; } if (*src == delim) i++; src++; } buf[j++] = '\0'; return strdup(buf); } #define DICT_PART_ADD(result, data, num, name) \ anidb_result_dict_set((result), (name), get_part((data), '|', (num))) static void handler_auth_accepted (anidb_result_t *result, char *data) { char buf[10]; sscanf(data, "200 %s", &buf); anidb_result_set_str(result, buf); } static void handler_auth_logout (anidb_result_t *result, char *data) { /* pass */ } static void handler_anime (anidb_result_t *result, char *data) { char *anime; anime = data + 10; DICT_PART_ADD(result, anime, 0, "aid"); DICT_PART_ADD(result, anime, 1, "eps"); DICT_PART_ADD(result, anime, 2, "ep_count"); DICT_PART_ADD(result, anime, 3, "special_cnt"); DICT_PART_ADD(result, anime, 4, "rating"); DICT_PART_ADD(result, anime, 5, "votes"); DICT_PART_ADD(result, anime, 6, "tmprating"); DICT_PART_ADD(result, anime, 7, "tmpvotes"); DICT_PART_ADD(result, anime, 8, "rating_average"); DICT_PART_ADD(result, anime, 9, "reviews"); DICT_PART_ADD(result, anime, 10, "year"); DICT_PART_ADD(result, anime, 11, "type"); DICT_PART_ADD(result, anime, 12, "romaji"); DICT_PART_ADD(result, anime, 13, "kanji"); DICT_PART_ADD(result, anime, 14, "english"); DICT_PART_ADD(result, anime, 15, "other"); DICT_PART_ADD(result, anime, 16, "short_names"); DICT_PART_ADD(result, anime, 17, "synonyms"); DICT_PART_ADD(result, anime, 18, "category_list"); } static void handler_animedesc (anidb_result_t *result, char *data) { char *desc; desc = data + 14; DICT_PART_ADD(result, desc, 0, "part"); DICT_PART_ADD(result, desc, 1, "max_parts"); DICT_PART_ADD(result, desc, 2, "description"); } static void handler_episode (anidb_result_t *result, char *data) { char *episode; episode = data + 12; DICT_PART_ADD(result, episode, 0, "eid"); DICT_PART_ADD(result, episode, 1, "aid"); DICT_PART_ADD(result, episode, 2, "length"); DICT_PART_ADD(result, episode, 3, "rating"); DICT_PART_ADD(result, episode, 4, "votes"); DICT_PART_ADD(result, episode, 5, "epno"); DICT_PART_ADD(result, episode, 6, "eng"); DICT_PART_ADD(result, episode, 7, "romaji"); DICT_PART_ADD(result, episode, 8, "kanji"); DICT_PART_ADD(result, episode, 9, "aired"); } static void handler_file (anidb_result_t *result, char *data) { char *file; file = data + 9; - DICT_PART_ADD(result, file, 0, "fid"); - DICT_PART_ADD(result, file, 1, "aid"); - DICT_PART_ADD(result, file, 2, "eid"); - DICT_PART_ADD(result, file, 3, "gid"); - DICT_PART_ADD(result, file, 4, "state"); - DICT_PART_ADD(result, file, 5, "size"); - DICT_PART_ADD(result, file, 6, "ed2k"); - DICT_PART_ADD(result, file, 7, "filename"); + DICT_PART_ADD(result, file, 0, "fid"); + DICT_PART_ADD(result, file, 1, "aid"); + DICT_PART_ADD(result, file, 2, "eid"); + DICT_PART_ADD(result, file, 3, "gid"); + DICT_PART_ADD(result, file, 4, "lid"); + DICT_PART_ADD(result, file, 5, "state"); + DICT_PART_ADD(result, file, 6, "size"); + DICT_PART_ADD(result, file, 7, "ed2k"); + DICT_PART_ADD(result, file, 8, "md5"); + DICT_PART_ADD(result, file, 9, "sha1"); + DICT_PART_ADD(result, file, 10, "crc32"); + DICT_PART_ADD(result, file, 11, "dub"); + DICT_PART_ADD(result, file, 12, "sub"); + DICT_PART_ADD(result, file, 13, "quality"); + DICT_PART_ADD(result, file, 14, "source"); + DICT_PART_ADD(result, file, 15, "audio"); + DICT_PART_ADD(result, file, 16, "video"); + DICT_PART_ADD(result, file, 17, "resolution"); + DICT_PART_ADD(result, file, 18, "ext"); + DICT_PART_ADD(result, file, 19, "duration"); + + DICT_PART_ADD(result, file, 20, "group_name"); + DICT_PART_ADD(result, file, 21, "group_short"); + + DICT_PART_ADD(result, file, 22, "ep_number"); + DICT_PART_ADD(result, file, 23, "ep_eng"); + DICT_PART_ADD(result, file, 24, "ep_romaji"); + DICT_PART_ADD(result, file, 25, "ep_kanji"); + + DICT_PART_ADD(result, file, 26, "anime_totalep"); + DICT_PART_ADD(result, file, 27, "anime_lastep"); + DICT_PART_ADD(result, file, 28, "anime_year"); + DICT_PART_ADD(result, file, 29, "anime_type"); + DICT_PART_ADD(result, file, 30, "anime_romaji"); + DICT_PART_ADD(result, file, 31, "anime_kanji"); + DICT_PART_ADD(result, file, 32, "anime_eng"); + DICT_PART_ADD(result, file, 33, "anime_categories"); } static void handler_group (anidb_result_t *result, char *data) { char *group; group = data + 10; DICT_PART_ADD(result, group, 0, "gid"); DICT_PART_ADD(result, group, 1, "rating"); DICT_PART_ADD(result, group, 2, "votes"); DICT_PART_ADD(result, group, 3, "acount"); DICT_PART_ADD(result, group, 4, "fcount"); DICT_PART_ADD(result, group, 5, "name"); DICT_PART_ADD(result, group, 6, "short"); DICT_PART_ADD(result, group, 7, "irc_channel"); DICT_PART_ADD(result, group, 8, "irc_server"); DICT_PART_ADD(result, group, 9, "url"); } anidb_result_handler_t anidb_handlers[] = { /* AUTH */ { ANIDB_LOGIN_ACCEPTED, handler_auth_accepted }, { ANIDB_LOGGED_OUT, handler_auth_logout }, /* ANIME */ { ANIDB_ANIME, handler_anime }, /* ANIMEDESC */ { ANIDB_ANIME_DESCRIPTION, handler_animedesc }, /* EPISODE */ { ANIDB_EPISODE, handler_episode }, /* FILE */ { ANIDB_FILE, handler_file }, /* GROUP */ { ANIDB_GROUP, handler_group }, /* GROUPSTATUS */ /* MYLIST */ /* MYLISTADD */ /* MYLISTDEL */ /* MYLISTSTATS */ /* VOTE */ /* RANDOM */ /* PING */ /* UPTIME */ /* ENCODING */ /* SENDMSG */ /* USER */ };
chrippa/hashfs
2266e0e9aeee15779d23de93f25854bb7beb73b3
Add more API functions.
diff --git a/src/anidbfs/anidbfs-update.c b/src/anidbfs/anidbfs-update.c index 272fc70..a1a828e 100644 --- a/src/anidbfs/anidbfs-update.c +++ b/src/anidbfs/anidbfs-update.c @@ -1,57 +1,154 @@ #include <stdio.h> #include <stdlib.h> #include <anidb.h> void -dump_anime (anidb_session_t *session, char *name) +dump_result (anidb_result_t *result) { - anidb_result_t *res; + int n; + char *str; anidb_dict_t *dict; - char *aid; - res = anidb_session_anime_by_name(session, "Neon Genesis Evangelion"); + switch (anidb_result_get_type(result)) { + case ANIDB_RESULT_NULL: + printf("<result %p null>\n", result); + break; + + case ANIDB_RESULT_STRING: + anidb_result_get_str(result, &str); + printf("<result %p (string) \"%s\">\n", result, str); + + break; + + case ANIDB_RESULT_NUMBER: + anidb_result_get_int(result, &n); + printf("<result %p (int) \"%d\">\n", result, n); + + break; + + case ANIDB_RESULT_DICT: + printf("<result %p (dict)\n", result); + + for (dict = anidb_result_get_dict(result); dict; dict = anidb_dict_next(dict)) { + printf(" %s = \"%s\"", dict->key, dict->value); + + if (anidb_dict_next(dict)) + printf(",\n"); + } + + printf(">\n"); + + break; + } +} + + +void +dump_anime (anidb_session_t *session, char *name) +{ + anidb_result_t *res; + res = anidb_session_anime_name(session, name); if (anidb_result_get_code(res) == ANIDB_ANIME) { - printf("Anime:\n"); + dump_result(res); + } - for (dict = res->value.dict; dict; dict = dict->next) { - printf("%s: %s\n", dict->key, dict->value); - } - } else { - printf("Fail\n"); + anidb_result_unref(res); +} + +void +dump_animedesc (anidb_session_t *session, int id, int part) +{ + anidb_result_t *res; + + res = anidb_session_animedesc(session, id, part); + + if (anidb_result_get_code(res) == ANIDB_ANIME_DESCRIPTION) { + dump_result(res); } + + anidb_result_unref(res); } +void +dump_episode (anidb_session_t *session, int id) +{ + anidb_result_t *res; + + res = anidb_session_episode_id(session, id); + + if (anidb_result_get_code(res) == ANIDB_EPISODE) { + dump_result(res); + } + + anidb_result_unref(res); +} + +void +dump_file (anidb_session_t *session, int id) +{ + anidb_result_t *res; + + res = anidb_session_file_ed2k(session, 44255118, "fa8313487b58f37f72500e8c5afeb3bf"); + + if (anidb_result_get_code(res) == ANIDB_FILE) { + dump_result(res); + } + + anidb_result_unref(res); +} + + +void +dump_group (anidb_session_t *session, char *name) +{ + anidb_result_t *res; + + res = anidb_session_group_name(session, name); + + if (anidb_result_get_code(res) == ANIDB_GROUP) { + dump_result(res); + } + + anidb_result_unref(res); +} + + int main (int argc, char *argv[]) { anidb_session_t *session; anidb_result_t *res; char *key; if (argc < 3) { printf("Usage: %s <username> <password>\n", argv[0]); exit(0); } session = anidb_session_new("anidbfs", "1"); res = anidb_session_authenticate(session, argv[1], argv[2]); + dump_result(res); if (anidb_result_get_code(res) == ANIDB_LOGIN_ACCEPTED) { if (anidb_result_get_str(res, &key)) { anidb_session_set_key(session, key); } dump_anime(session, "Neon Genesis Evangelion"); + dump_group(session, "Chrippa Crapsubs"); + dump_animedesc(session, 23, 0); + dump_episode(session, 21346); + dump_file(session, 92739); - anidb_session_logout(session); + dump_result(anidb_session_logout(session)); } anidb_result_unref(res); anidb_session_unref(session); return 0; } diff --git a/src/anidbfs/wscript-wtf b/src/anidbfs/wscript-wtf deleted file mode 100644 index 095f211..0000000 --- a/src/anidbfs/wscript-wtf +++ /dev/null @@ -1,42 +0,0 @@ -# vim: set fileencoding=utf-8 filetype=python : - -anidbfs = """ -anidbfs.c -""".split() - -anidbfs-update = """ -anidbfs-update.c -""".split() - - -def set_options(opt): - pass - -def configure(conf): - import Options - - conf.env['CCFLAGS_c99'] = '-std=c99' - - if Options.options.debug: - conf.env['CCFLAGS_debug'] = '-DDEBUG' - - for pkg in ['fuse']: - if not conf.check_cfg(package = pkg, args = '--cflags --libs', uselib_store = pkg): - return False - - return True - -def build(bld): - obj = bld.new_task_gen('cc', 'program') - obj.target = 'anidbfs' - obj.source = files - obj.uselib = 'c99 debug fuse' - obj.install_path = '${PREFIX}/bin' - - obj = bld.new_task_gen('cc', 'program') - obj.target = 'anidbfs-update' - obj.includes = '. ../anidblib' - obj.source = files - obj.uselib = 'c99 debug' - obj.uselib_local = 'libanidb' - obj.install_path = '${PREFIX}/bin' diff --git a/src/libanidb/anidb.c b/src/libanidb/anidb.c index 202b15d..c1d4a49 100644 --- a/src/libanidb/anidb.c +++ b/src/libanidb/anidb.c @@ -1,424 +1,703 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "anidb.h" #include "util.h" extern anidb_result_handler_t anidb_handlers[1024]; static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...); static void gen_query_va (char *buf, va_list ap); static void gen_query (char *buf, ...); static void gen_query_va (char *buf, va_list ap) { int i = 0; for (char *str = va_arg(ap, char *); str; str = va_arg(ap, char *), i++) { strcat(buf, str); if ((i % 2) == 0) strcat(buf, "="); else strcat(buf, "&"); } buf[strlen(buf) - 1] = '\0'; } static void gen_query (char *buf, ...) { va_list ap, aq; va_start(ap, buf); va_copy(aq, ap); va_end(ap); gen_query_va(buf, aq); } static void sock_send (anidb_session_t *session, char *msg, char *out) { int n; printf("send: '%s'\n", msg); send(session->socket, msg, strlen(msg) + 1, 0); n = recv(session->socket, out, 1000, 0); - out[n] = '\0'; + out[n-1] = '\0'; // strcpy(out, "200 fsdf LOGIN ACCEPTED"); printf("recv: '%s'\n", out); } anidb_session_t * anidb_session_new (char *name, char *version) { anidb_session_t *session; struct protoent *protocol; struct hostent *host; struct sockaddr_in addr, local; int sock, rval; session = calloc(1, sizeof(anidb_session_t)); protocol = getprotobyname("udp"); if (protocol == 0) { ANIDB_ERROR("UDP sockets not available"); } sock = socket(PF_INET, SOCK_DGRAM, protocol->p_proto); if (sock < 0) { ANIDB_ERROR("Unable to open socket"); } host = gethostbyname(ANIDB_SERVER_HOST); if (host == NULL) { ANIDB_ERROR("Could lookup hostname: %s", ANIDB_SERVER_HOST); } local.sin_addr.s_addr = INADDR_ANY; local.sin_family = AF_INET; local.sin_port = htons(9999); rval = bind(sock, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Unable to bind local port 0.0.0.0:9999"); } addr.sin_family = AF_INET; addr.sin_port = htons(ANIDB_SERVER_PORT); memcpy((char *) &addr.sin_addr, (char *) host->h_addr_list[0], host->h_length); rval = connect(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_in)); if (rval < 0) { ANIDB_ERROR("Could not connect to server"); } session->socket = sock; session->clientname = name; session->clientversion = version; session->key = NULL; anidb_session_ref(session); return session; } void anidb_session_ref (anidb_session_t *session) { session->refcount++; } void anidb_session_unref (anidb_session_t *session) { session->refcount--; if (session->refcount == 0) { close(session->socket); if (session->key) free(session->key); free(session); } } void anidb_session_set_key (anidb_session_t *session, char *key) { session->key = (char *) strdup(key); } static anidb_result_t * anidb_session_cmd (anidb_session_t *session, char *cmd, ...) { char out[1024]; char in[1024]; int code; anidb_result_t *res; va_list aq, ap; sprintf(out, "%s ", cmd); va_start(ap, cmd); va_copy(aq, ap); gen_query_va(out, aq); va_end(ap); sock_send(session, out, in); code = atoi(in); res = anidb_result_new(code); for (int i = 0; i < LENGTH(anidb_handlers); i++) { if (anidb_handlers[i].code == code) { anidb_handlers[i].func(res, in); break; } } return res; } + +/* AUTH */ + anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password) { anidb_result_t *res; res = anidb_session_cmd(session, "AUTH", "user", username, "pass", password, "protover", ANIDB_PROTO_VERSION, "client", session->clientname, "clientver", session->clientversion, - "nat", "1", - "enc", "UTF8", + "nat", "1", + "enc", "UTF8", NULL); return res; } + +/* ANIME */ + anidb_result_t * -anidb_session_anime_by_name (anidb_session_t *session, char *name) +anidb_session_anime_name (anidb_session_t *session, char *name) { anidb_result_t *res; res = anidb_session_cmd(session, "ANIME", "aname", name, "s", session->key, NULL); return res; } anidb_result_t * -anidb_session_anime_by_aid (anidb_session_t *session, int id) +anidb_session_anime_id (anidb_session_t *session, int id) { anidb_result_t *res; char aid[10]; sprintf(aid, "%d", id); res = anidb_session_cmd(session, "ANIME", "aid", aid, "s", session->key, NULL); return res; } + +/* ANIMEDESC */ + +anidb_result_t * +anidb_session_animedesc (anidb_session_t *session, int id, int n) +{ + anidb_result_t *res; + char aid[10]; + char part[10]; + + sprintf(aid, "%d", id); + sprintf(part, "%d", n); + + res = anidb_session_cmd(session, "ANIMEDESC", + "aid", aid, + "part", part, + "s", session->key, + NULL); + + return res; +} + + +/* EPISODE */ + +anidb_result_t * +anidb_session_episode_id (anidb_session_t *session, int id) +{ + anidb_result_t *res; + char eid[10]; + + sprintf(eid, "%d", id); + + res = anidb_session_cmd(session, "EPISODE", + "eid", eid, + "s", session->key, + NULL); + + return res; +} + +anidb_result_t * +anidb_session_episode_name (anidb_session_t *session, char *name, int ep) +{ + anidb_result_t *res; + char epno[10]; + + sprintf(epno, "%d", ep); + + res = anidb_session_cmd(session, "EPISODE", + "aname", name, + "epno", epno, + "s", session->key, + NULL); + + return res; + +} + +anidb_result_t * +anidb_session_episode_aid (anidb_session_t *session, int id, int ep) +{ + anidb_result_t *res; + char aid[10]; + char epno[10]; + + sprintf(aid, "%d", id); + sprintf(epno, "%d", ep); + + res = anidb_session_cmd(session, "EPISODE", + "aid", aid, + "epno", epno, + "s", session->key, + NULL); + + return res; + +} + + +/* FILE */ + +anidb_result_t * +anidb_session_file_id (anidb_session_t *session, int id) +{ + anidb_result_t *res; + char fid[10]; + + sprintf(fid, "%d", id); + + res = anidb_session_cmd(session, "FILE", + "fid", fid, + "s", session->key, + NULL); + + return res; +} + +anidb_result_t * +anidb_session_file_ed2k (anidb_session_t *session, int size, char *ed2k) +{ + anidb_result_t *res; + char siz[20]; + + sprintf(siz, "%d", size); + + res = anidb_session_cmd(session, "FILE", + "size", siz, + "ed2k", ed2k, + "s", session->key, + NULL); + + return res; +} + + +/* GROUP */ + +anidb_result_t * +anidb_session_group_id (anidb_session_t *session, int id) +{ + anidb_result_t *res; + char gid[10]; + + sprintf(gid, "%d", id); + + res = anidb_session_cmd(session, "GROUP", + "gid", gid, + "s", session->key, + NULL); + + return res; +} + +anidb_result_t * +anidb_session_group_name (anidb_session_t *session, char *name) +{ + anidb_result_t *res; + + res = anidb_session_cmd(session, "GROUP", + "gname", name, + "s", session->key, + NULL); + + return res; +} + + +/* GROUPSTATUS */ +anidb_result_t * +anidb_session_groupstatus (anidb_session_t *session, int id) +{ + +} + +/* MYLIST */ + + +/* MYLISTADD */ + +anidb_result_t * +anidb_session_mylist_add_fid (anidb_session_t *session, int id) +{ + anidb_result_t *res; + char fid[10]; + + sprintf(fid, "%d", id); + + res = anidb_session_cmd(session, "MYLISTADD", + "fid", fid, + "s", session->key, + NULL); + + return res; +} + +anidb_result_t * +anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k) +{ + anidb_result_t *res; + char siz[20]; + + sprintf(siz, "%d", size); + + res = anidb_session_cmd(session, "MYLISTADD", + "size", siz, + "ed2k", ed2k, + "s", session->key, + NULL); + + return res; +} + + +/* MYLISTDEL */ + +anidb_result_t * +anidb_session_mylist_del_id (anidb_session_t *session, int id) +{ + anidb_result_t *res; + char lid[10]; + + sprintf(lid, "%d", id); + + res = anidb_session_cmd(session, "MYLISTDEL", + "lid", lid, + "s", session->key, + NULL); + + return res; + +} + +anidb_result_t * +anidb_session_mylist_del_fid (anidb_session_t *session, int id) +{ + anidb_result_t *res; + char fid[10]; + + sprintf(fid, "%d", id); + + res = anidb_session_cmd(session, "MYLISTDEL", + "fid", fid, + "s", session->key, + NULL); + + return res; + +} + +anidb_result_t * +anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k) +{ + anidb_result_t *res; + char siz[20]; + + sprintf(siz, "%d", size); + + res = anidb_session_cmd(session, "MYLISTDEL", + "size", siz, + "ed2k", ed2k, + "s", session->key, + NULL); + + return res; +} + + +/* MYLISTSTATS */ + +anidb_result_t * +anidb_session_mylist_stats (anidb_session_t *session) +{ + +} + + +/* LOGOUT */ + anidb_result_t * anidb_session_logout (anidb_session_t *session) { anidb_result_t *res; res = anidb_session_cmd(session, "LOGOUT", "s", session->key, NULL); return res; } anidb_dict_t * anidb_dict_new (void) { anidb_dict_t *dict; dict = calloc(1, sizeof(anidb_dict_t)); dict->next = NULL; anidb_dict_ref(dict); return dict; } void anidb_dict_ref (anidb_dict_t *dict) { dict->refcount++; } void anidb_dict_unref (anidb_dict_t *dict) { dict->refcount--; if (dict->refcount == 0) { free(dict); } } void anidb_dict_set (anidb_dict_t *dict, char *key, char *value) { dict->key = key; dict->value = value; } int anidb_dict_get (anidb_dict_t *dict, char **out) { *out = dict->value; return 1; } +anidb_dict_t * +anidb_dict_next (anidb_dict_t *dict) +{ + return dict->next; +} anidb_result_t * anidb_result_new (int code) { anidb_result_t *res; res = calloc(1, sizeof(anidb_result_t)); res->code = code; res->type = ANIDB_RESULT_NULL; anidb_result_ref(res); return res; } void anidb_result_ref (anidb_result_t *result) { result->refcount++; } void anidb_result_unref (anidb_result_t *result) { anidb_dict_t *dict, *next; result->refcount--; if (result->refcount == 0) { if (result->type == ANIDB_RESULT_DICT) { next = result->value.dict; for (dict = next; dict; dict = next) { next = dict->next; anidb_dict_unref(dict); } } free(result); } } void anidb_result_set_str (anidb_result_t *result, char *string) { result->type = ANIDB_RESULT_STRING; result->value.string = string; } void anidb_result_set_int (anidb_result_t *result, int number) { result->type = ANIDB_RESULT_NUMBER; result->value.number = number; } void anidb_result_dict_set (anidb_result_t *result, char *key, char *value) { anidb_dict_t *dict, *new; result->type = ANIDB_RESULT_DICT; if (!result->value.dict) { dict = anidb_dict_new(); anidb_dict_set(dict, key, value); result->value.dict = dict; } else { for (dict = result->value.dict; dict; dict = dict->next) { if (!dict->next) { new = anidb_dict_new(); anidb_dict_set(new, key, value); dict->next = new; break; } } } } anidb_result_type_t anidb_result_get_type (anidb_result_t *result) { return result->type; } int anidb_result_get_code (anidb_result_t *result) { return result->code; } int anidb_result_get_str (anidb_result_t *result, char **out) { if (result->type != ANIDB_RESULT_STRING) return 0; *out = result->value.string; return 1; } int anidb_result_get_int (anidb_result_t *result, int *out) { if (result->type != ANIDB_RESULT_NUMBER) return 0; *out = result->value.number; return 1; } int anidb_result_dict_get (anidb_result_t *result, char *key, char **out) { anidb_dict_t *dict; if (result->type != ANIDB_RESULT_DICT) return 0; for (dict = result->value.dict; dict; dict = dict->next) { if (!strcmp(dict->key, key)) { return anidb_dict_get(dict, out); } } return 0; } + +anidb_dict_t * +anidb_result_get_dict (anidb_result_t *result) +{ + if (result->type != ANIDB_RESULT_DICT) + return NULL; + + return result->value.dict; +} diff --git a/src/libanidb/anidb.h b/src/libanidb/anidb.h index c2e6279..075fded 100644 --- a/src/libanidb/anidb.h +++ b/src/libanidb/anidb.h @@ -1,314 +1,322 @@ #ifndef _LIBANIDB_H #define _LIBANIDB_H enum anidb_result_type { ANIDB_RESULT_NULL, ANIDB_RESULT_NUMBER, ANIDB_RESULT_STRING, ANIDB_RESULT_DICT }; struct anidb_session_St { int socket; char *clientname; char *clientversion; char *key; int refcount; }; struct anidb_error_St { int errcode; char *errmsg; }; struct anidb_dict_St { char *key; char *value; struct anidb_dict_St *next; int refcount; }; struct anidb_result_St { struct anidb_error_St *error; int code; enum anidb_result_type type; union { int number; char *string; struct anidb_dict_St *dict; } value; int refcount; }; struct anidb_result_handler_St { int code; void (*func)(struct anidb_result_St *, char *); }; /* Types */ typedef enum anidb_result_type anidb_result_type_t; typedef struct anidb_session_St anidb_session_t; typedef struct anidb_dict_St anidb_dict_t; typedef struct anidb_result_St anidb_result_t; typedef struct anidb_result_handler_St anidb_result_handler_t; typedef struct anidb_error_St anidb_error_t; /* Session */ anidb_session_t * anidb_session_new (char *name, char *version); /* AUTH */ anidb_result_t * anidb_session_authenticate (anidb_session_t *session, char *username, char *password); /* LOGOUT */ anidb_result_t * anidb_session_logout (anidb_session_t *session); /* ANIME */ -anidb_result_t * anidb_session_anime_by_name (anidb_session_t *session, char *name); -anidb_result_t * anidb_session_anime_by_id (anidb_session_t *session, int id); +anidb_result_t * anidb_session_anime_name (anidb_session_t *session, char *name); +anidb_result_t * anidb_session_anime_id (anidb_session_t *session, int id); /* ANIMEDESC */ anidb_result_t * anidb_session_animedesc (anidb_session_t *session, int id, int ep); /* EPISODE */ -anidb_result_t * anidb_session_episode_by_id (anidb_session_t *session, int id); -anidb_result_t * anidb_session_episode_by_aname (anidb_session_t *session, char *name, int ep); -anidb_result_t * anidb_session_episode_by_aid (anidb_session_t *session, int id); +anidb_result_t * anidb_session_episode_id (anidb_session_t *session, int id); +anidb_result_t * anidb_session_episode_name (anidb_session_t *session, char *name, int ep); +anidb_result_t * anidb_session_episode_aid (anidb_session_t *session, int id, int ep); /* FILE */ -anidb_result_t * anidb_session_file_by_id (anidb_session_t *session, int id); -anidb_result_t * anidb_session_file_by_ed2k (anidb_session_t *session, int size, char *ed2k); +anidb_result_t * anidb_session_file_id (anidb_session_t *session, int id); +anidb_result_t * anidb_session_file_ed2k (anidb_session_t *session, int size, char *ed2k); /* GROUP */ anidb_result_t * anidb_session_group_id (anidb_session_t *session, int id); anidb_result_t * anidb_session_group_name (anidb_session_t *session, char *name); /* GROUPSTATUS */ anidb_result_t * anidb_session_groupstatus (anidb_session_t *session, int id); /* MYLIST */ /* MYLISTADD */ +anidb_result_t * anidb_session_mylist_add_fid (anidb_session_t *session, int id); +anidb_result_t * anidb_session_mylist_add_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTDEL */ +anidb_result_t * anidb_session_mylist_del_id (anidb_session_t *session, int id); +anidb_result_t * anidb_session_mylist_del_fid (anidb_session_t *session, int id); +anidb_result_t * anidb_session_mylist_del_ed2k (anidb_session_t *session, int size, char *ed2k); /* MYLISTSTATS */ +anidb_result_t * anidb_session_mylist_stats (anidb_session_t *session); /* VOTE */ /* RANDOM */ /* MYLISTEXPORT */ /* PING */ anidb_result_t * anidb_session_ping (anidb_session_t *session); /* VERSION */ anidb_result_t * anidb_session_uptime (anidb_session_t *session); /* UPTIME */ anidb_result_t * anidb_session_version (anidb_session_t *session); /* ENCODING */ /* SENDMSG */ /* USER */ void anidb_session_set_key (anidb_session_t *session, char *key); void anidb_session_ref (anidb_session_t *session); void anidb_session_unref (anidb_session_t *session); /* Dict */ anidb_dict_t * anidb_dict_new (void); +anidb_dict_t * anidb_dict_next (anidb_dict_t *dict); void anidb_dict_ref (anidb_dict_t *dict); void anidb_dict_unref (anidb_dict_t *dict); void anidb_dict_set (anidb_dict_t *dict, char *key, char *value); int anidb_dict_get (anidb_dict_t *dict, char **out); /* Result */ anidb_result_t * anidb_result_new (int code); void anidb_result_ref (anidb_result_t *result); void anidb_result_unref (anidb_result_t *result); void anidb_result_set_str (anidb_result_t *result, char *string); void anidb_result_set_int (anidb_result_t *result, int number); void anidb_result_dict_set (anidb_result_t *result, char *key, char *value); anidb_result_type_t anidb_result_get_type (anidb_result_t *result); int anidb_result_get_code (anidb_result_t *result); int anidb_result_get_str (anidb_result_t *result, char **out); int anidb_result_get_int (anidb_result_t *result, int *out); int anidb_result_dict_get (anidb_result_t *result, char *key, char **out); +anidb_dict_t * anidb_result_get_dict (anidb_result_t *result); /* Error */ anidb_error_t * anidb_error_new (void); void anidb_error_get_code (anidb_error_t *error, int *out); void anidb_error_get_str (anidb_error_t *error, char *out); void anidb_error_set_code (anidb_error_t *error, int code); void anidb_error_set_str (anidb_error_t *error, char *str); void anidb_session_ref (anidb_session_t *session); void anidb_session_unref (anidb_session_t *session); #define ANIDB_SERVER_HOST "api.anidb.net" #define ANIDB_SERVER_PORT 9000 #define ANIDB_PROTO_VERSION "3" /* Positive responses 2XX */ #define ANIDB_LOGIN_ACCEPTED 200 #define ANIDB_LOGIN_ACCEPTED_NEW_VER 201 #define ANIDB_LOGGED_OUT 203 #define ANIDB_RESOURCE 205 #define ANIDB_STATS 206 #define ANIDB_TOP 207 #define ANIDB_UPTIME 208 #define ANIDB_ENCRYPTION_ENABLED 209 #define ANIDB_MYLIST_ENTRY_ADDED 210 #define ANIDB_MYLIST_ENTRY_DELETED 211 #define ANIDB_ADDED_FILE 214 #define ANIDB_ADDED_STREAM 215 #define ANIDB_ENCODING_CHANGED 219 #define ANIDB_FILE 220 #define ANIDB_MYLIST 221 #define ANIDB_MYLIST_STATS 222 #define ANIDB_ANIME 230 #define ANIDB_ANIME_BEST_MATCH 231 #define ANIDB_RANDOMANIME 232 #define ANIDB_ANIME_DESCRIPTION 233 #define ANIDB_EPISODE 240 #define ANIDB_PRODUCER 245 #define ANIDB_GROUP 250 #define ANIDB_BUDDY_LIST 253 #define ANIDB_BUDDY_STATE 254 #define ANIDB_BUDDY_ADDED 255 #define ANIDB_BUDDY_DELETED 256 #define ANIDB_BUDDY_ACCEPTED 257 #define ANIDB_BUDDY_DENIED 258 #define ANIDB_VOTED 260 #define ANIDB_VOTE_FOUND 261 #define ANIDB_VOTE_UPDATED 262 #define ANIDB_VOTE_REVOKED 263 #define ANIDB_NOTIFICATION_ENABLED 270 #define ANIDB_NOTIFICATION_NOTIFY 271 #define ANIDB_NOTIFICATION_MESSAGE 272 #define ANIDB_NOTIFICATION_BUDDY 273 #define ANIDB_NOTIFICATION_SHUTDOWN 274 #define ANIDB_PUSHACK_CONFIRMED 280 #define ANIDB_NOTIFYACK_SUCCESSFUL_M 281 #define ANIDB_NOTIFYACK_SUCCESSFUL_N 282 #define ANIDB_NOTIFICATION 290 #define ANIDB_NOTIFYLIST 291 #define ANIDB_NOTIFYGET_MESSAGE 292 #define ANIDB_NOTIFYGET_NOTIFY 293 #define ANIDB_SENDMSG_SUCCESSFUL 294 #define ANIDB_USER 295 /* Affirmative/Negative responses 3XX */ #define ANIDB_PONG 300 #define ANIDB_AUTHPONG 301 #define ANIDB_NO_SUCH_RESOURCE 305 #define ANIDB_API_PASSWORD_NOT_DEFINED 309 #define ANIDB_FILE_ALREADY_IN_MYLIST 310 #define ANIDB_MYLIST_ENTRY_EDITED 311 #define ANIDB_MULTIPLE_MYLIST_ENTRIES 312 #define ANIDB_SIZE_HASH_EXISTS 314 #define ANIDB_INVALID_DATA 315 #define ANIDB_STREAMNOID_USED 316 #define ANIDB_NO_SUCH_FILE 320 #define ANIDB_NO_SUCH_ENTRY 321 #define ANIDB_MULTIPLE_FILES_FOUND 322 #define ANIDB_NO_SUCH_ANIME 330 #define ANIDB_NO_SUCH_ANIME_DESCRIPTION 333 #define ANIDB_NO_SUCH_EPISODE 340 #define ANIDB_NO_SUCH_PRODUCER 345 #define ANIDB_NO_SUCH_GROUP 350 #define ANIDB_BUDDY_ALREADY_ADDED 355 #define ANIDB_NO_SUCH_BUDDY 356 #define ANIDB_BUDDY_ALREADY_ACCEPTED 357 #define ANIDB_BUDDY_ALREADY_DENIED 358 #define ANIDB_NO_SUCH_VOTE 360 #define ANIDB_INVALID_VOTE_TYPE 361 #define ANIDB_INVALID_VOTE_VALUE 362 #define ANIDB_PERMVOTE_NOT_ALLOWED 363 #define ANIDB_ALREADY_PERMVOTED 364 #define ANIDB_NOTIFICATION_DISABLED 370 #define ANIDB_NO_SUCH_PACKET_PENDING 380 #define ANIDB_NO_SUCH_ENTRY_M 381 #define ANIDB_NO_SUCH_ENTRY_N 382 #define ANIDB_NO_SUCH_MESSAGE 392 #define ANIDB_NO_SUCH_NOTIFY 393 #define ANIDB_NO_SUCH_USER 394 /* Negative responses 4XX */ #define ANIDB_NOT_LOGGED_IN 403 #define ANIDB_NO_SUCH_MYLIST_FILE 410 #define ANIDB_NO_SUCH_MYLIST_ENTRY 411 /* Client side failure 5XX */ #define ANIDB_LOGIN_FAILED 500 #define ANIDB_LOGIN_FIRST 501 #define ANIDB_ACCESS_DENIED 502 #define ANIDB_CLIENT_VERSION_OUTDATED 503 #define ANIDB_CLIENT_BANNED 504 #define ANIDB_ILLEGAL_INPUT_OR_ACCESS_DENIED 505 #define ANIDB_INVALID_SESSION 506 #define ANIDB_NO_SUCH_ENCRYPTION_TYPE 509 #define ANIDB_ENCODING_NOT_SUPPORTED 519 #define ANIDB_BANNED 555 #define ANIDB_UNKNOWN_COMMAND 598 /* Server side failure 6XX */ #define ANIDB_INTERNAL_SERVER_ERROR 600 #define ANIDB_ANIDB_OUT_OF_SERVICE 601 #define ANIDB_SERVER_BUSY 602 #define ANIDB_API_VIOLATION 666 #endif diff --git a/src/libanidb/handlers.c b/src/libanidb/handlers.c index 9d5823e..feead7b 100644 --- a/src/libanidb/handlers.c +++ b/src/libanidb/handlers.c @@ -1,97 +1,184 @@ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <netdb.h> #include <malloc.h> #include <string.h> #include <sys/socket.h> #include "util.h" #include "anidb.h" static char * get_part(char *src, int delim, int idx) { int i = 0, j = 0; char buf[1024]; while (*src != '\0') { if (i == idx && *src != delim) { buf[j] = *src; j++; } if (*src == delim) i++; src++; } buf[j++] = '\0'; return strdup(buf); } #define DICT_PART_ADD(result, data, num, name) \ anidb_result_dict_set((result), (name), get_part((data), '|', (num))) static void handler_auth_accepted (anidb_result_t *result, char *data) { char buf[10]; sscanf(data, "200 %s", &buf); anidb_result_set_str(result, buf); } static void handler_auth_logout (anidb_result_t *result, char *data) { - anidb_result_dict_set(result, "test", "hej"); - anidb_result_dict_set(result, "test1", "hej"); - anidb_result_dict_set(result, "test2", "hej"); - anidb_result_dict_set(result, "test3", "hej"); + /* pass */ } static void handler_anime (anidb_result_t *result, char *data) { char *anime; - anime = data + 10; DICT_PART_ADD(result, anime, 0, "aid"); DICT_PART_ADD(result, anime, 1, "eps"); DICT_PART_ADD(result, anime, 2, "ep_count"); DICT_PART_ADD(result, anime, 3, "special_cnt"); DICT_PART_ADD(result, anime, 4, "rating"); DICT_PART_ADD(result, anime, 5, "votes"); DICT_PART_ADD(result, anime, 6, "tmprating"); DICT_PART_ADD(result, anime, 7, "tmpvotes"); DICT_PART_ADD(result, anime, 8, "rating_average"); DICT_PART_ADD(result, anime, 9, "reviews"); DICT_PART_ADD(result, anime, 10, "year"); DICT_PART_ADD(result, anime, 11, "type"); DICT_PART_ADD(result, anime, 12, "romaji"); DICT_PART_ADD(result, anime, 13, "kanji"); DICT_PART_ADD(result, anime, 14, "english"); DICT_PART_ADD(result, anime, 15, "other"); DICT_PART_ADD(result, anime, 16, "short_names"); DICT_PART_ADD(result, anime, 17, "synonyms"); DICT_PART_ADD(result, anime, 18, "category_list"); } +static void +handler_animedesc (anidb_result_t *result, char *data) +{ + char *desc; + + desc = data + 14; + + DICT_PART_ADD(result, desc, 0, "part"); + DICT_PART_ADD(result, desc, 1, "max_parts"); + DICT_PART_ADD(result, desc, 2, "description"); +} + +static void +handler_episode (anidb_result_t *result, char *data) +{ + char *episode; + + episode = data + 12; + + DICT_PART_ADD(result, episode, 0, "eid"); + DICT_PART_ADD(result, episode, 1, "aid"); + DICT_PART_ADD(result, episode, 2, "length"); + DICT_PART_ADD(result, episode, 3, "rating"); + DICT_PART_ADD(result, episode, 4, "votes"); + DICT_PART_ADD(result, episode, 5, "epno"); + DICT_PART_ADD(result, episode, 6, "eng"); + DICT_PART_ADD(result, episode, 7, "romaji"); + DICT_PART_ADD(result, episode, 8, "kanji"); + DICT_PART_ADD(result, episode, 9, "aired"); +} + +static void +handler_file (anidb_result_t *result, char *data) +{ + char *file; + + file = data + 9; + + DICT_PART_ADD(result, file, 0, "fid"); + DICT_PART_ADD(result, file, 1, "aid"); + DICT_PART_ADD(result, file, 2, "eid"); + DICT_PART_ADD(result, file, 3, "gid"); + DICT_PART_ADD(result, file, 4, "state"); + DICT_PART_ADD(result, file, 5, "size"); + DICT_PART_ADD(result, file, 6, "ed2k"); + DICT_PART_ADD(result, file, 7, "filename"); +} + +static void +handler_group (anidb_result_t *result, char *data) +{ + char *group; + + group = data + 10; + + DICT_PART_ADD(result, group, 0, "gid"); + DICT_PART_ADD(result, group, 1, "rating"); + DICT_PART_ADD(result, group, 2, "votes"); + DICT_PART_ADD(result, group, 3, "acount"); + DICT_PART_ADD(result, group, 4, "fcount"); + DICT_PART_ADD(result, group, 5, "name"); + DICT_PART_ADD(result, group, 6, "short"); + DICT_PART_ADD(result, group, 7, "irc_channel"); + DICT_PART_ADD(result, group, 8, "irc_server"); + DICT_PART_ADD(result, group, 9, "url"); +} + anidb_result_handler_t anidb_handlers[] = { /* AUTH */ - { ANIDB_LOGIN_ACCEPTED, handler_auth_accepted }, - { ANIDB_LOGGED_OUT, handler_auth_logout }, + { ANIDB_LOGIN_ACCEPTED, handler_auth_accepted }, + { ANIDB_LOGGED_OUT, handler_auth_logout }, /* ANIME */ - { ANIDB_ANIME, handler_anime }, + { ANIDB_ANIME, handler_anime }, + + /* ANIMEDESC */ + { ANIDB_ANIME_DESCRIPTION, handler_animedesc }, + + /* EPISODE */ + { ANIDB_EPISODE, handler_episode }, + + /* FILE */ + { ANIDB_FILE, handler_file }, + + /* GROUP */ + { ANIDB_GROUP, handler_group }, + /* GROUPSTATUS */ + /* MYLIST */ + /* MYLISTADD */ + /* MYLISTDEL */ + /* MYLISTSTATS */ + /* VOTE */ + /* RANDOM */ + /* PING */ + /* UPTIME */ + /* ENCODING */ + /* SENDMSG */ + /* USER */ }; diff --git a/test.sh b/test.sh new file mode 100755 index 0000000..8687c39 --- /dev/null +++ b/test.sh @@ -0,0 +1,5 @@ +#!/bin/sh + +export LD_LIBRARY_PATH=./_build_/default/src/libanidb/ + +./_build_/default/src/anidbfs/anidbfs-update fusetest testuser
trnsfr/crudlinks
994654f52b6638eca9caf9140a2766f30fbeea50
fixed split on comma thing with proper regex
diff --git a/lib/crudlinks.rb b/lib/crudlinks.rb index 24a965e..b4b085e 100644 --- a/lib/crudlinks.rb +++ b/lib/crudlinks.rb @@ -1,94 +1,94 @@ # Creats a <ul class="crud_links"> with links as list items. # Use like so: <%= CrudLinks.new(self, @controller, @link_options).to_html {yield :yr_blk} %> # # Options are +controller_name+ and +hide+. # # To change behavior in a view: # # crudlinks(:hide => true, :controller_name => 'foo') do # link_to 'home', admin_path # link_to 'vacation', vacation_path # end module Crudlink::ViewHelper def crudlinks(options={}, &blk) @crudlink_options = options cap = block_given? ? capture(&blk) : '' content_for(:link_content) {cap} end end class Crudlinks def initialize(template, controller, options={}) options ||= {} # Don't ask @template, @controller = template, controller set_instance_by_controller_name @link_controller = (options[:controller_name] || @name.pluralize) @hide = (options[:hide] || false) end def edit_link path = {:controller => @link_controller, :action => "edit", :id => @instance} link_to("Edit #{@name.titleize}", path, :class => "button edit") end def extract_links(links="") - @extra_links = links.split(",") rescue [] + @extra_links ||= links.scan(/<a.*?>.*?<\/a>/) rescue [] end def delete_link path = {:controller => @link_controller, :action => "destroy", :id => @instance} link_to("Delete #{@name.titleize}", path, :confirm => 'Are you sure?', :method => :delete, :class => "button delete") end def index_link path = {:controller => @link_controller, :action => "index"} link_to("Back to index", path, :class => "button list") end def new_link path = {:controller => @link_controller, :action => "new"} link_to("Create #{@name.titleize}", path, :class => "button new") end def show_link path = {:controller => @link_controller, :action => "show", :id => @instance} link_to("Back to show", path, :class => "button list") end def to_html(&blk) extract_links(blk.call) action_links = {:index => [new_link], :new => [index_link], :edit => [show_link, index_link], :show => [edit_link, delete_link, index_link], :search => [index_link] } @extra_links.unshift(action_links[params[:action].to_sym]) unless @hide content_tag(:ul, (@extra_links.flatten.compact.map{ |link| content_tag(:li, link) }), :class => 'crud_links') end def method_missing(*args, &block) @template.send(*args, &block) end private # Finds an instance variable named after the controller if there is one. # def set_instance_by_controller_name @name = @controller.controller_name.singularize @instance = get_instance_variable(@name) end def get_instance_variable(variable) @controller.instance_variable_get("@#{variable}") if @controller.instance_variables.include?("@#{variable}") end end
trnsfr/crudlinks
91064d22e028382f0c434e85420cf86413dc0a63
initial
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 b/README new file mode 100644 index 0000000..3f3b92e --- /dev/null +++ b/README @@ -0,0 +1,13 @@ +Crudlinks +========= + +Introduction goes here. + + +Example +======= + +Example goes here. + + +Copyright (c) 2008 [name of plugin creator], released under the MIT license diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..f38ee0a --- /dev/null +++ b/Rakefile @@ -0,0 +1,22 @@ +require 'rake' +require 'rake/testtask' +require 'rake/rdoctask' + +desc 'Default: run unit tests.' +task :default => :test + +desc 'Test the crudlinks plugin.' +Rake::TestTask.new(:test) do |t| + t.libs << 'lib' + t.pattern = 'test/**/*_test.rb' + t.verbose = true +end + +desc 'Generate documentation for the crudlinks plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'Crudlinks' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README') + rdoc.rdoc_files.include('lib/**/*.rb') +end diff --git a/init.rb b/init.rb new file mode 100644 index 0000000..bb0ef1c --- /dev/null +++ b/init.rb @@ -0,0 +1,3 @@ +# Include hook code here +require 'crudlinks' +ActionView::Base.send(:include, Crudlink::ViewHelper) diff --git a/install.rb b/install.rb new file mode 100644 index 0000000..f7732d3 --- /dev/null +++ b/install.rb @@ -0,0 +1 @@ +# Install hook code here diff --git a/lib/.DS_Store b/lib/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/lib/.DS_Store differ diff --git a/lib/crudlinks.rb b/lib/crudlinks.rb new file mode 100644 index 0000000..24a965e --- /dev/null +++ b/lib/crudlinks.rb @@ -0,0 +1,94 @@ +# Creats a <ul class="crud_links"> with links as list items. +# Use like so: <%= CrudLinks.new(self, @controller, @link_options).to_html {yield :yr_blk} %> +# +# Options are +controller_name+ and +hide+. +# +# To change behavior in a view: +# +# crudlinks(:hide => true, :controller_name => 'foo') do +# link_to 'home', admin_path +# link_to 'vacation', vacation_path +# end + + +module Crudlink::ViewHelper + def crudlinks(options={}, &blk) + @crudlink_options = options + cap = block_given? ? capture(&blk) : '' + content_for(:link_content) {cap} + end +end + + +class Crudlinks + + def initialize(template, controller, options={}) + options ||= {} # Don't ask + @template, @controller = template, controller + set_instance_by_controller_name + @link_controller = (options[:controller_name] || @name.pluralize) + @hide = (options[:hide] || false) + end + + + def edit_link + path = {:controller => @link_controller, :action => "edit", :id => @instance} + link_to("Edit #{@name.titleize}", path, :class => "button edit") + end + + + def extract_links(links="") + @extra_links = links.split(",") rescue [] + end + + + def delete_link + path = {:controller => @link_controller, :action => "destroy", :id => @instance} + link_to("Delete #{@name.titleize}", path, :confirm => 'Are you sure?', :method => :delete, :class => "button delete") + end + + + def index_link + path = {:controller => @link_controller, :action => "index"} + link_to("Back to index", path, :class => "button list") + end + + + def new_link + path = {:controller => @link_controller, :action => "new"} + link_to("Create #{@name.titleize}", path, :class => "button new") + end + + + def show_link + path = {:controller => @link_controller, :action => "show", :id => @instance} + link_to("Back to show", path, :class => "button list") + end + + + def to_html(&blk) + extract_links(blk.call) + action_links = {:index => [new_link], :new => [index_link], :edit => [show_link, index_link], :show => [edit_link, delete_link, index_link], :search => [index_link] } + @extra_links.unshift(action_links[params[:action].to_sym]) unless @hide + content_tag(:ul, (@extra_links.flatten.compact.map{ |link| content_tag(:li, link) }), :class => 'crud_links') + end + + + def method_missing(*args, &block) + @template.send(*args, &block) + end + +private + + # Finds an instance variable named after the controller if there is one. + # + def set_instance_by_controller_name + @name = @controller.controller_name.singularize + @instance = get_instance_variable(@name) + end + + + def get_instance_variable(variable) + @controller.instance_variable_get("@#{variable}") if @controller.instance_variables.include?("@#{variable}") + end +end diff --git a/tasks/crudlinks_tasks.rake b/tasks/crudlinks_tasks.rake new file mode 100644 index 0000000..f4eb310 --- /dev/null +++ b/tasks/crudlinks_tasks.rake @@ -0,0 +1,4 @@ +# desc "Explaining what the task does" +# task :crudlinks do +# # Task goes here +# end diff --git a/test/crudlinks_test.rb b/test/crudlinks_test.rb new file mode 100644 index 0000000..639b088 --- /dev/null +++ b/test/crudlinks_test.rb @@ -0,0 +1,8 @@ +require 'test/unit' + +class CrudlinksTest < Test::Unit::TestCase + # Replace this with your real tests. + def test_this_plugin + flunk + end +end diff --git a/uninstall.rb b/uninstall.rb new file mode 100644 index 0000000..9738333 --- /dev/null +++ b/uninstall.rb @@ -0,0 +1 @@ +# Uninstall hook code here
mattmccray/boilerplate
ae5172d86796afc6b6854a852157bbd7f9e414cc
initial import into git
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..89a9274 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.DS_Store +pkg \ No newline at end of file diff --git a/Changes b/Changes new file mode 100644 index 0000000..8223510 --- /dev/null +++ b/Changes @@ -0,0 +1 @@ +# Populate this file by git log > Changes diff --git a/Manifest b/Manifest new file mode 100644 index 0000000..9df5ae0 --- /dev/null +++ b/Manifest @@ -0,0 +1,11 @@ +Changes +Manifest +Rakefile +Readme.markdown +bin/boilerplate +boilerplate.gemspec +lib/boilerplate.rb +lib/boilerplate/cli.rb +lib/boilerplate/version.rb +test/helper.rb +test/test_boilerplate.rb diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..f98fed3 --- /dev/null +++ b/Rakefile @@ -0,0 +1,86 @@ +$: << 'lib' +require 'rake' +require 'rake/testtask' +require 'rake/gempackagetask' +require 'boilerplate/version' + +spec = Gem::Specification.new do |s| + s.platform = Gem::Platform::RUBY + s.summary = "DESCRIPTION" + s.name = 'boilerplate' + s.version = Boilerplate::VERSION + s.author = 'AUTHOR' + s.email = 'EMAIL' + s.homepage = 'HOMEPAGE' + + # s.requirements << 'rake' + s.require_path = 'lib' + s.autorequire = 'rake' + s.files = File.read("Manifest").split + s.executables = s.files.grep(/bin/) { |f| File.basename(f) } + s.description = <<EOF +YOUR DESCRIPTION HERE +EOF +end + +Rake::GemPackageTask.new(spec) do |pkg| + pkg.need_zip = true + pkg.need_tar = true +end + +Rake::TestTask.new do |t| + t.libs << 'test' + t.test_files = FileList['test/test*.rb'] + t.verbose = false +end + +task :default=>:test + +namespace :gem do + desc "Create the gemspec file" + task :spec do + File.open("boilerplate.gemspec", "w") do |file| + file.puts spec.to_ruby + end + end +end + +desc 'Clean up' +task :clean => :clobber_package do + %w(diff diff email ri *.gem **/*~ .DS_Store).each do |pattern| + files = Dir[pattern] + rm_rf files unless files.empty? + end +end + +namespace :manifest do + desc "Verify the manifest" + task :check => :clean do + f = "Manifest.tmp" + require 'find' + files = [] + Find.find '.' do |path| + next unless File.file? path + next if path =~ /\.git|tmp$|\.DS_Store/ + files << path[2..-1] + end + files = files.sort.join "\n" + File.open f, 'w' do |fp| fp.puts files end + system "diff -du Manifest #{f}" + rm f + end + + desc "Create the manifest" + task :create => :clean do + f = "Manifest" + require 'find' + files = [] + Find.find '.' do |path| + next unless File.file? path + next if path =~ /\.git|tmp$|\.DS_Store/ + files << path[2..-1] + end + files = files.sort.join "\n" + File.open f, 'w' do |fp| fp.puts files end + end +end diff --git a/Readme.markdown b/Readme.markdown new file mode 100644 index 0000000..a17ea82 --- /dev/null +++ b/Readme.markdown @@ -0,0 +1,3 @@ +# Boilerplate + +Fill out some info about the project here... diff --git a/bin/gen-boilerplate b/bin/gen-boilerplate new file mode 100644 index 0000000..2b21d4e --- /dev/null +++ b/bin/gen-boilerplate @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby + +# +# Generates the source for a boilerplate from a template folder/file structure on the filesystem... +# + +puts "Coming soon..." \ No newline at end of file diff --git a/bin/gen-gem b/bin/gen-gem new file mode 100644 index 0000000..5dea350 --- /dev/null +++ b/bin/gen-gem @@ -0,0 +1,199 @@ +#!/usr/bin/env ruby + +$: << File.expand_path(File.dirname(__FILE__) + "/../lib") +require "boilerplate" +require "boilerplate/cli" + +base_name, opts = Boilerplate.parse_args! + +newgem = Boilerplate::Builder.new(base_name, DATA) do + folder(base_name) { + folder('bin') { + file('bin_file', :filename=>"#{project_name}") + } + folder('lib') { + folder(base_name) { + file('cli.rb') + file('version.rb') + } + file('project_name.rb', :filename=>"#{project_name}.rb") + } + folder('test') { + file('helper.rb') + file('test_project_name.rb', :filename=>"test_#{project_name}.rb") + } + file('Readme.markdown') + file('Rakefile') + file('Changes') + file('Manifest') + file('project_name.gemspec', :filename=>"#{project_name}.gemspec") + file('gitignore', :filename=>".gitignore") + } +end + +newgem.execute(opts) + +__END__ +--- +Manifest: | + # Populate this file by running rake manifest:create + +Readme.markdown: | + # <%= project_title %> + + Fill out some info about the project here... + + +Rakefile: | + $: << 'lib' + require 'rake' + require 'rake/testtask' + require 'rake/gempackagetask' + require '<%= project_name %>/version' + + spec = Gem::Specification.new do |s| + s.platform = Gem::Platform::RUBY + s.summary = "DESCRIPTION" + s.name = '<%= project_name %>' + s.version = <%= project_module %>::VERSION + s.author = 'AUTHOR' + s.email = 'EMAIL' + s.homepage = 'HOMEPAGE' + + # s.requirements << 'rake' + s.require_path = 'lib' + s.autorequire = 'rake' + s.files = File.read("Manifest").split + s.executables = s.files.grep(/bin/) { |f| File.basename(f) } + s.description = <<EOF + YOUR DESCRIPTION HERE + EOF + end + + Rake::GemPackageTask.new(spec) do |pkg| + pkg.need_zip = true + pkg.need_tar = true + end + + Rake::TestTask.new do |t| + t.libs << 'test' + t.test_files = FileList['test/test*.rb'] + t.verbose = false + end + + task :default=>:test + + namespace :gem do + desc "Create the gemspec file" + task :spec do + File.open("<%= project_name %>.gemspec", "w") do |file| + file.puts spec.to_ruby + end + end + end + + desc 'Clean up' + task :clean => :clobber_package do + %w(diff diff email ri *.gem **/*~ .DS_Store).each do |pattern| + files = Dir[pattern] + rm_rf files unless files.empty? + end + end + + namespace :manifest do + desc "Verify the manifest" + task :check => :clean do + f = "Manifest.tmp" + require 'find' + files = [] + Find.find '.' do |path| + next unless File.file? path + next if path =~ /\.git|tmp$|\.DS_Store/ + files << path[2..-1] + end + files = files.sort.join "\n" + File.open f, 'w' do |fp| fp.puts files end + system "diff -du Manifest #{f}" + rm f + end + + desc "Create the manifest" + task :create => :clean do + f = "Manifest" + require 'find' + files = [] + Find.find '.' do |path| + next unless File.file? path + next if path =~ /\.git|tmp$|\.DS_Store/ + files << path[2..-1] + end + files = files.sort.join "\n" + File.open f, 'w' do |fp| fp.puts files end + end + end + +Changes: | + # Populate this file by git log > Changes + + +test_project_name.rb: | + require 'helper' + + class <%= project_module %>Test < Test::Unit::TestCase + + context "<%= project_title %>" do + + setup do + # Some setup stuff here... + end + + should "create tests" do + assert false, "Implement your tests!!" + end + + end + + end + +bin_file: | + #!/usr/bin/env ruby + + $: << File.expand_path(File.dirname(__FILE__) + "/../lib") + require "<%= project_name %>" + require "<%= project_name %>/cli" + + <%= project_module %>::CLI.run(ARGV) + +helper.rb: | + require 'rubygems' + require 'test/unit' + require 'shoulda' + $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') + require '<%= project_name %>' + +project_name.gemspec: | + # Populate this file by running rake gem:spec + + +project_name.rb: | + require '<%= project_name %>/version' + +cli.rb: | + module <%= project_module %> + class CLI + class << self + def run(args) + puts "<%= project_title %> command line interface... Done." + end + end + end + end + +version.rb: | + module <%= project_module %> + VERSION = "0.1" + end + +gitignore: | + .DS_Store + pkg \ No newline at end of file diff --git a/bin/gen-sinatra b/bin/gen-sinatra new file mode 100644 index 0000000..9eab11b --- /dev/null +++ b/bin/gen-sinatra @@ -0,0 +1,239 @@ +#!/usr/bin/env ruby + +$: << File.expand_path(File.dirname(__FILE__) + "/../lib") +require "boilerplate" +require "boilerplate/cli" + +base_name, opts = Boilerplate.parse_args! + +sinatra = Boilerplate.new(base_name, DATA) do + + folder(project_name) { + file('app.rb') + file('Capfile') + file('Rakefile') + file('config.ru') + folder('db') { + folder('migrations') { + file('001_initial_schema.rb') + } + } + folder('lib') { + folder(project_name) { + file('controllers.rb') + file('models.rb') + file('helpers.rb') + file('test_helper.rb') + } + file('project_name.rb', :filename=>"#{project_name}.rb") + } + folder('public') { + folder('theme') { + folder('styles') { + file('main.css') + } + folder('scripts') + folder('images') + } + } + folder('views') { + file('layout.erb', :erb=>false) + file('index.erb', :erb=>false) + } + folder('vendor') { + gem_unpack('sinatra', :as=>'sinatra') + gem_unpack('sequel', :as=>'sinatra') + file('paths.rb', :include=>['sinatra', 'sequel']) + } + folder('test') { + file('test_project_name.rb', :filename=>"test_#{project_name}.rb") + } + } + +end + +sinatra.execute(opts) + +__END__ +--- +controllers.rb: | + get '/' do + erb :index + end + +app.rb: | + require 'rubygems' + require File.join(File.dirname(__FILE__), 'vendor', 'paths.rb') unless defined?(APP_ROOT) + require 'sinatra' + require 'sequel' + + unless Sinatra.application.reloading? + DB = Sequel.sqlite( local_path( 'db', '<%= project_name %>.db.sqlite3' ) ) + current_version = Sequel::Migrator.get_current_migration_version(DB) + latest_version = Sequel::Migrator.apply(DB, local_path("db","migrations") ) + puts 'Migrations loaded!' if current_version < latest_version + end + + set :public, 'public' + set :views, 'views' + + require '<%= project_name %>' + + helpers do + include Helpers + include Rack::Utils + alias_method :h, :escape_html + end + +project_name.rb: | + require '<%= project_name %>/helpers' + require '<%= project_name %>/models' + require '<%= project_name %>/controllers' + + +models.rb: | + # Your Sequel models here... + # class ModelName < Sequel::Model ; end + +index.erb: | + <p>Hello! Welcome to <%= project_name %></p> + +main.css: | + BODY { + font-family: "lucida grande", "tahoma", sans-serif; + } + +paths.rb: | + APP_ROOT = File.expand_path(File.dirname(__FILE__)) unless defined?(APP_ROOT) + + def local_path(*args) + File.join(APP_ROOT, *args) + end + + # Add local lib directory to load path... + $:.unshift local_path('lib', '<%= project_name %>') + + # Add vendored directories to load path... + $:.unshift local_path('vendor', 'sinatra', 'lib') + $:.unshift local_path('vendor', 'sequel', 'lib') + + +Rakefile: | + require 'rubygems' + require 'rake' + require 'vendor/paths' + + namespace :<%= project_name %> do + + desc "Setup" + task :setup do + puts "I don't do anything yet..." + end + + end + +layout.erb: | + <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> + <head> + <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> + <title>Welcome</title> + </head> + <body> + <%= yield %> + </body> + </html> + + +test_project_name.rb: | + require 'test_helper' + + class <%= project_name.capitalize %>Test < Test::Unit::TestCase + + context "<%= project_name.capitalize %>" do + + context "get /" do + setup do + get_it '/' + end + + should "respond" do + assert @response.body + end + end + + end + + end + +test_helper.rb: | + require 'rubygems' + $:.unshift File.join(File.dirname(__FILE__), '..', 'vendor', 'sinatra', 'lib') + $:.unshift File.join(File.dirname(__FILE__), '..', 'vendor', 'sequel', 'lib') + require 'sinatra' + require 'sinatra/test/unit' + require 'shoulda' + require File.join(File.dirname(__FILE__), '..', 'app.rb') + +helpers.rb: | + module Helpers + def short_date(date) + date.strftime('%m/%d/%Y') + end + end + +Capfile: | + load 'deploy' if respond_to?(:namespace) # cap2 differentiator + + default_run_options[:pty] = true + + # be sure to change these + set :user, 'username' + set :domain, 'yourdomain.com' + set :application, '<%= project_name %>' + + # the rest should be good + set :repository, "#{user}@#{domain}:git/#{application}.git" + set :deploy_to, "/home/#{user}/#{domain}" + set :deploy_via, :remote_cache + set :scm, 'git' + set :branch, 'master' + set :git_shallow_clone, 1 + set :scm_verbose, true + set :use_sudo, false + + server domain, :app, :web + + namespace :deploy do + task :restart do + run "touch #{current_path}/tmp/restart.txt" + end + end + +config.ru: | + require 'rubygems' + require File.join(File.dirname(__FILE__), 'vendor', 'paths.rb') + require local_path('app.rb') + + Sinatra::Application.default_options.merge!( + :run => false, + :env => ENV.fetch('RACK_ENV', :production), + :views => local_path('views'), + :public => local_path('public') + ) + + run Sinatra.application + +001_initial_schema.rb: | + class InitialSchema < Sequel::Migration + def up + create_table :table_name do + primary_key :id + datetime :created_at + datetime :updated_at + end + end + + def down + drop_table :table_name + end + end diff --git a/boilerplate.gemspec b/boilerplate.gemspec new file mode 100644 index 0000000..75c59fe --- /dev/null +++ b/boilerplate.gemspec @@ -0,0 +1,30 @@ +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{boilerplate} + s.version = "0.1" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["AUTHOR"] + s.autorequire = %q{rake} + s.date = %q{2009-01-03} + s.default_executable = %q{boilerplate} + s.description = %q{YOUR DESCRIPTION HERE} + s.email = %q{EMAIL} + s.executables = ["boilerplate"] + s.files = ["Changes", "Manifest", "Rakefile", "Readme.markdown", "bin/boilerplate", "boilerplate.gemspec", "lib/boilerplate.rb", "lib/boilerplate/cli.rb", "lib/boilerplate/version.rb", "test/helper.rb", "test/test_boilerplate.rb"] + s.homepage = %q{HOMEPAGE} + s.require_paths = ["lib"] + s.rubygems_version = %q{1.3.1} + s.summary = %q{DESCRIPTION} + + if s.respond_to? :specification_version then + current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION + s.specification_version = 2 + + if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then + else + end + else + end +end diff --git a/lib/boilerplate.rb b/lib/boilerplate.rb new file mode 100644 index 0000000..46f3d8a --- /dev/null +++ b/lib/boilerplate.rb @@ -0,0 +1,8 @@ +require 'yaml' +require 'erb' +require 'rubygems' +require 'active_support/inflector' +require 'active_support/core_ext/string' + +require 'boilerplate/version' +require 'boilerplate/builder' diff --git a/lib/boilerplate/builder.rb b/lib/boilerplate/builder.rb new file mode 100644 index 0000000..ec204ae --- /dev/null +++ b/lib/boilerplate/builder.rb @@ -0,0 +1,121 @@ +module Boilerplate + + class Builder + + attr_accessor :type, :data, :project_title, :project_name, :project_module, :path, :folders, :files, :gems, :commands, :options + + def initialize(title, data, &block) + @type = type + @data = if data.is_a? File + YAML.load(data) + else + data + end + @project_title = title.titlecase + @project_name = project_title.gsub(' ', '').underscore + @project_module = project_name.camelcase + @path = [] + @block = block + @files = [] + @folders = [] + @gems = [] + @commands = [] + @options = {} + end + + def execute(opts={}) + @options = opts + instance_eval(&@block) + s = "\n" + s << (is_dryrun? ? "Would have created" : "Created") + s << " #{@folders.length} folders, #{files.length} files. " + s << "Unpacked #{@gems.length} gems." if @gems.length > 0 + s << "Executed #{@commands.length} commands." if @commands.length > 0 + info s, true + end + + def full_path + path.join('/') + end + + def folder(name, opts={}, &block) + info "#{ " " * full_path.length }#{name}/" + @folders << name + @path << name + unless is_dryrun? + FileUtils.mkdir_p(full_path) + end + instance_eval(&block) if block_given? + @path.pop + end + alias_method :dir, :folder + alias_method :d, :folder + + def file(name, opts={}, &block) + # Body from opts or data + body = opts[:body] || data[name] || "" + # Filename from opts or name + name = opts[:filename] || name + # Run body through ERB... + body = ERB.new(body).result(binding) unless body.empty? or opts[:erb] == false + info "#{ " " * full_path.length }#{name}" + @files << name + unless is_dryrun? + File.open(File.join(full_path, name), 'w') do |f| + f.write body + end + end + end + alias_method :f, :file + + def cmd(line, opts={}, &block) + results = `#{line}` + yield results if block_given? + end + + def gem_unpack(name, opts={}, &block) + info "#{ " " * full_path.length }@#{name}" + @gems << name + end + alias_method :gem, :gem_unpack + alias_method :g, :gem_unpack + + def set(key, value=nil, &block) + value = if block_given? + block.call + else + value + end + @data[key] = value + end + + def info(msg, force=false) + if is_verbose? or force + puts msg + end + end + + def method_missing(key, *args) + if @data.has_key?(key) + @data[key] + else + super(key, *args) + end + end + + protected + + def is_dryrun? + options.fetch(:dry, false) + end + + def is_quiet? + options.fetch(:quiet, false) + end + def is_verbose? + !is_quiet? + end + + end + +end \ No newline at end of file diff --git a/lib/boilerplate/cli.rb b/lib/boilerplate/cli.rb new file mode 100644 index 0000000..c1d1230 --- /dev/null +++ b/lib/boilerplate/cli.rb @@ -0,0 +1,35 @@ +require 'trollop' + +module Boilerplate + class << self + + def parse_args!(args=ARGV) + name, opts = parse_args(args) + if name.nil? + puts 'Error. You must specify a project name.' + exit(1) + else + [name, opts] + end + end + + def parse_args(args=ARGV) + opts = Trollop::options do + version "Boilerplate Generator 0.1 (c) 2008 M@ McCray" + banner <<-EOS + Usage: + gen-* [options] <project_name> + Where * is the boilerplate generator name and [options] are: + EOS + opt :quiet, "Reduce output verbosity", :default => false # a flag --verbose, defaulting to false + opt :dry, "Dry run, do not actually create files or directories", :default => false + end + if args.length > 0 + [args[0], opts] + else + [nil, {}] + end + end + end + +end diff --git a/lib/boilerplate/version.rb b/lib/boilerplate/version.rb new file mode 100644 index 0000000..6247577 --- /dev/null +++ b/lib/boilerplate/version.rb @@ -0,0 +1,3 @@ +module Boilerplate + VERSION = "0.1" +end diff --git a/test/helper.rb b/test/helper.rb new file mode 100644 index 0000000..40b0b78 --- /dev/null +++ b/test/helper.rb @@ -0,0 +1,5 @@ +require 'rubygems' +require 'test/unit' +require 'shoulda' +$:.unshift File.join(File.dirname(__FILE__), '..', 'lib') +require 'boilerplate' diff --git a/test/test_boilerplate.rb b/test/test_boilerplate.rb new file mode 100644 index 0000000..f3a095b --- /dev/null +++ b/test/test_boilerplate.rb @@ -0,0 +1,17 @@ +require 'helper' + +class BoilerplateTest < Test::Unit::TestCase + + context "Boilerplate" do + + setup do + # Some setup stuff here... + end + + should "create tests" do + assert false, "Implement your tests!!" + end + + end + +end
GICodeWarrior/goodie-bag
f20aca580d66e209148c74af38f20cba4d3d8aa8
Add script for viewing lines added by each user over time
diff --git a/git_lines_added.sh b/git_lines_added.sh new file mode 100755 index 0000000..7bdd6c2 --- /dev/null +++ b/git_lines_added.sh @@ -0,0 +1,9 @@ +#!/bin/sh + +git_log_options=$* + +git log \ + | awk '/Author:/{print$2}' \ + | sort -u \ + | xargs -n1 -I@ echo 'git log --author=@ --shortstat '"$git_log_options"' | awk -F, '"'"'/files changed/{c += $2-$3} END{print "@: "c}'"'"'' \ + | sh
GICodeWarrior/goodie-bag
93102b98a52c32e64b8be3c3f56752ef29af2fa8
Add script to dump hypertable schema.
diff --git a/dump_ht_schema.sh b/dump_ht_schema.sh new file mode 100755 index 0000000..a4aa10a --- /dev/null +++ b/dump_ht_schema.sh @@ -0,0 +1,32 @@ +#!/bin/sh +# +# Copyright (c) 2009 Rusty Burchfield +# +# 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. +# +# Simple script to rip the schema out of hypertable. + +ht="`which hypertable` --batch" + +echo 'show tables;' \ + | $ht \ + | sed '/^METADATA$/D;s/^\(.*\)$/show create table \1;/' \ + | $ht \ + | sed 's/^)$/);/'
GICodeWarrior/goodie-bag
cea3875de86c002cd95452a1c26128b6028967df
Add a bunch more scripts and apply licenses
diff --git a/cleanse_empty_dirs_under_svn.sh b/cleanse_empty_dirs_under_svn.sh new file mode 100755 index 0000000..8a20720 --- /dev/null +++ b/cleanse_empty_dirs_under_svn.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# +# Copyright (c) 2009 Rusty Burchfield +# +# 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. +# +# Crude script to remove empty directories under svn. These can build up if +# you use git-svn. Execute from within the root of an svn checkout. You will +# need to make multiple passes of this script and svn commit. + +find . \ + | sed 's%/[^\/]*$%%' \ + | sort -r \ + | uniq -c \ + | awk '/^ *1 / && !/.svn/{print"svn rm "$2}' \ + | sh diff --git a/export-firefox-cookies.py b/export-firefox-cookies.py new file mode 100755 index 0000000..6fa2550 --- /dev/null +++ b/export-firefox-cookies.py @@ -0,0 +1,57 @@ +#!/usr/bin/python +# +# Copyright (c) 2009 Rusty Burchfield +# +# 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. +# +# Given a cookies.sqlite from your firefox profile, an output file and any part +# of a hostname will export all of the matching cookies into the output file. + +import sqlite3 as db +import sys + +cookiedb = sys.argv[1] +targetfile = sys.argv[2] +what = '%' + sys.argv[3] + '%' + +print "Filter: %s" % what + +connection = db.connect(cookiedb) +cursor = connection.cursor() +statement = """ + SELECT host, path, isSecure, expiry, name, value + FROM moz_cookies + WHERE host LIKE ? +""" + +cursor.execute(statement, (what,)) + +file = open(targetfile, 'w') +format = "%s\tTRUE\t%s\t%s\t%d\t%s\t%s\n" +index = 0 +for row in cursor.fetchall(): + file.write(format % (row[0], row[1], str(bool(row[2])).upper(), row[3], + str(row[4]), str(row[5]))) + index += 1 + +print "Count: %d" % index + +file.close() +connection.close() diff --git a/find_unused_images.sh b/find_unused_images.sh new file mode 100755 index 0000000..3b0dd81 --- /dev/null +++ b/find_unused_images.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# +# Copyright (c) 2009 Rusty Burchfield +# +# 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. +# +# Helps to find images that are not being referenced in your application. + +if [ $# -lt 2 ] +then + echo 'Usage: find_unused_images.sh <image path> <search path>...' >> /dev/stderr + echo 'Example: find_unused_images.sh public/images app public/stylesheets public/javascripts' >> /dev/stderr + exit 1 +fi + +image_path=$1 +shift +search_path=$* + +escaped_image_path=$(echo $image_path | sed 's/\//\\\//g') +escaped_search_path=$(echo $search_path | sed 's/\//\\\//g') + +find $image_path -maxdepth 1 -type f -printf %f\\n \ + | sort \ + | sed 's/^\(.*\)\.\([^.]*\)$/grep -qR "\1" '"$escaped_search_path"' || echo '"$escaped_image_path"'\/\1.\2/' \ + | sh + diff --git a/git-diff-to-svn.rb b/git-diff-to-svn.rb new file mode 100755 index 0000000..436ef25 --- /dev/null +++ b/git-diff-to-svn.rb @@ -0,0 +1,38 @@ +#!/usr/bin/ruby -w +# +# Copyright (c) 2009 Rusty Burchfield +# +# 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. +# +# Crude attempt to make a git diff look like an svn diff. Useful for tools +# that only like svn diffs. + +diff_options=ARGV.join(' ') +diff = `unset GIT_EXTERNAL_DIFF; git diff #{diff_options}`; +svn_rev = `git svn info | awk '/^Revision: /{print$2}'`.chomp + +diff.gsub!(/^diff --git (.*\n)+?--- .*\n\+\+\+ .*\n/) do |matched| + file = matched.match(/^--- a\/.*$/).to_s.sub(/^--- a\//, '') + "Index: #{file}\n#{'='*66}\n" + + "--- #{file}\t(revision #{svn_rev})\n" + + "+++ #{file}\t(working copy)\n" +end + +puts diff diff --git a/git_update_with_master.sh b/git_update_with_master.sh new file mode 100755 index 0000000..d1dd218 --- /dev/null +++ b/git_update_with_master.sh @@ -0,0 +1,32 @@ +#!/bin/sh +# +# Copyright (c) 2009 Rusty Burchfield +# +# 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. +# +# Update my local branch and the master branch at the same time so I can diff +# and interactive rebase against it. + +branch=`git branch | awk '/^\*/{print$2}'` + +git svn rebase \ + && git checkout master \ + && git svn rebase \ + && git checkout $branch diff --git a/gvimdiff-wrapper.sh b/gvimdiff-wrapper.sh new file mode 100755 index 0000000..2bc5425 --- /dev/null +++ b/gvimdiff-wrapper.sh @@ -0,0 +1,37 @@ +#!/bin/sh +# +# Copyright (c) 2009 Rusty Burchfield +# +# 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. +# +# Wrapper for gvimdiff so it can be used as an git external diff tool. + +gvimdiff_path=/usr/bin/gvimdiff + +path=$1 +old_file=$2 +old_hex=$3 +old_mode=$4 +new_file=$5 +new_hex=$6 +new_mode=$7 + +$gvimdiff_path --nofork $old_file $new_file + diff --git a/partial_hierarchy.rb b/partial_hierarchy.rb index a3e464a..15dc3ff 100755 --- a/partial_hierarchy.rb +++ b/partial_hierarchy.rb @@ -1,33 +1,55 @@ #!/usr/bin/ruby +# +# Copyright (c) 2009 Rusty Burchfield +# +# 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. +# +# Crude script to show the reference hierarchy of the specified partials. require 'yaml' - require 'rubygems' require 'active_support' files = ARGV partials = {} files.each do |file_name| short_name = file_name.sub(/app\/views\//, '').sub(/.html.erb$/, '') partials[short_name] = [] File.open(file_name) do |file| file.read.scan(/:partial\s*=>\s*("[^"]*"|'[^']*')/) do |groups| name = groups.first.gsub(/^\s*['"]\/?|['"]\s*$/, '') partials[short_name] << name.sub(/\/([^\/]+)$/, '/_\1') end end partials[short_name].sort!.uniq! end parents = partials.keys.select{|n| !partials.values.any?{|v| v.include?(n)}} def build_tree(partials, file) if !partials[file] || partials[file].empty? return file else {file => partials[file].map{|pn| build_tree(partials, pn)}} end end puts parents.sort.map{|p| build_tree(partials, p)}.to_yaml
GICodeWarrior/goodie-bag
99ab971b0c1110ddb7502261f9968c74edb65f6c
Add script to display list of partials used by each view/partial as a tree.
diff --git a/partial_hierarchy.rb b/partial_hierarchy.rb new file mode 100755 index 0000000..a3e464a --- /dev/null +++ b/partial_hierarchy.rb @@ -0,0 +1,33 @@ +#!/usr/bin/ruby + +require 'yaml' + +require 'rubygems' +require 'active_support' + +files = ARGV +partials = {} + +files.each do |file_name| + short_name = file_name.sub(/app\/views\//, '').sub(/.html.erb$/, '') + partials[short_name] = [] + File.open(file_name) do |file| + file.read.scan(/:partial\s*=>\s*("[^"]*"|'[^']*')/) do |groups| + name = groups.first.gsub(/^\s*['"]\/?|['"]\s*$/, '') + partials[short_name] << name.sub(/\/([^\/]+)$/, '/_\1') + end + end + partials[short_name].sort!.uniq! +end + +parents = partials.keys.select{|n| !partials.values.any?{|v| v.include?(n)}} + +def build_tree(partials, file) + if !partials[file] || partials[file].empty? + return file + else + {file => partials[file].map{|pn| build_tree(partials, pn)}} + end +end + +puts parents.sort.map{|p| build_tree(partials, p)}.to_yaml
andreacampi/fancybox
1dc8663f7c6ca4e0c4563b5e41c452c2a018fdd5
Only create fancy_wrap if it doesn't exist, but always populate it.
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index c681159..ebaaee2 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,447 +1,450 @@ /* * FancyBox - simple jQuery plugin for fancy image zooming * Examples and documentation at: http://fancy.klade.lv/ * Version: 1.0.0 (29/04/2008) * Copyright (c) 2008 Janis Skarnelis * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php * Requires: jQuery v1.2.1 or later */ (function($) { var opts = {}, imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], loadingTimer, loadingFrame = 1; $.fn.fancybox = function(settings) { opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); $.fn.fancybox.init(); if (opts.settings.followBrowserSize) { function doSomething() { var item = $.fn.fancybox.getCurrentItemNum(); if (item == null) { return; } $.fn.fancybox.resizeItem(); }; var resizeTimer = null; $(window).bind('resize', function() { doSomething(); // if (resizeTimer) clearTimeout(resizeTimer); // resizeTimer = setTimeout(doSomething, 100); }); } return this.each(function() { var $this = $(this); var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; $this.unbind('click').click(function() { $.fn.fancybox.start(this, o); return false; }); }); }; $.fn.fancybox.start = function(el, o) { if (opts.animating) return false; if (!o.inline && o.overlayShow) { $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); if ($.browser.msie) { $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); } $("#fancy_overlay").click($.fn.fancybox.close); } opts.itemArray = []; opts.itemNum = 0; if (jQuery.isFunction(o.itemLoadCallback)) { o.itemLoadCallback.apply(this, [opts]); var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} for (var i = 0; i < opts.itemArray.length; i++) { opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { opts.itemArray[i].orig = tmp; } } } else { if (!el.rel || el.rel == '') { var item = {url: el.href, title: el.title, o: o}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } opts.itemArray.push(item); } else { var arr = $("a[@rel=" + el.rel + "]").get(); for (var i = 0; i < arr.length; i++) { var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; var item = {url: arr[i].href, title: arr[i].title, o: tmp}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } if (arr[i].href == el.href) opts.itemNum = i; opts.itemArray.push(item); } } } $.fn.fancybox.changeItem(opts.itemNum); }; $.fn.fancybox.changeItem = function(n) { if (opts.itemArray[n].o.showLoading) { $.fn.fancybox.showLoading(); } opts.itemNum = n; $("#fancy_nav").empty(); $("#fancy_outer").stop(); $("#fancy_title").hide(); $(document).unbind("keydown"); imgRegExp = imgTypes.join('|'); imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); var url = opts.itemArray[n].url; if (url.match(/#/)) { var target = window.location.href.split('#')[0]; target = url.replace(target,''); $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); $("#fancy_loading").hide(); } else if (url.match(imgRegExp)) { $(imgPreloader).unbind('load').bind('load', function() { $("#fancy_loading").hide(); opts.itemArray[n].o.frameWidth = imgPreloader.width; opts.itemArray[n].o.frameHeight = imgPreloader.height; $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); }).attr('src', url + (opts.itemArray[n].o.random? '?rand=' + Math.floor(Math.random() * 999999999): "")); } else { $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + (opts.itemArray[n].o.random? Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>': "")); } }; $.fn.fancybox.showIframe = function() { $("#fancy_loading").hide(); $("#fancy_frame").show(); }; $.fn.fancybox.showItem = function(val) { $.fn.fancybox.preloadNeighborImages(); var viewportPos = $.fn.fancybox.getViewport(); var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; var itemOpts = { 'left': itemLeft, 'top': itemTop, 'width': itemSize[0] + 'px', 'height': itemSize[1] + 'px' } if (opts.active) { $('#fancy_content').fadeOut("normal", function() { $("#fancy_content").empty(); $("#fancy_outer").animate(itemOpts, "normal", function() { $("#fancy_content").append($(val)).fadeIn("normal"); $.fn.fancybox.updateDetails(); }); }); } else { opts.active = true; $("#fancy_content").empty(); if ($("#fancy_content").is(":animated")) { console.info('animated!'); } if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { opts.animating = true; itemOpts.opacity = "show"; $("#fancy_outer").css({ 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width }); $("#fancy_content").append($(val)).show(); $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { opts.animating = false; $.fn.fancybox.updateDetails(); }); } else { $("#fancy_content").append($(val)).show(); $("#fancy_outer").css(itemOpts).show(); $.fn.fancybox.updateDetails(); } } }; $.fn.fancybox.resizeItem = function() { val = $("#fancy_img"); var viewportPos = $.fn.fancybox.getViewport(); var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; var itemOpts = { 'left': itemLeft, 'top': itemTop, 'width': itemSize[0] + 'px', 'height': itemSize[1] + 'px' } $("#fancy_outer").css(itemOpts); $.fn.fancybox.updateDetails(); if (opts.itemArray[opts.itemNum].o.overlayShow) { $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': opts.itemArray[opts.itemNum].o.overlayOpacity}); if ($.browser.msie) { $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); } } }; $.fn.fancybox.updateDetails = function() { if (!opts.itemArray[opts.itemNum].o.inline) { $("#fancy_bg,#fancy_close").show(); } if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); $('#fancy_title').show(); } if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { $("#fancy_content").click($.fn.fancybox.close); } else { $("#fancy_content").unbind('click'); } if (opts.itemArray[opts.itemNum].o.inline) { $("#fancy_nav").empty(); } if (opts.itemNum != 0) { $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); $('#fancy_left').click(function() { $.fn.fancybox.changeItem(opts.itemNum - 1); return false; }); } if (opts.itemNum != (opts.itemArray.length - 1)) { $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); $('#fancy_right').click(function(){ $.fn.fancybox.changeItem(opts.itemNum + 1); return false; }); } $(document).keydown(function(event) { if (event.keyCode == 27) { $.fn.fancybox.close(); } else if(event.keyCode == 37 && opts.itemNum != 0) { $.fn.fancybox.changeItem(opts.itemNum - 1); } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { $.fn.fancybox.changeItem(opts.itemNum + 1); } }); }; $.fn.fancybox.preloadNeighborImages = function() { if ((opts.itemArray.length - 1) > opts.itemNum) { preloadNextImage = new Image(); preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; } if (opts.itemNum > 0) { preloadPrevImage = new Image(); preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; } }; $.fn.fancybox.close = function() { if (opts.animating) return false; $(imgPreloader).unbind('load'); $(document).unbind("keydown"); $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); $("#fancy_nav").empty(); opts.active = false; if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { var itemOpts = { 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width, 'opacity': 'hide' }; opts.animating = true; $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").remove(); opts.animating = false; }); } else { $("#fancy_outer").hide(); $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); } opts.itemNum = null; }; $.fn.fancybox.showLoading = function() { clearInterval(loadingTimer); var pos = $.fn.fancybox.getViewport(); $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); $("#fancy_loading").bind('click', $.fn.fancybox.close); loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); }; $.fn.fancybox.animateLoading = function(el, o) { if (!$("#fancy_loading").is(':visible')){ clearInterval(loadingTimer); return; } $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; $.fn.fancybox.init = function() { if (!$('#fancy_wrap').length) { - $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); + $('<div id="fancy_wrap"></div>').appendTo("body"); + } + if (1 /* XXX fancy_wrap has no children */) { + $('<div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div>').appendTo("#fancy_wrap"); $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); } if ($.browser.msie) { $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); } if (jQuery.fn.pngFix) $(document).pngFix(); $("#fancy_close").click($.fn.fancybox.close); }; $.fn.fancybox.getPosition = function(el) { var pos = el.offset(); pos.top += $.fn.fancybox.num(el, 'paddingTop'); pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); pos.left += $.fn.fancybox.num(el, 'paddingLeft'); pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); return pos; }; $.fn.fancybox.num = function (el, prop) { return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; }; $.fn.fancybox.getPageScroll = function() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) { yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return [xScroll, yScroll]; }; $.fn.fancybox.getViewport = function() { var scroll = $.fn.fancybox.getPageScroll(); return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; }; $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; }; $.fn.fancybox.getCurrentItemNum = function() { return opts.itemNum; }; $.fn.fancybox.defaults = { hideOnContentClick: false, zoomSpeedIn: 500, zoomSpeedOut: 500, frameWidth: 600, frameHeight: 400, overlayShow: false, overlayOpacity: 0.4, itemLoadCallback: null, showLoading: true, random: true, followBrowserSize: false, inline: false }; })(jQuery);
andreacampi/fancybox
7f1eb808b289e6e6cd7ae2581303c5ff436bfb0f
New functionality: * show the full-size photo inline. The page must define a suitable div to use for display (documentation coming). * add an option to resize the photo when the browser page is resized.
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index 485a8ad..c681159 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,390 +1,447 @@ /* * FancyBox - simple jQuery plugin for fancy image zooming * Examples and documentation at: http://fancy.klade.lv/ * Version: 1.0.0 (29/04/2008) * Copyright (c) 2008 Janis Skarnelis * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php * Requires: jQuery v1.2.1 or later */ (function($) { var opts = {}, imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], loadingTimer, loadingFrame = 1; $.fn.fancybox = function(settings) { opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); $.fn.fancybox.init(); + if (opts.settings.followBrowserSize) { + function doSomething() { + var item = $.fn.fancybox.getCurrentItemNum(); + if (item == null) { + return; + } + $.fn.fancybox.resizeItem(); + }; + + var resizeTimer = null; + $(window).bind('resize', function() { + doSomething(); + // if (resizeTimer) clearTimeout(resizeTimer); + // resizeTimer = setTimeout(doSomething, 100); + }); + } + return this.each(function() { var $this = $(this); var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; $this.unbind('click').click(function() { $.fn.fancybox.start(this, o); return false; }); }); }; $.fn.fancybox.start = function(el, o) { if (opts.animating) return false; - if (o.overlayShow) { + if (!o.inline && o.overlayShow) { $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); if ($.browser.msie) { $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); } $("#fancy_overlay").click($.fn.fancybox.close); } opts.itemArray = []; opts.itemNum = 0; if (jQuery.isFunction(o.itemLoadCallback)) { o.itemLoadCallback.apply(this, [opts]); var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} for (var i = 0; i < opts.itemArray.length; i++) { opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { opts.itemArray[i].orig = tmp; } } } else { if (!el.rel || el.rel == '') { var item = {url: el.href, title: el.title, o: o}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } opts.itemArray.push(item); } else { var arr = $("a[@rel=" + el.rel + "]").get(); for (var i = 0; i < arr.length; i++) { var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; var item = {url: arr[i].href, title: arr[i].title, o: tmp}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } if (arr[i].href == el.href) opts.itemNum = i; opts.itemArray.push(item); } } } $.fn.fancybox.changeItem(opts.itemNum); }; $.fn.fancybox.changeItem = function(n) { if (opts.itemArray[n].o.showLoading) { $.fn.fancybox.showLoading(); } opts.itemNum = n; $("#fancy_nav").empty(); $("#fancy_outer").stop(); $("#fancy_title").hide(); $(document).unbind("keydown"); imgRegExp = imgTypes.join('|'); imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); var url = opts.itemArray[n].url; if (url.match(/#/)) { var target = window.location.href.split('#')[0]; target = url.replace(target,''); $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); $("#fancy_loading").hide(); } else if (url.match(imgRegExp)) { $(imgPreloader).unbind('load').bind('load', function() { $("#fancy_loading").hide(); opts.itemArray[n].o.frameWidth = imgPreloader.width; opts.itemArray[n].o.frameHeight = imgPreloader.height; $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); }).attr('src', url + (opts.itemArray[n].o.random? '?rand=' + Math.floor(Math.random() * 999999999): "")); } else { $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + (opts.itemArray[n].o.random? Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>': "")); } }; $.fn.fancybox.showIframe = function() { $("#fancy_loading").hide(); $("#fancy_frame").show(); }; $.fn.fancybox.showItem = function(val) { $.fn.fancybox.preloadNeighborImages(); var viewportPos = $.fn.fancybox.getViewport(); var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; var itemOpts = { 'left': itemLeft, 'top': itemTop, 'width': itemSize[0] + 'px', 'height': itemSize[1] + 'px' } if (opts.active) { $('#fancy_content').fadeOut("normal", function() { $("#fancy_content").empty(); $("#fancy_outer").animate(itemOpts, "normal", function() { $("#fancy_content").append($(val)).fadeIn("normal"); $.fn.fancybox.updateDetails(); }); }); } else { opts.active = true; $("#fancy_content").empty(); if ($("#fancy_content").is(":animated")) { console.info('animated!'); } if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { opts.animating = true; itemOpts.opacity = "show"; $("#fancy_outer").css({ 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width }); $("#fancy_content").append($(val)).show(); $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { opts.animating = false; $.fn.fancybox.updateDetails(); }); } else { $("#fancy_content").append($(val)).show(); $("#fancy_outer").css(itemOpts).show(); $.fn.fancybox.updateDetails(); } } }; + + $.fn.fancybox.resizeItem = function() { + val = $("#fancy_img"); + + var viewportPos = $.fn.fancybox.getViewport(); + var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); + + var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; + var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; + + var itemOpts = { + 'left': itemLeft, + 'top': itemTop, + 'width': itemSize[0] + 'px', + 'height': itemSize[1] + 'px' + } + + $("#fancy_outer").css(itemOpts); + $.fn.fancybox.updateDetails(); + + if (opts.itemArray[opts.itemNum].o.overlayShow) { + $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': opts.itemArray[opts.itemNum].o.overlayOpacity}); + + if ($.browser.msie) { + $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); + } + } + }; $.fn.fancybox.updateDetails = function() { - $("#fancy_bg,#fancy_close").show(); + if (!opts.itemArray[opts.itemNum].o.inline) { + $("#fancy_bg,#fancy_close").show(); + } if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); $('#fancy_title').show(); } if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { $("#fancy_content").click($.fn.fancybox.close); } else { $("#fancy_content").unbind('click'); } + if (opts.itemArray[opts.itemNum].o.inline) { + $("#fancy_nav").empty(); + } + if (opts.itemNum != 0) { $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); $('#fancy_left').click(function() { $.fn.fancybox.changeItem(opts.itemNum - 1); return false; }); } if (opts.itemNum != (opts.itemArray.length - 1)) { $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); $('#fancy_right').click(function(){ $.fn.fancybox.changeItem(opts.itemNum + 1); return false; }); } $(document).keydown(function(event) { if (event.keyCode == 27) { $.fn.fancybox.close(); } else if(event.keyCode == 37 && opts.itemNum != 0) { $.fn.fancybox.changeItem(opts.itemNum - 1); } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { $.fn.fancybox.changeItem(opts.itemNum + 1); } }); }; $.fn.fancybox.preloadNeighborImages = function() { if ((opts.itemArray.length - 1) > opts.itemNum) { preloadNextImage = new Image(); preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; } if (opts.itemNum > 0) { preloadPrevImage = new Image(); preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; } }; $.fn.fancybox.close = function() { if (opts.animating) return false; $(imgPreloader).unbind('load'); $(document).unbind("keydown"); $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); $("#fancy_nav").empty(); opts.active = false; if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { var itemOpts = { 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width, 'opacity': 'hide' }; opts.animating = true; $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").remove(); opts.animating = false; }); } else { $("#fancy_outer").hide(); $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); } opts.itemNum = null; }; $.fn.fancybox.showLoading = function() { clearInterval(loadingTimer); var pos = $.fn.fancybox.getViewport(); $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); $("#fancy_loading").bind('click', $.fn.fancybox.close); loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); }; $.fn.fancybox.animateLoading = function(el, o) { if (!$("#fancy_loading").is(':visible')){ clearInterval(loadingTimer); return; } $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; $.fn.fancybox.init = function() { if (!$('#fancy_wrap').length) { $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); } if ($.browser.msie) { $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); } if (jQuery.fn.pngFix) $(document).pngFix(); $("#fancy_close").click($.fn.fancybox.close); }; $.fn.fancybox.getPosition = function(el) { var pos = el.offset(); pos.top += $.fn.fancybox.num(el, 'paddingTop'); pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); pos.left += $.fn.fancybox.num(el, 'paddingLeft'); pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); return pos; }; $.fn.fancybox.num = function (el, prop) { return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; }; $.fn.fancybox.getPageScroll = function() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) { yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return [xScroll, yScroll]; }; $.fn.fancybox.getViewport = function() { var scroll = $.fn.fancybox.getPageScroll(); return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; }; $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; }; + $.fn.fancybox.getCurrentItemNum = function() { + return opts.itemNum; + }; + $.fn.fancybox.defaults = { hideOnContentClick: false, zoomSpeedIn: 500, zoomSpeedOut: 500, frameWidth: 600, frameHeight: 400, overlayShow: false, overlayOpacity: 0.4, itemLoadCallback: null, showLoading: true, - random: true + random: true, + followBrowserSize: false, + inline: false }; })(jQuery);
andreacampi/fancybox
8589219f38b75884210bf084a573ab450245fe3f
Make random links for cache-busting optional.
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index adccffe..485a8ad 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,388 +1,390 @@ /* * FancyBox - simple jQuery plugin for fancy image zooming * Examples and documentation at: http://fancy.klade.lv/ * Version: 1.0.0 (29/04/2008) * Copyright (c) 2008 Janis Skarnelis * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php * Requires: jQuery v1.2.1 or later */ (function($) { var opts = {}, imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], loadingTimer, loadingFrame = 1; $.fn.fancybox = function(settings) { opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); $.fn.fancybox.init(); return this.each(function() { var $this = $(this); var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; $this.unbind('click').click(function() { $.fn.fancybox.start(this, o); return false; }); }); }; $.fn.fancybox.start = function(el, o) { if (opts.animating) return false; if (o.overlayShow) { $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); if ($.browser.msie) { $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); } $("#fancy_overlay").click($.fn.fancybox.close); } opts.itemArray = []; opts.itemNum = 0; if (jQuery.isFunction(o.itemLoadCallback)) { o.itemLoadCallback.apply(this, [opts]); var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} for (var i = 0; i < opts.itemArray.length; i++) { opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { opts.itemArray[i].orig = tmp; } } } else { if (!el.rel || el.rel == '') { var item = {url: el.href, title: el.title, o: o}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } opts.itemArray.push(item); } else { var arr = $("a[@rel=" + el.rel + "]").get(); for (var i = 0; i < arr.length; i++) { var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; var item = {url: arr[i].href, title: arr[i].title, o: tmp}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } if (arr[i].href == el.href) opts.itemNum = i; opts.itemArray.push(item); } } } $.fn.fancybox.changeItem(opts.itemNum); }; $.fn.fancybox.changeItem = function(n) { if (opts.itemArray[n].o.showLoading) { $.fn.fancybox.showLoading(); } opts.itemNum = n; $("#fancy_nav").empty(); $("#fancy_outer").stop(); $("#fancy_title").hide(); $(document).unbind("keydown"); imgRegExp = imgTypes.join('|'); imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); var url = opts.itemArray[n].url; if (url.match(/#/)) { var target = window.location.href.split('#')[0]; target = url.replace(target,''); $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); $("#fancy_loading").hide(); } else if (url.match(imgRegExp)) { $(imgPreloader).unbind('load').bind('load', function() { $("#fancy_loading").hide(); opts.itemArray[n].o.frameWidth = imgPreloader.width; opts.itemArray[n].o.frameHeight = imgPreloader.height; $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); - }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); + }).attr('src', url + (opts.itemArray[n].o.random? '?rand=' + Math.floor(Math.random() * 999999999): "")); } else { - $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); + $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + + (opts.itemArray[n].o.random? Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>': "")); } }; $.fn.fancybox.showIframe = function() { $("#fancy_loading").hide(); $("#fancy_frame").show(); }; $.fn.fancybox.showItem = function(val) { $.fn.fancybox.preloadNeighborImages(); var viewportPos = $.fn.fancybox.getViewport(); var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; var itemOpts = { 'left': itemLeft, 'top': itemTop, 'width': itemSize[0] + 'px', 'height': itemSize[1] + 'px' } if (opts.active) { $('#fancy_content').fadeOut("normal", function() { $("#fancy_content").empty(); $("#fancy_outer").animate(itemOpts, "normal", function() { $("#fancy_content").append($(val)).fadeIn("normal"); $.fn.fancybox.updateDetails(); }); }); } else { opts.active = true; $("#fancy_content").empty(); if ($("#fancy_content").is(":animated")) { console.info('animated!'); } if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { opts.animating = true; itemOpts.opacity = "show"; $("#fancy_outer").css({ 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width }); $("#fancy_content").append($(val)).show(); $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { opts.animating = false; $.fn.fancybox.updateDetails(); }); } else { $("#fancy_content").append($(val)).show(); $("#fancy_outer").css(itemOpts).show(); $.fn.fancybox.updateDetails(); } } }; $.fn.fancybox.updateDetails = function() { $("#fancy_bg,#fancy_close").show(); if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); $('#fancy_title').show(); } if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { $("#fancy_content").click($.fn.fancybox.close); } else { $("#fancy_content").unbind('click'); } if (opts.itemNum != 0) { $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); $('#fancy_left').click(function() { $.fn.fancybox.changeItem(opts.itemNum - 1); return false; }); } if (opts.itemNum != (opts.itemArray.length - 1)) { $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); $('#fancy_right').click(function(){ $.fn.fancybox.changeItem(opts.itemNum + 1); return false; }); } $(document).keydown(function(event) { if (event.keyCode == 27) { $.fn.fancybox.close(); } else if(event.keyCode == 37 && opts.itemNum != 0) { $.fn.fancybox.changeItem(opts.itemNum - 1); } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { $.fn.fancybox.changeItem(opts.itemNum + 1); } }); }; $.fn.fancybox.preloadNeighborImages = function() { if ((opts.itemArray.length - 1) > opts.itemNum) { preloadNextImage = new Image(); preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; } if (opts.itemNum > 0) { preloadPrevImage = new Image(); preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; } }; $.fn.fancybox.close = function() { if (opts.animating) return false; $(imgPreloader).unbind('load'); $(document).unbind("keydown"); $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); $("#fancy_nav").empty(); opts.active = false; if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { var itemOpts = { 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width, 'opacity': 'hide' }; opts.animating = true; $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").remove(); opts.animating = false; }); } else { $("#fancy_outer").hide(); $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); } opts.itemNum = null; }; $.fn.fancybox.showLoading = function() { clearInterval(loadingTimer); var pos = $.fn.fancybox.getViewport(); $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); $("#fancy_loading").bind('click', $.fn.fancybox.close); loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); }; $.fn.fancybox.animateLoading = function(el, o) { if (!$("#fancy_loading").is(':visible')){ clearInterval(loadingTimer); return; } $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; $.fn.fancybox.init = function() { if (!$('#fancy_wrap').length) { $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); } if ($.browser.msie) { $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); } if (jQuery.fn.pngFix) $(document).pngFix(); $("#fancy_close").click($.fn.fancybox.close); }; $.fn.fancybox.getPosition = function(el) { var pos = el.offset(); pos.top += $.fn.fancybox.num(el, 'paddingTop'); pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); pos.left += $.fn.fancybox.num(el, 'paddingLeft'); pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); return pos; }; $.fn.fancybox.num = function (el, prop) { return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; }; $.fn.fancybox.getPageScroll = function() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) { yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return [xScroll, yScroll]; }; $.fn.fancybox.getViewport = function() { var scroll = $.fn.fancybox.getPageScroll(); return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; }; $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; }; $.fn.fancybox.defaults = { hideOnContentClick: false, zoomSpeedIn: 500, zoomSpeedOut: 500, frameWidth: 600, frameHeight: 400, overlayShow: false, overlayOpacity: 0.4, itemLoadCallback: null, - showLoading: true, + showLoading: true, + random: true }; })(jQuery);
andreacampi/fancybox
ed29ee158a1ce0fd9265ea26af16cd8af8e75940
Use the item's options instead of the global ones.
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index 6ac234c..adccffe 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,388 +1,388 @@ /* * FancyBox - simple jQuery plugin for fancy image zooming * Examples and documentation at: http://fancy.klade.lv/ * Version: 1.0.0 (29/04/2008) * Copyright (c) 2008 Janis Skarnelis * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php * Requires: jQuery v1.2.1 or later */ (function($) { var opts = {}, imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], loadingTimer, loadingFrame = 1; $.fn.fancybox = function(settings) { opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); $.fn.fancybox.init(); return this.each(function() { var $this = $(this); var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; $this.unbind('click').click(function() { $.fn.fancybox.start(this, o); return false; }); }); }; $.fn.fancybox.start = function(el, o) { if (opts.animating) return false; if (o.overlayShow) { $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); if ($.browser.msie) { $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); } $("#fancy_overlay").click($.fn.fancybox.close); } opts.itemArray = []; opts.itemNum = 0; if (jQuery.isFunction(o.itemLoadCallback)) { o.itemLoadCallback.apply(this, [opts]); var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} for (var i = 0; i < opts.itemArray.length; i++) { opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { opts.itemArray[i].orig = tmp; } } } else { if (!el.rel || el.rel == '') { var item = {url: el.href, title: el.title, o: o}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } opts.itemArray.push(item); } else { var arr = $("a[@rel=" + el.rel + "]").get(); for (var i = 0; i < arr.length; i++) { var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; var item = {url: arr[i].href, title: arr[i].title, o: tmp}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } if (arr[i].href == el.href) opts.itemNum = i; opts.itemArray.push(item); } } } $.fn.fancybox.changeItem(opts.itemNum); }; $.fn.fancybox.changeItem = function(n) { - if (opts.showLoading) { + if (opts.itemArray[n].o.showLoading) { $.fn.fancybox.showLoading(); } opts.itemNum = n; $("#fancy_nav").empty(); $("#fancy_outer").stop(); $("#fancy_title").hide(); $(document).unbind("keydown"); imgRegExp = imgTypes.join('|'); imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); var url = opts.itemArray[n].url; if (url.match(/#/)) { var target = window.location.href.split('#')[0]; target = url.replace(target,''); $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); $("#fancy_loading").hide(); } else if (url.match(imgRegExp)) { $(imgPreloader).unbind('load').bind('load', function() { $("#fancy_loading").hide(); opts.itemArray[n].o.frameWidth = imgPreloader.width; opts.itemArray[n].o.frameHeight = imgPreloader.height; $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); } else { $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); } }; $.fn.fancybox.showIframe = function() { $("#fancy_loading").hide(); $("#fancy_frame").show(); }; $.fn.fancybox.showItem = function(val) { $.fn.fancybox.preloadNeighborImages(); var viewportPos = $.fn.fancybox.getViewport(); var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; var itemOpts = { 'left': itemLeft, 'top': itemTop, 'width': itemSize[0] + 'px', 'height': itemSize[1] + 'px' } if (opts.active) { $('#fancy_content').fadeOut("normal", function() { $("#fancy_content").empty(); $("#fancy_outer").animate(itemOpts, "normal", function() { $("#fancy_content").append($(val)).fadeIn("normal"); $.fn.fancybox.updateDetails(); }); }); } else { opts.active = true; $("#fancy_content").empty(); if ($("#fancy_content").is(":animated")) { console.info('animated!'); } if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { opts.animating = true; itemOpts.opacity = "show"; $("#fancy_outer").css({ 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width }); $("#fancy_content").append($(val)).show(); $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { opts.animating = false; $.fn.fancybox.updateDetails(); }); } else { $("#fancy_content").append($(val)).show(); $("#fancy_outer").css(itemOpts).show(); $.fn.fancybox.updateDetails(); } } }; $.fn.fancybox.updateDetails = function() { $("#fancy_bg,#fancy_close").show(); if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); $('#fancy_title').show(); } if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { $("#fancy_content").click($.fn.fancybox.close); } else { $("#fancy_content").unbind('click'); } if (opts.itemNum != 0) { $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); $('#fancy_left').click(function() { $.fn.fancybox.changeItem(opts.itemNum - 1); return false; }); } if (opts.itemNum != (opts.itemArray.length - 1)) { $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); $('#fancy_right').click(function(){ $.fn.fancybox.changeItem(opts.itemNum + 1); return false; }); } $(document).keydown(function(event) { if (event.keyCode == 27) { $.fn.fancybox.close(); } else if(event.keyCode == 37 && opts.itemNum != 0) { $.fn.fancybox.changeItem(opts.itemNum - 1); } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { $.fn.fancybox.changeItem(opts.itemNum + 1); } }); }; $.fn.fancybox.preloadNeighborImages = function() { if ((opts.itemArray.length - 1) > opts.itemNum) { preloadNextImage = new Image(); preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; } if (opts.itemNum > 0) { preloadPrevImage = new Image(); preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; } }; $.fn.fancybox.close = function() { if (opts.animating) return false; $(imgPreloader).unbind('load'); $(document).unbind("keydown"); $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); $("#fancy_nav").empty(); opts.active = false; if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { var itemOpts = { 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width, 'opacity': 'hide' }; opts.animating = true; $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").remove(); opts.animating = false; }); } else { $("#fancy_outer").hide(); $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); } opts.itemNum = null; }; $.fn.fancybox.showLoading = function() { clearInterval(loadingTimer); var pos = $.fn.fancybox.getViewport(); $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); $("#fancy_loading").bind('click', $.fn.fancybox.close); loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); }; $.fn.fancybox.animateLoading = function(el, o) { if (!$("#fancy_loading").is(':visible')){ clearInterval(loadingTimer); return; } $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; $.fn.fancybox.init = function() { if (!$('#fancy_wrap').length) { $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); } if ($.browser.msie) { $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); } if (jQuery.fn.pngFix) $(document).pngFix(); $("#fancy_close").click($.fn.fancybox.close); }; $.fn.fancybox.getPosition = function(el) { var pos = el.offset(); pos.top += $.fn.fancybox.num(el, 'paddingTop'); pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); pos.left += $.fn.fancybox.num(el, 'paddingLeft'); pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); return pos; }; $.fn.fancybox.num = function (el, prop) { return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; }; $.fn.fancybox.getPageScroll = function() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) { yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return [xScroll, yScroll]; }; $.fn.fancybox.getViewport = function() { var scroll = $.fn.fancybox.getPageScroll(); return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; }; $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; }; $.fn.fancybox.defaults = { hideOnContentClick: false, zoomSpeedIn: 500, zoomSpeedOut: 500, frameWidth: 600, frameHeight: 400, overlayShow: false, overlayOpacity: 0.4, itemLoadCallback: null, showLoading: true, }; })(jQuery);
andreacampi/fancybox
aa03bcd34034c00079fdec4211e6abb870be9d1b
Use Unix EOL's.
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index e3dbd2f..6ac234c 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,388 +1,388 @@ -/* - * FancyBox - simple jQuery plugin for fancy image zooming - * Examples and documentation at: http://fancy.klade.lv/ - * Version: 1.0.0 (29/04/2008) - * Copyright (c) 2008 Janis Skarnelis - * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php - * Requires: jQuery v1.2.1 or later -*/ -(function($) { - var opts = {}, - imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], - loadingTimer, loadingFrame = 1; - - $.fn.fancybox = function(settings) { - opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); - - $.fn.fancybox.init(); - - return this.each(function() { - var $this = $(this); - var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; - - $this.unbind('click').click(function() { - $.fn.fancybox.start(this, o); return false; - }); - }); - }; - - $.fn.fancybox.start = function(el, o) { - if (opts.animating) return false; - - if (o.overlayShow) { - $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); - $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); - - if ($.browser.msie) { - $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); - $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); - } - - $("#fancy_overlay").click($.fn.fancybox.close); - } - - opts.itemArray = []; - opts.itemNum = 0; - - if (jQuery.isFunction(o.itemLoadCallback)) { - o.itemLoadCallback.apply(this, [opts]); - - var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); - var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - - for (var i = 0; i < opts.itemArray.length; i++) { - opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - opts.itemArray[i].orig = tmp; - } - } - - } else { - if (!el.rel || el.rel == '') { - var item = {url: el.href, title: el.title, o: o}; - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); - item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - } - - opts.itemArray.push(item); - - } else { - var arr = $("a[@rel=" + el.rel + "]").get(); - - for (var i = 0; i < arr.length; i++) { - var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; - var item = {url: arr[i].href, title: arr[i].title, o: tmp}; - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); - - item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - } - - if (arr[i].href == el.href) opts.itemNum = i; - - opts.itemArray.push(item); - } - } - } - - $.fn.fancybox.changeItem(opts.itemNum); - }; - - $.fn.fancybox.changeItem = function(n) { - if (opts.showLoading) { - $.fn.fancybox.showLoading(); - } - - opts.itemNum = n; - - $("#fancy_nav").empty(); - $("#fancy_outer").stop(); - $("#fancy_title").hide(); - $(document).unbind("keydown"); - - imgRegExp = imgTypes.join('|'); - imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); - - var url = opts.itemArray[n].url; - - if (url.match(/#/)) { - var target = window.location.href.split('#')[0]; target = url.replace(target,''); - - $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); - - $("#fancy_loading").hide(); - - } else if (url.match(imgRegExp)) { - $(imgPreloader).unbind('load').bind('load', function() { - $("#fancy_loading").hide(); - - opts.itemArray[n].o.frameWidth = imgPreloader.width; - opts.itemArray[n].o.frameHeight = imgPreloader.height; - - $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); - - }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); - - } else { - $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); - } - }; - - $.fn.fancybox.showIframe = function() { - $("#fancy_loading").hide(); - $("#fancy_frame").show(); - }; - - $.fn.fancybox.showItem = function(val) { - $.fn.fancybox.preloadNeighborImages(); - - var viewportPos = $.fn.fancybox.getViewport(); - var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); - - var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; - var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; - - var itemOpts = { - 'left': itemLeft, - 'top': itemTop, - 'width': itemSize[0] + 'px', - 'height': itemSize[1] + 'px' - } - - if (opts.active) { - $('#fancy_content').fadeOut("normal", function() { - $("#fancy_content").empty(); - - $("#fancy_outer").animate(itemOpts, "normal", function() { - $("#fancy_content").append($(val)).fadeIn("normal"); - $.fn.fancybox.updateDetails(); - }); - }); - - } else { - opts.active = true; - - $("#fancy_content").empty(); - - if ($("#fancy_content").is(":animated")) { - console.info('animated!'); - } - - if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { - opts.animating = true; - itemOpts.opacity = "show"; - - $("#fancy_outer").css({ - 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, - 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, - 'height': opts.itemArray[opts.itemNum].orig.height, - 'width': opts.itemArray[opts.itemNum].orig.width - }); - - $("#fancy_content").append($(val)).show(); - - $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { - opts.animating = false; - $.fn.fancybox.updateDetails(); - }); - - } else { - $("#fancy_content").append($(val)).show(); - $("#fancy_outer").css(itemOpts).show(); - $.fn.fancybox.updateDetails(); - } - } - }; - - $.fn.fancybox.updateDetails = function() { - $("#fancy_bg,#fancy_close").show(); - - if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { - $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); - $('#fancy_title').show(); - } - - if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { - $("#fancy_content").click($.fn.fancybox.close); - } else { - $("#fancy_content").unbind('click'); - } - - if (opts.itemNum != 0) { - $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); - - $('#fancy_left').click(function() { - $.fn.fancybox.changeItem(opts.itemNum - 1); return false; - }); - } - - if (opts.itemNum != (opts.itemArray.length - 1)) { - $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); - - $('#fancy_right').click(function(){ - $.fn.fancybox.changeItem(opts.itemNum + 1); return false; - }); - } - - $(document).keydown(function(event) { - if (event.keyCode == 27) { - $.fn.fancybox.close(); - - } else if(event.keyCode == 37 && opts.itemNum != 0) { - $.fn.fancybox.changeItem(opts.itemNum - 1); - - } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { - $.fn.fancybox.changeItem(opts.itemNum + 1); - } - }); - }; - - $.fn.fancybox.preloadNeighborImages = function() { - if ((opts.itemArray.length - 1) > opts.itemNum) { - preloadNextImage = new Image(); - preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; - } - - if (opts.itemNum > 0) { - preloadPrevImage = new Image(); - preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; - } - }; - - $.fn.fancybox.close = function() { - if (opts.animating) return false; - - $(imgPreloader).unbind('load'); - $(document).unbind("keydown"); - - $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); - - $("#fancy_nav").empty(); - - opts.active = false; - - if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { - var itemOpts = { - 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, - 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, - 'height': opts.itemArray[opts.itemNum].orig.height, - 'width': opts.itemArray[opts.itemNum].orig.width, - 'opacity': 'hide' - }; - - opts.animating = true; - - $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { - $("#fancy_content").hide().empty(); - $("#fancy_overlay,#fancy_bigIframe").remove(); - opts.animating = false; - }); - - } else { - $("#fancy_outer").hide(); - $("#fancy_content").hide().empty(); - $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); - } - opts.itemNum = null; - }; - - $.fn.fancybox.showLoading = function() { - clearInterval(loadingTimer); - - var pos = $.fn.fancybox.getViewport(); - - $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); - $("#fancy_loading").bind('click', $.fn.fancybox.close); - - loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); - }; - - $.fn.fancybox.animateLoading = function(el, o) { - if (!$("#fancy_loading").is(':visible')){ - clearInterval(loadingTimer); - return; - } - - $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); - - loadingFrame = (loadingFrame + 1) % 12; - }; - - $.fn.fancybox.init = function() { - if (!$('#fancy_wrap').length) { - $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); - $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); - - $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); - } - - if ($.browser.msie) { - $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); - } - - if (jQuery.fn.pngFix) $(document).pngFix(); - - $("#fancy_close").click($.fn.fancybox.close); - }; - - $.fn.fancybox.getPosition = function(el) { - var pos = el.offset(); - - pos.top += $.fn.fancybox.num(el, 'paddingTop'); - pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); - - pos.left += $.fn.fancybox.num(el, 'paddingLeft'); - pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); - - return pos; - }; - - $.fn.fancybox.num = function (el, prop) { - return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; - }; - - $.fn.fancybox.getPageScroll = function() { - var xScroll, yScroll; - - if (self.pageYOffset) { - yScroll = self.pageYOffset; - xScroll = self.pageXOffset; - } else if (document.documentElement && document.documentElement.scrollTop) { - yScroll = document.documentElement.scrollTop; - xScroll = document.documentElement.scrollLeft; - } else if (document.body) { - yScroll = document.body.scrollTop; - xScroll = document.body.scrollLeft; - } - - return [xScroll, yScroll]; - }; - - $.fn.fancybox.getViewport = function() { - var scroll = $.fn.fancybox.getPageScroll(); - - return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; - }; - - $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { - var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); - - return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; - }; - - $.fn.fancybox.defaults = { - hideOnContentClick: false, - zoomSpeedIn: 500, - zoomSpeedOut: 500, - frameWidth: 600, - frameHeight: 400, - overlayShow: false, - overlayOpacity: 0.4, - itemLoadCallback: null, - showLoading: true, - }; -})(jQuery); +/* + * FancyBox - simple jQuery plugin for fancy image zooming + * Examples and documentation at: http://fancy.klade.lv/ + * Version: 1.0.0 (29/04/2008) + * Copyright (c) 2008 Janis Skarnelis + * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php + * Requires: jQuery v1.2.1 or later +*/ +(function($) { + var opts = {}, + imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], + loadingTimer, loadingFrame = 1; + + $.fn.fancybox = function(settings) { + opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); + + $.fn.fancybox.init(); + + return this.each(function() { + var $this = $(this); + var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; + + $this.unbind('click').click(function() { + $.fn.fancybox.start(this, o); return false; + }); + }); + }; + + $.fn.fancybox.start = function(el, o) { + if (opts.animating) return false; + + if (o.overlayShow) { + $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); + $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); + + if ($.browser.msie) { + $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); + $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); + } + + $("#fancy_overlay").click($.fn.fancybox.close); + } + + opts.itemArray = []; + opts.itemNum = 0; + + if (jQuery.isFunction(o.itemLoadCallback)) { + o.itemLoadCallback.apply(this, [opts]); + + var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); + var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + + for (var i = 0; i < opts.itemArray.length; i++) { + opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + opts.itemArray[i].orig = tmp; + } + } + + } else { + if (!el.rel || el.rel == '') { + var item = {url: el.href, title: el.title, o: o}; + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); + item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + } + + opts.itemArray.push(item); + + } else { + var arr = $("a[@rel=" + el.rel + "]").get(); + + for (var i = 0; i < arr.length; i++) { + var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; + var item = {url: arr[i].href, title: arr[i].title, o: tmp}; + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); + + item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + } + + if (arr[i].href == el.href) opts.itemNum = i; + + opts.itemArray.push(item); + } + } + } + + $.fn.fancybox.changeItem(opts.itemNum); + }; + + $.fn.fancybox.changeItem = function(n) { + if (opts.showLoading) { + $.fn.fancybox.showLoading(); + } + + opts.itemNum = n; + + $("#fancy_nav").empty(); + $("#fancy_outer").stop(); + $("#fancy_title").hide(); + $(document).unbind("keydown"); + + imgRegExp = imgTypes.join('|'); + imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); + + var url = opts.itemArray[n].url; + + if (url.match(/#/)) { + var target = window.location.href.split('#')[0]; target = url.replace(target,''); + + $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); + + $("#fancy_loading").hide(); + + } else if (url.match(imgRegExp)) { + $(imgPreloader).unbind('load').bind('load', function() { + $("#fancy_loading").hide(); + + opts.itemArray[n].o.frameWidth = imgPreloader.width; + opts.itemArray[n].o.frameHeight = imgPreloader.height; + + $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); + + }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); + + } else { + $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); + } + }; + + $.fn.fancybox.showIframe = function() { + $("#fancy_loading").hide(); + $("#fancy_frame").show(); + }; + + $.fn.fancybox.showItem = function(val) { + $.fn.fancybox.preloadNeighborImages(); + + var viewportPos = $.fn.fancybox.getViewport(); + var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); + + var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; + var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; + + var itemOpts = { + 'left': itemLeft, + 'top': itemTop, + 'width': itemSize[0] + 'px', + 'height': itemSize[1] + 'px' + } + + if (opts.active) { + $('#fancy_content').fadeOut("normal", function() { + $("#fancy_content").empty(); + + $("#fancy_outer").animate(itemOpts, "normal", function() { + $("#fancy_content").append($(val)).fadeIn("normal"); + $.fn.fancybox.updateDetails(); + }); + }); + + } else { + opts.active = true; + + $("#fancy_content").empty(); + + if ($("#fancy_content").is(":animated")) { + console.info('animated!'); + } + + if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { + opts.animating = true; + itemOpts.opacity = "show"; + + $("#fancy_outer").css({ + 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, + 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, + 'height': opts.itemArray[opts.itemNum].orig.height, + 'width': opts.itemArray[opts.itemNum].orig.width + }); + + $("#fancy_content").append($(val)).show(); + + $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { + opts.animating = false; + $.fn.fancybox.updateDetails(); + }); + + } else { + $("#fancy_content").append($(val)).show(); + $("#fancy_outer").css(itemOpts).show(); + $.fn.fancybox.updateDetails(); + } + } + }; + + $.fn.fancybox.updateDetails = function() { + $("#fancy_bg,#fancy_close").show(); + + if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { + $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); + $('#fancy_title').show(); + } + + if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { + $("#fancy_content").click($.fn.fancybox.close); + } else { + $("#fancy_content").unbind('click'); + } + + if (opts.itemNum != 0) { + $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); + + $('#fancy_left').click(function() { + $.fn.fancybox.changeItem(opts.itemNum - 1); return false; + }); + } + + if (opts.itemNum != (opts.itemArray.length - 1)) { + $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); + + $('#fancy_right').click(function(){ + $.fn.fancybox.changeItem(opts.itemNum + 1); return false; + }); + } + + $(document).keydown(function(event) { + if (event.keyCode == 27) { + $.fn.fancybox.close(); + + } else if(event.keyCode == 37 && opts.itemNum != 0) { + $.fn.fancybox.changeItem(opts.itemNum - 1); + + } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { + $.fn.fancybox.changeItem(opts.itemNum + 1); + } + }); + }; + + $.fn.fancybox.preloadNeighborImages = function() { + if ((opts.itemArray.length - 1) > opts.itemNum) { + preloadNextImage = new Image(); + preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; + } + + if (opts.itemNum > 0) { + preloadPrevImage = new Image(); + preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; + } + }; + + $.fn.fancybox.close = function() { + if (opts.animating) return false; + + $(imgPreloader).unbind('load'); + $(document).unbind("keydown"); + + $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); + + $("#fancy_nav").empty(); + + opts.active = false; + + if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { + var itemOpts = { + 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, + 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, + 'height': opts.itemArray[opts.itemNum].orig.height, + 'width': opts.itemArray[opts.itemNum].orig.width, + 'opacity': 'hide' + }; + + opts.animating = true; + + $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { + $("#fancy_content").hide().empty(); + $("#fancy_overlay,#fancy_bigIframe").remove(); + opts.animating = false; + }); + + } else { + $("#fancy_outer").hide(); + $("#fancy_content").hide().empty(); + $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); + } + opts.itemNum = null; + }; + + $.fn.fancybox.showLoading = function() { + clearInterval(loadingTimer); + + var pos = $.fn.fancybox.getViewport(); + + $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); + $("#fancy_loading").bind('click', $.fn.fancybox.close); + + loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); + }; + + $.fn.fancybox.animateLoading = function(el, o) { + if (!$("#fancy_loading").is(':visible')){ + clearInterval(loadingTimer); + return; + } + + $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); + + loadingFrame = (loadingFrame + 1) % 12; + }; + + $.fn.fancybox.init = function() { + if (!$('#fancy_wrap').length) { + $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); + $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); + + $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); + } + + if ($.browser.msie) { + $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); + } + + if (jQuery.fn.pngFix) $(document).pngFix(); + + $("#fancy_close").click($.fn.fancybox.close); + }; + + $.fn.fancybox.getPosition = function(el) { + var pos = el.offset(); + + pos.top += $.fn.fancybox.num(el, 'paddingTop'); + pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); + + pos.left += $.fn.fancybox.num(el, 'paddingLeft'); + pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); + + return pos; + }; + + $.fn.fancybox.num = function (el, prop) { + return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; + }; + + $.fn.fancybox.getPageScroll = function() { + var xScroll, yScroll; + + if (self.pageYOffset) { + yScroll = self.pageYOffset; + xScroll = self.pageXOffset; + } else if (document.documentElement && document.documentElement.scrollTop) { + yScroll = document.documentElement.scrollTop; + xScroll = document.documentElement.scrollLeft; + } else if (document.body) { + yScroll = document.body.scrollTop; + xScroll = document.body.scrollLeft; + } + + return [xScroll, yScroll]; + }; + + $.fn.fancybox.getViewport = function() { + var scroll = $.fn.fancybox.getPageScroll(); + + return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; + }; + + $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { + var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); + + return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; + }; + + $.fn.fancybox.defaults = { + hideOnContentClick: false, + zoomSpeedIn: 500, + zoomSpeedOut: 500, + frameWidth: 600, + frameHeight: 400, + overlayShow: false, + overlayOpacity: 0.4, + itemLoadCallback: null, + showLoading: true, + }; +})(jQuery);
andreacampi/fancybox
2757f0b38e3fd5816fb21b17977717e529e38590
Make sure itemNum holds a value only when a full-size photo is being shown.
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index 8c9f37a..e3dbd2f 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,387 +1,388 @@ /* * FancyBox - simple jQuery plugin for fancy image zooming * Examples and documentation at: http://fancy.klade.lv/ * Version: 1.0.0 (29/04/2008) * Copyright (c) 2008 Janis Skarnelis * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php * Requires: jQuery v1.2.1 or later */ (function($) { var opts = {}, imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], loadingTimer, loadingFrame = 1; $.fn.fancybox = function(settings) { opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); $.fn.fancybox.init(); return this.each(function() { var $this = $(this); var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; $this.unbind('click').click(function() { $.fn.fancybox.start(this, o); return false; }); }); }; $.fn.fancybox.start = function(el, o) { if (opts.animating) return false; if (o.overlayShow) { $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); if ($.browser.msie) { $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); } $("#fancy_overlay").click($.fn.fancybox.close); } opts.itemArray = []; opts.itemNum = 0; if (jQuery.isFunction(o.itemLoadCallback)) { o.itemLoadCallback.apply(this, [opts]); var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} for (var i = 0; i < opts.itemArray.length; i++) { opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { opts.itemArray[i].orig = tmp; } } } else { if (!el.rel || el.rel == '') { var item = {url: el.href, title: el.title, o: o}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } opts.itemArray.push(item); } else { var arr = $("a[@rel=" + el.rel + "]").get(); for (var i = 0; i < arr.length; i++) { var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; var item = {url: arr[i].href, title: arr[i].title, o: tmp}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } if (arr[i].href == el.href) opts.itemNum = i; opts.itemArray.push(item); } } } $.fn.fancybox.changeItem(opts.itemNum); }; $.fn.fancybox.changeItem = function(n) { if (opts.showLoading) { $.fn.fancybox.showLoading(); } opts.itemNum = n; $("#fancy_nav").empty(); $("#fancy_outer").stop(); $("#fancy_title").hide(); $(document).unbind("keydown"); imgRegExp = imgTypes.join('|'); imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); var url = opts.itemArray[n].url; if (url.match(/#/)) { var target = window.location.href.split('#')[0]; target = url.replace(target,''); $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); $("#fancy_loading").hide(); } else if (url.match(imgRegExp)) { $(imgPreloader).unbind('load').bind('load', function() { $("#fancy_loading").hide(); opts.itemArray[n].o.frameWidth = imgPreloader.width; opts.itemArray[n].o.frameHeight = imgPreloader.height; $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); } else { $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); } }; $.fn.fancybox.showIframe = function() { $("#fancy_loading").hide(); $("#fancy_frame").show(); }; $.fn.fancybox.showItem = function(val) { $.fn.fancybox.preloadNeighborImages(); var viewportPos = $.fn.fancybox.getViewport(); var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; var itemOpts = { 'left': itemLeft, 'top': itemTop, 'width': itemSize[0] + 'px', 'height': itemSize[1] + 'px' } if (opts.active) { $('#fancy_content').fadeOut("normal", function() { $("#fancy_content").empty(); $("#fancy_outer").animate(itemOpts, "normal", function() { $("#fancy_content").append($(val)).fadeIn("normal"); $.fn.fancybox.updateDetails(); }); }); } else { opts.active = true; $("#fancy_content").empty(); if ($("#fancy_content").is(":animated")) { console.info('animated!'); } if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { opts.animating = true; itemOpts.opacity = "show"; $("#fancy_outer").css({ 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width }); $("#fancy_content").append($(val)).show(); $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { opts.animating = false; $.fn.fancybox.updateDetails(); }); } else { $("#fancy_content").append($(val)).show(); $("#fancy_outer").css(itemOpts).show(); $.fn.fancybox.updateDetails(); } } }; $.fn.fancybox.updateDetails = function() { $("#fancy_bg,#fancy_close").show(); if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); $('#fancy_title').show(); } if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { $("#fancy_content").click($.fn.fancybox.close); } else { $("#fancy_content").unbind('click'); } if (opts.itemNum != 0) { $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); $('#fancy_left').click(function() { $.fn.fancybox.changeItem(opts.itemNum - 1); return false; }); } if (opts.itemNum != (opts.itemArray.length - 1)) { $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); $('#fancy_right').click(function(){ $.fn.fancybox.changeItem(opts.itemNum + 1); return false; }); } $(document).keydown(function(event) { if (event.keyCode == 27) { $.fn.fancybox.close(); } else if(event.keyCode == 37 && opts.itemNum != 0) { $.fn.fancybox.changeItem(opts.itemNum - 1); } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { $.fn.fancybox.changeItem(opts.itemNum + 1); } }); }; $.fn.fancybox.preloadNeighborImages = function() { if ((opts.itemArray.length - 1) > opts.itemNum) { preloadNextImage = new Image(); preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; } if (opts.itemNum > 0) { preloadPrevImage = new Image(); preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; } }; $.fn.fancybox.close = function() { if (opts.animating) return false; $(imgPreloader).unbind('load'); $(document).unbind("keydown"); $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); $("#fancy_nav").empty(); opts.active = false; if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { var itemOpts = { 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width, 'opacity': 'hide' }; opts.animating = true; $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").remove(); opts.animating = false; }); } else { $("#fancy_outer").hide(); $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); } + opts.itemNum = null; }; $.fn.fancybox.showLoading = function() { clearInterval(loadingTimer); var pos = $.fn.fancybox.getViewport(); $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); $("#fancy_loading").bind('click', $.fn.fancybox.close); loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); }; $.fn.fancybox.animateLoading = function(el, o) { if (!$("#fancy_loading").is(':visible')){ clearInterval(loadingTimer); return; } $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; $.fn.fancybox.init = function() { if (!$('#fancy_wrap').length) { $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); } if ($.browser.msie) { $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); } if (jQuery.fn.pngFix) $(document).pngFix(); $("#fancy_close").click($.fn.fancybox.close); }; $.fn.fancybox.getPosition = function(el) { var pos = el.offset(); pos.top += $.fn.fancybox.num(el, 'paddingTop'); pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); pos.left += $.fn.fancybox.num(el, 'paddingLeft'); pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); return pos; }; $.fn.fancybox.num = function (el, prop) { return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; }; $.fn.fancybox.getPageScroll = function() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) { yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return [xScroll, yScroll]; }; $.fn.fancybox.getViewport = function() { var scroll = $.fn.fancybox.getPageScroll(); return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; }; $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; }; $.fn.fancybox.defaults = { hideOnContentClick: false, zoomSpeedIn: 500, zoomSpeedOut: 500, frameWidth: 600, frameHeight: 400, overlayShow: false, overlayOpacity: 0.4, itemLoadCallback: null, showLoading: true, }; })(jQuery);
andreacampi/fancybox
63b1a493e59e41badfbc5f18b9c170e19210f1da
Make loader animation optional.
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index d1f2b75..8c9f37a 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,384 +1,387 @@ /* * FancyBox - simple jQuery plugin for fancy image zooming * Examples and documentation at: http://fancy.klade.lv/ * Version: 1.0.0 (29/04/2008) * Copyright (c) 2008 Janis Skarnelis * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php * Requires: jQuery v1.2.1 or later */ (function($) { var opts = {}, imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], loadingTimer, loadingFrame = 1; $.fn.fancybox = function(settings) { opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); $.fn.fancybox.init(); return this.each(function() { var $this = $(this); var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; $this.unbind('click').click(function() { $.fn.fancybox.start(this, o); return false; }); }); }; $.fn.fancybox.start = function(el, o) { if (opts.animating) return false; if (o.overlayShow) { $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); if ($.browser.msie) { $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); } $("#fancy_overlay").click($.fn.fancybox.close); } opts.itemArray = []; opts.itemNum = 0; if (jQuery.isFunction(o.itemLoadCallback)) { o.itemLoadCallback.apply(this, [opts]); var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} for (var i = 0; i < opts.itemArray.length; i++) { opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { opts.itemArray[i].orig = tmp; } } } else { if (!el.rel || el.rel == '') { var item = {url: el.href, title: el.title, o: o}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } opts.itemArray.push(item); } else { var arr = $("a[@rel=" + el.rel + "]").get(); for (var i = 0; i < arr.length; i++) { var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; var item = {url: arr[i].href, title: arr[i].title, o: tmp}; if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} } if (arr[i].href == el.href) opts.itemNum = i; opts.itemArray.push(item); } } } $.fn.fancybox.changeItem(opts.itemNum); }; $.fn.fancybox.changeItem = function(n) { - $.fn.fancybox.showLoading(); + if (opts.showLoading) { + $.fn.fancybox.showLoading(); + } opts.itemNum = n; $("#fancy_nav").empty(); $("#fancy_outer").stop(); $("#fancy_title").hide(); $(document).unbind("keydown"); imgRegExp = imgTypes.join('|'); imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); var url = opts.itemArray[n].url; if (url.match(/#/)) { var target = window.location.href.split('#')[0]; target = url.replace(target,''); $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); $("#fancy_loading").hide(); } else if (url.match(imgRegExp)) { $(imgPreloader).unbind('load').bind('load', function() { $("#fancy_loading").hide(); opts.itemArray[n].o.frameWidth = imgPreloader.width; opts.itemArray[n].o.frameHeight = imgPreloader.height; $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); } else { $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); } }; $.fn.fancybox.showIframe = function() { $("#fancy_loading").hide(); $("#fancy_frame").show(); }; $.fn.fancybox.showItem = function(val) { $.fn.fancybox.preloadNeighborImages(); var viewportPos = $.fn.fancybox.getViewport(); var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; var itemOpts = { 'left': itemLeft, 'top': itemTop, 'width': itemSize[0] + 'px', 'height': itemSize[1] + 'px' } if (opts.active) { $('#fancy_content').fadeOut("normal", function() { $("#fancy_content").empty(); $("#fancy_outer").animate(itemOpts, "normal", function() { $("#fancy_content").append($(val)).fadeIn("normal"); $.fn.fancybox.updateDetails(); }); }); } else { opts.active = true; $("#fancy_content").empty(); if ($("#fancy_content").is(":animated")) { console.info('animated!'); } if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { opts.animating = true; itemOpts.opacity = "show"; $("#fancy_outer").css({ 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width }); $("#fancy_content").append($(val)).show(); $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { opts.animating = false; $.fn.fancybox.updateDetails(); }); } else { $("#fancy_content").append($(val)).show(); $("#fancy_outer").css(itemOpts).show(); $.fn.fancybox.updateDetails(); } } }; $.fn.fancybox.updateDetails = function() { $("#fancy_bg,#fancy_close").show(); if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); $('#fancy_title').show(); } if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { $("#fancy_content").click($.fn.fancybox.close); } else { $("#fancy_content").unbind('click'); } if (opts.itemNum != 0) { $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); $('#fancy_left').click(function() { $.fn.fancybox.changeItem(opts.itemNum - 1); return false; }); } if (opts.itemNum != (opts.itemArray.length - 1)) { $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); $('#fancy_right').click(function(){ $.fn.fancybox.changeItem(opts.itemNum + 1); return false; }); } $(document).keydown(function(event) { if (event.keyCode == 27) { $.fn.fancybox.close(); } else if(event.keyCode == 37 && opts.itemNum != 0) { $.fn.fancybox.changeItem(opts.itemNum - 1); } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { $.fn.fancybox.changeItem(opts.itemNum + 1); } }); }; $.fn.fancybox.preloadNeighborImages = function() { if ((opts.itemArray.length - 1) > opts.itemNum) { preloadNextImage = new Image(); preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; } if (opts.itemNum > 0) { preloadPrevImage = new Image(); preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; } }; $.fn.fancybox.close = function() { if (opts.animating) return false; $(imgPreloader).unbind('load'); $(document).unbind("keydown"); $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); $("#fancy_nav").empty(); opts.active = false; if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { var itemOpts = { 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, 'height': opts.itemArray[opts.itemNum].orig.height, 'width': opts.itemArray[opts.itemNum].orig.width, 'opacity': 'hide' }; opts.animating = true; $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").remove(); opts.animating = false; }); } else { $("#fancy_outer").hide(); $("#fancy_content").hide().empty(); $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); } }; $.fn.fancybox.showLoading = function() { clearInterval(loadingTimer); var pos = $.fn.fancybox.getViewport(); $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); $("#fancy_loading").bind('click', $.fn.fancybox.close); loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); }; $.fn.fancybox.animateLoading = function(el, o) { if (!$("#fancy_loading").is(':visible')){ clearInterval(loadingTimer); return; } $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; $.fn.fancybox.init = function() { if (!$('#fancy_wrap').length) { $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); } if ($.browser.msie) { $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); } if (jQuery.fn.pngFix) $(document).pngFix(); $("#fancy_close").click($.fn.fancybox.close); }; $.fn.fancybox.getPosition = function(el) { var pos = el.offset(); pos.top += $.fn.fancybox.num(el, 'paddingTop'); pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); pos.left += $.fn.fancybox.num(el, 'paddingLeft'); pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); return pos; }; $.fn.fancybox.num = function (el, prop) { return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; }; $.fn.fancybox.getPageScroll = function() { var xScroll, yScroll; if (self.pageYOffset) { yScroll = self.pageYOffset; xScroll = self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollTop) { yScroll = document.documentElement.scrollTop; xScroll = document.documentElement.scrollLeft; } else if (document.body) { yScroll = document.body.scrollTop; xScroll = document.body.scrollLeft; } return [xScroll, yScroll]; }; $.fn.fancybox.getViewport = function() { var scroll = $.fn.fancybox.getPageScroll(); return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; }; $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; }; $.fn.fancybox.defaults = { hideOnContentClick: false, zoomSpeedIn: 500, zoomSpeedOut: 500, frameWidth: 600, frameHeight: 400, overlayShow: false, overlayOpacity: 0.4, - itemLoadCallback: null + itemLoadCallback: null, + showLoading: true, }; -})(jQuery); \ No newline at end of file +})(jQuery);
andreacampi/fancybox
fbb8f5adaaaf0f62b91941fd6663b1aca600260d
Revert "Unix newlines."
diff --git a/jquery.fancybox-1.0.0.js b/jquery.fancybox-1.0.0.js index bd932dd..d1f2b75 100755 --- a/jquery.fancybox-1.0.0.js +++ b/jquery.fancybox-1.0.0.js @@ -1,384 +1,384 @@ -/* - * FancyBox - simple jQuery plugin for fancy image zooming - * Examples and documentation at: http://fancy.klade.lv/ - * Version: 1.0.0 (29/04/2008) - * Copyright (c) 2008 Janis Skarnelis - * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php - * Requires: jQuery v1.2.1 or later -*/ -(function($) { - var opts = {}, - imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], - loadingTimer, loadingFrame = 1; - - $.fn.fancybox = function(settings) { - opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); - - $.fn.fancybox.init(); - - return this.each(function() { - var $this = $(this); - var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; - - $this.unbind('click').click(function() { - $.fn.fancybox.start(this, o); return false; - }); - }); - }; - - $.fn.fancybox.start = function(el, o) { - if (opts.animating) return false; - - if (o.overlayShow) { - $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); - $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); - - if ($.browser.msie) { - $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); - $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); - } - - $("#fancy_overlay").click($.fn.fancybox.close); - } - - opts.itemArray = []; - opts.itemNum = 0; - - if (jQuery.isFunction(o.itemLoadCallback)) { - o.itemLoadCallback.apply(this, [opts]); - - var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); - var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - - for (var i = 0; i < opts.itemArray.length; i++) { - opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - opts.itemArray[i].orig = tmp; - } - } - - } else { - if (!el.rel || el.rel == '') { - var item = {url: el.href, title: el.title, o: o}; - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); - item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - } - - opts.itemArray.push(item); - - } else { - var arr = $("a[@rel=" + el.rel + "]").get(); - - for (var i = 0; i < arr.length; i++) { - var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; - var item = {url: arr[i].href, title: arr[i].title, o: tmp}; - - if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { - var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); - - item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} - } - - if (arr[i].href == el.href) opts.itemNum = i; - - opts.itemArray.push(item); - } - } - } - - $.fn.fancybox.changeItem(opts.itemNum); - }; - - $.fn.fancybox.changeItem = function(n) { - $.fn.fancybox.showLoading(); - - opts.itemNum = n; - - $("#fancy_nav").empty(); - $("#fancy_outer").stop(); - $("#fancy_title").hide(); - $(document).unbind("keydown"); - - imgRegExp = imgTypes.join('|'); - imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); - - var url = opts.itemArray[n].url; - - if (url.match(/#/)) { - var target = window.location.href.split('#')[0]; target = url.replace(target,''); - - $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); - - $("#fancy_loading").hide(); - - } else if (url.match(imgRegExp)) { - $(imgPreloader).unbind('load').bind('load', function() { - $("#fancy_loading").hide(); - - opts.itemArray[n].o.frameWidth = imgPreloader.width; - opts.itemArray[n].o.frameHeight = imgPreloader.height; - - $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); - - }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); - - } else { - $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); - } - }; - - $.fn.fancybox.showIframe = function() { - $("#fancy_loading").hide(); - $("#fancy_frame").show(); - }; - - $.fn.fancybox.showItem = function(val) { - $.fn.fancybox.preloadNeighborImages(); - - var viewportPos = $.fn.fancybox.getViewport(); - var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); - - var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; - var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; - - var itemOpts = { - 'left': itemLeft, - 'top': itemTop, - 'width': itemSize[0] + 'px', - 'height': itemSize[1] + 'px' - } - - if (opts.active) { - $('#fancy_content').fadeOut("normal", function() { - $("#fancy_content").empty(); - - $("#fancy_outer").animate(itemOpts, "normal", function() { - $("#fancy_content").append($(val)).fadeIn("normal"); - $.fn.fancybox.updateDetails(); - }); - }); - - } else { - opts.active = true; - - $("#fancy_content").empty(); - - if ($("#fancy_content").is(":animated")) { - console.info('animated!'); - } - - if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { - opts.animating = true; - itemOpts.opacity = "show"; - - $("#fancy_outer").css({ - 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, - 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, - 'height': opts.itemArray[opts.itemNum].orig.height, - 'width': opts.itemArray[opts.itemNum].orig.width - }); - - $("#fancy_content").append($(val)).show(); - - $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { - opts.animating = false; - $.fn.fancybox.updateDetails(); - }); - - } else { - $("#fancy_content").append($(val)).show(); - $("#fancy_outer").css(itemOpts).show(); - $.fn.fancybox.updateDetails(); - } - } - }; - - $.fn.fancybox.updateDetails = function() { - $("#fancy_bg,#fancy_close").show(); - - if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { - $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); - $('#fancy_title').show(); - } - - if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { - $("#fancy_content").click($.fn.fancybox.close); - } else { - $("#fancy_content").unbind('click'); - } - - if (opts.itemNum != 0) { - $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); - - $('#fancy_left').click(function() { - $.fn.fancybox.changeItem(opts.itemNum - 1); return false; - }); - } - - if (opts.itemNum != (opts.itemArray.length - 1)) { - $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); - - $('#fancy_right').click(function(){ - $.fn.fancybox.changeItem(opts.itemNum + 1); return false; - }); - } - - $(document).keydown(function(event) { - if (event.keyCode == 27) { - $.fn.fancybox.close(); - - } else if(event.keyCode == 37 && opts.itemNum != 0) { - $.fn.fancybox.changeItem(opts.itemNum - 1); - - } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { - $.fn.fancybox.changeItem(opts.itemNum + 1); - } - }); - }; - - $.fn.fancybox.preloadNeighborImages = function() { - if ((opts.itemArray.length - 1) > opts.itemNum) { - preloadNextImage = new Image(); - preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; - } - - if (opts.itemNum > 0) { - preloadPrevImage = new Image(); - preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; - } - }; - - $.fn.fancybox.close = function() { - if (opts.animating) return false; - - $(imgPreloader).unbind('load'); - $(document).unbind("keydown"); - - $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); - - $("#fancy_nav").empty(); - - opts.active = false; - - if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { - var itemOpts = { - 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, - 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, - 'height': opts.itemArray[opts.itemNum].orig.height, - 'width': opts.itemArray[opts.itemNum].orig.width, - 'opacity': 'hide' - }; - - opts.animating = true; - - $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { - $("#fancy_content").hide().empty(); - $("#fancy_overlay,#fancy_bigIframe").remove(); - opts.animating = false; - }); - - } else { - $("#fancy_outer").hide(); - $("#fancy_content").hide().empty(); - $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); - } - }; - - $.fn.fancybox.showLoading = function() { - clearInterval(loadingTimer); - - var pos = $.fn.fancybox.getViewport(); - - $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); - $("#fancy_loading").bind('click', $.fn.fancybox.close); - - loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); - }; - - $.fn.fancybox.animateLoading = function(el, o) { - if (!$("#fancy_loading").is(':visible')){ - clearInterval(loadingTimer); - return; - } - - $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); - - loadingFrame = (loadingFrame + 1) % 12; - }; - - $.fn.fancybox.init = function() { - if (!$('#fancy_wrap').length) { - $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); - $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); - - $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); - } - - if ($.browser.msie) { - $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); - } - - if (jQuery.fn.pngFix) $(document).pngFix(); - - $("#fancy_close").click($.fn.fancybox.close); - }; - - $.fn.fancybox.getPosition = function(el) { - var pos = el.offset(); - - pos.top += $.fn.fancybox.num(el, 'paddingTop'); - pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); - - pos.left += $.fn.fancybox.num(el, 'paddingLeft'); - pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); - - return pos; - }; - - $.fn.fancybox.num = function (el, prop) { - return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; - }; - - $.fn.fancybox.getPageScroll = function() { - var xScroll, yScroll; - - if (self.pageYOffset) { - yScroll = self.pageYOffset; - xScroll = self.pageXOffset; - } else if (document.documentElement && document.documentElement.scrollTop) { - yScroll = document.documentElement.scrollTop; - xScroll = document.documentElement.scrollLeft; - } else if (document.body) { - yScroll = document.body.scrollTop; - xScroll = document.body.scrollLeft; - } - - return [xScroll, yScroll]; - }; - - $.fn.fancybox.getViewport = function() { - var scroll = $.fn.fancybox.getPageScroll(); - - return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; - }; - - $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { - var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); - - return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; - }; - - $.fn.fancybox.defaults = { - hideOnContentClick: false, - zoomSpeedIn: 500, - zoomSpeedOut: 500, - frameWidth: 600, - frameHeight: 400, - overlayShow: false, - overlayOpacity: 0.4, - itemLoadCallback: null - }; +/* + * FancyBox - simple jQuery plugin for fancy image zooming + * Examples and documentation at: http://fancy.klade.lv/ + * Version: 1.0.0 (29/04/2008) + * Copyright (c) 2008 Janis Skarnelis + * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php + * Requires: jQuery v1.2.1 or later +*/ +(function($) { + var opts = {}, + imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], + loadingTimer, loadingFrame = 1; + + $.fn.fancybox = function(settings) { + opts.settings = $.extend({}, $.fn.fancybox.defaults, settings); + + $.fn.fancybox.init(); + + return this.each(function() { + var $this = $(this); + var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings; + + $this.unbind('click').click(function() { + $.fn.fancybox.start(this, o); return false; + }); + }); + }; + + $.fn.fancybox.start = function(el, o) { + if (opts.animating) return false; + + if (o.overlayShow) { + $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>'); + $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity}); + + if ($.browser.msie) { + $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>'); + $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0}); + } + + $("#fancy_overlay").click($.fn.fancybox.close); + } + + opts.itemArray = []; + opts.itemNum = 0; + + if (jQuery.isFunction(o.itemLoadCallback)) { + o.itemLoadCallback.apply(this, [opts]); + + var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); + var tmp = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + + for (var i = 0; i < opts.itemArray.length; i++) { + opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o); + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + opts.itemArray[i].orig = tmp; + } + } + + } else { + if (!el.rel || el.rel == '') { + var item = {url: el.href, title: el.title, o: o}; + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el); + item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + } + + opts.itemArray.push(item); + + } else { + var arr = $("a[@rel=" + el.rel + "]").get(); + + for (var i = 0; i < arr.length; i++) { + var tmp = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o; + var item = {url: arr[i].href, title: arr[i].title, o: tmp}; + + if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) { + var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el); + + item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)} + } + + if (arr[i].href == el.href) opts.itemNum = i; + + opts.itemArray.push(item); + } + } + } + + $.fn.fancybox.changeItem(opts.itemNum); + }; + + $.fn.fancybox.changeItem = function(n) { + $.fn.fancybox.showLoading(); + + opts.itemNum = n; + + $("#fancy_nav").empty(); + $("#fancy_outer").stop(); + $("#fancy_title").hide(); + $(document).unbind("keydown"); + + imgRegExp = imgTypes.join('|'); + imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i'); + + var url = opts.itemArray[n].url; + + if (url.match(/#/)) { + var target = window.location.href.split('#')[0]; target = url.replace(target,''); + + $.fn.fancybox.showItem('<div id="fancy_div">' + $(target).html() + '</div>'); + + $("#fancy_loading").hide(); + + } else if (url.match(imgRegExp)) { + $(imgPreloader).unbind('load').bind('load', function() { + $("#fancy_loading").hide(); + + opts.itemArray[n].o.frameWidth = imgPreloader.width; + opts.itemArray[n].o.frameHeight = imgPreloader.height; + + $.fn.fancybox.showItem('<img id="fancy_img" src="' + imgPreloader.src + '" />'); + + }).attr('src', url + '?rand=' + Math.floor(Math.random() * 999999999) ); + + } else { + $.fn.fancybox.showItem('<iframe id="fancy_frame" onload="$.fn.fancybox.showIframe()" name="fancy_iframe' + Math.round(Math.random()*1000) + '" frameborder="0" hspace="0" src="' + url + '"></iframe>'); + } + }; + + $.fn.fancybox.showIframe = function() { + $("#fancy_loading").hide(); + $("#fancy_frame").show(); + }; + + $.fn.fancybox.showItem = function(val) { + $.fn.fancybox.preloadNeighborImages(); + + var viewportPos = $.fn.fancybox.getViewport(); + var itemSize = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight); + + var itemLeft = viewportPos[2] + Math.round((viewportPos[0] - itemSize[0]) / 2) - 20; + var itemTop = viewportPos[3] + Math.round((viewportPos[1] - itemSize[1]) / 2) - 40; + + var itemOpts = { + 'left': itemLeft, + 'top': itemTop, + 'width': itemSize[0] + 'px', + 'height': itemSize[1] + 'px' + } + + if (opts.active) { + $('#fancy_content').fadeOut("normal", function() { + $("#fancy_content").empty(); + + $("#fancy_outer").animate(itemOpts, "normal", function() { + $("#fancy_content").append($(val)).fadeIn("normal"); + $.fn.fancybox.updateDetails(); + }); + }); + + } else { + opts.active = true; + + $("#fancy_content").empty(); + + if ($("#fancy_content").is(":animated")) { + console.info('animated!'); + } + + if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) { + opts.animating = true; + itemOpts.opacity = "show"; + + $("#fancy_outer").css({ + 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, + 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, + 'height': opts.itemArray[opts.itemNum].orig.height, + 'width': opts.itemArray[opts.itemNum].orig.width + }); + + $("#fancy_content").append($(val)).show(); + + $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() { + opts.animating = false; + $.fn.fancybox.updateDetails(); + }); + + } else { + $("#fancy_content").append($(val)).show(); + $("#fancy_outer").css(itemOpts).show(); + $.fn.fancybox.updateDetails(); + } + } + }; + + $.fn.fancybox.updateDetails = function() { + $("#fancy_bg,#fancy_close").show(); + + if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') { + $('#fancy_title div').html(opts.itemArray[opts.itemNum].title); + $('#fancy_title').show(); + } + + if (opts.itemArray[opts.itemNum].o.hideOnContentClick) { + $("#fancy_content").click($.fn.fancybox.close); + } else { + $("#fancy_content").unbind('click'); + } + + if (opts.itemNum != 0) { + $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>'); + + $('#fancy_left').click(function() { + $.fn.fancybox.changeItem(opts.itemNum - 1); return false; + }); + } + + if (opts.itemNum != (opts.itemArray.length - 1)) { + $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>'); + + $('#fancy_right').click(function(){ + $.fn.fancybox.changeItem(opts.itemNum + 1); return false; + }); + } + + $(document).keydown(function(event) { + if (event.keyCode == 27) { + $.fn.fancybox.close(); + + } else if(event.keyCode == 37 && opts.itemNum != 0) { + $.fn.fancybox.changeItem(opts.itemNum - 1); + + } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) { + $.fn.fancybox.changeItem(opts.itemNum + 1); + } + }); + }; + + $.fn.fancybox.preloadNeighborImages = function() { + if ((opts.itemArray.length - 1) > opts.itemNum) { + preloadNextImage = new Image(); + preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url; + } + + if (opts.itemNum > 0) { + preloadPrevImage = new Image(); + preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url; + } + }; + + $.fn.fancybox.close = function() { + if (opts.animating) return false; + + $(imgPreloader).unbind('load'); + $(document).unbind("keydown"); + + $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide(); + + $("#fancy_nav").empty(); + + opts.active = false; + + if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) { + var itemOpts = { + 'top': opts.itemArray[opts.itemNum].orig.pos.top - 18, + 'left': opts.itemArray[opts.itemNum].orig.pos.left - 18, + 'height': opts.itemArray[opts.itemNum].orig.height, + 'width': opts.itemArray[opts.itemNum].orig.width, + 'opacity': 'hide' + }; + + opts.animating = true; + + $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() { + $("#fancy_content").hide().empty(); + $("#fancy_overlay,#fancy_bigIframe").remove(); + opts.animating = false; + }); + + } else { + $("#fancy_outer").hide(); + $("#fancy_content").hide().empty(); + $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove(); + } + }; + + $.fn.fancybox.showLoading = function() { + clearInterval(loadingTimer); + + var pos = $.fn.fancybox.getViewport(); + + $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show(); + $("#fancy_loading").bind('click', $.fn.fancybox.close); + + loadingTimer = setInterval($.fn.fancybox.animateLoading, 66); + }; + + $.fn.fancybox.animateLoading = function(el, o) { + if (!$("#fancy_loading").is(':visible')){ + clearInterval(loadingTimer); + return; + } + + $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px'); + + loadingFrame = (loadingFrame + 1) % 12; + }; + + $.fn.fancybox.init = function() { + if (!$('#fancy_wrap').length) { + $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body"); + $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner"); + + $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title'); + } + + if ($.browser.msie) { + $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>'); + } + + if (jQuery.fn.pngFix) $(document).pngFix(); + + $("#fancy_close").click($.fn.fancybox.close); + }; + + $.fn.fancybox.getPosition = function(el) { + var pos = el.offset(); + + pos.top += $.fn.fancybox.num(el, 'paddingTop'); + pos.top += $.fn.fancybox.num(el, 'borderTopWidth'); + + pos.left += $.fn.fancybox.num(el, 'paddingLeft'); + pos.left += $.fn.fancybox.num(el, 'borderLeftWidth'); + + return pos; + }; + + $.fn.fancybox.num = function (el, prop) { + return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0; + }; + + $.fn.fancybox.getPageScroll = function() { + var xScroll, yScroll; + + if (self.pageYOffset) { + yScroll = self.pageYOffset; + xScroll = self.pageXOffset; + } else if (document.documentElement && document.documentElement.scrollTop) { + yScroll = document.documentElement.scrollTop; + xScroll = document.documentElement.scrollLeft; + } else if (document.body) { + yScroll = document.body.scrollTop; + xScroll = document.body.scrollLeft; + } + + return [xScroll, yScroll]; + }; + + $.fn.fancybox.getViewport = function() { + var scroll = $.fn.fancybox.getPageScroll(); + + return [$(window).width(), $(window).height(), scroll[0], scroll[1]]; + }; + + $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) { + var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight); + + return [Math.round(r * imageWidth), Math.round(r * imageHeight)]; + }; + + $.fn.fancybox.defaults = { + hideOnContentClick: false, + zoomSpeedIn: 500, + zoomSpeedOut: 500, + frameWidth: 600, + frameHeight: 400, + overlayShow: false, + overlayOpacity: 0.4, + itemLoadCallback: null + }; })(jQuery); \ No newline at end of file