repo
stringlengths
5
75
commit
stringlengths
40
40
message
stringlengths
6
18.2k
diff
stringlengths
60
262k
aemadrid/rubyhaze-persisted
b95dc369bf8f2ca10c59b642fe3a2dea4f668cb9
Version bump to 0.0.1
diff --git a/VERSION b/VERSION index 77d6f4c..8acdd82 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.0 +0.0.1
aemadrid/rubyhaze-persisted
4c02e2bc87392c956ec60ede70304d42800e0df3
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
aemadrid/rubyhaze-persisted
d7f7d4e3981e610ecc1258ecd2af536f30fb9509
First running version
diff --git a/.gitignore b/.gitignore index c1e0daf..a2972e6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,23 @@ ## MAC OS .DS_Store ## TEXTMATE *.tmproj tmtags ## EMACS *~ \#* .\#* ## VIM *.swp ## PROJECT::GENERAL coverage rdoc pkg +.rvmrc +.idea/* ## PROJECT::SPECIFIC diff --git a/README.rdoc b/README.rdoc index 62e3acc..84f7277 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,17 +1,42 @@ = rubyhaze-persisted -Description goes here. +RubyHaze Persisted is a little gem that helps you persist and search your (j)ruby objects into Hazelcast distributed maps. + +== Getting started + +Let's get some distributed ruby objects going: + + shell> rvm jruby + shell> gem install rubyhaze-persisted + shell> rubyhaze_console + + require 'rubyhaze-persisted' + + class Foo + include RubyHaze::Persisted + field :name, :string + field :age, :int + end + + a = Foo.create :name => "Raffaello", :age => 32 + b = Foo.create :name => "Leonardo", :age => 45 + c = Foo.create :name => "Michelangelo", :age => 65 + + found = Foo.find "age < 60 AND name LIKE '%lo'" + found.first.name + + >> "Raffaello" == Note on Patches/Pull Requests - + * Fork the project. * Make your feature addition or bug fix. * Add tests for it. This is important so I don't break it in a - future version unintentionally. + future version unintentionally. * Commit, do not mess with rakefile, version, or history. - (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) + (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) * Send me a pull request. Bonus points for topic branches. == Copyright Copyright (c) 2010 Adrian Madrid. See LICENSE for details. diff --git a/Rakefile b/Rakefile index d681f57..b19ec56 100644 --- a/Rakefile +++ b/Rakefile @@ -1,52 +1,55 @@ require 'rubygems' require 'rake' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "rubyhaze-persisted" gem.summary = %Q{ActiveRecord-like objects persisted with Hazelcast and RubyHaze} gem.description = %Q{TODO: longer description of your gem} gem.email = "[email protected]" gem.homepage = "http://github.com/aemadrid/rubyhaze-persisted" gem.authors = ["Adrian Madrid"] - # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings + gem.files = FileList['bin/*', 'lib/**/*.rb', 'test/**/*.rb', '[A-Z]*'].to_a + gem.test_files = Dir["test/test*.rb"] + gem.platform = "jruby" + gem.add_dependency "bitescript" 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 = "rubyhaze-persisted #{version}" rdoc.rdoc_files.include('README*') rdoc.rdoc_files.include('lib/**/*.rb') end diff --git a/lib/rubyhaze-persisted.rb b/lib/rubyhaze-persisted.rb deleted file mode 100644 index e69de29..0000000 diff --git a/lib/rubyhaze/persisted.rb b/lib/rubyhaze/persisted.rb new file mode 100644 index 0000000..53b3cdc --- /dev/null +++ b/lib/rubyhaze/persisted.rb @@ -0,0 +1,12 @@ +$:.unshift File.expand_path(File.join(File.dirname(__FILE__), 'persisted')) +require 'shadow_class_generator' +require 'model' + +class D + include RubyHaze::Persisted + attribute :name, :string + attribute :age, :int + + + validates_presence_of :name +end \ No newline at end of file diff --git a/lib/rubyhaze/persisted/model.rb b/lib/rubyhaze/persisted/model.rb new file mode 100644 index 0000000..4fe6f91 --- /dev/null +++ b/lib/rubyhaze/persisted/model.rb @@ -0,0 +1,218 @@ +require "rubyhaze" + +gem "activesupport" + +require "active_support/core_ext/module/attr_accessor_with_default" +require "active_support/core_ext/object/blank" +require "active_support/concern" +require "active_support/callbacks" + +require "active_model" + +module RubyHaze + module Persisted + + extend ActiveSupport::Concern + include ActiveSupport::Callbacks + + extend ActiveModel::Naming + extend ActiveModel::Translation + extend ActiveModel::Callbacks + + include ActiveModel::AttributeMethods + include ActiveModel::Conversion + include ActiveModel::Dirty + include ActiveModel::Serialization + include ActiveModel::Serializers::JSON + include ActiveModel::Serializers::Xml + include ActiveModel::Validations + + included do + attribute_method_suffix '', '=', '?' + extend ClassMethods + end + + module InstanceMethods + + def initialize(options = {}) + options.each { |name, value| send "#{name}=", value } + @callbacks = [] + @new_record = true + @destroyed = false + end + + def new_record? + @new_record + end + + def persisted? + !(new_record? || destroyed?) + end + + def destroyed? + @destroyed + end + + def attribute(key) + instance_variable_get("@#{key}") + end + + def attribute=(key, value) + send("#{key}_will_change!") unless value == attribute(key) + instance_variable_set("@#{key}", value) + end + + def attribute?(key) + instance_variable_get("@#{key}").present? + end + + def attribute_names + self.class.attribute_names + end + + def attribute_types + self.class.attribute_types + end + + def attribute_options + self.class.attribute_options + end + + def attributes + attrs = {} + attribute_names.each { |name| attrs[name.to_s] = attribute(name) } + attrs + end + + def values + attribute_names.map { |name| attribute(name) } + end + + def to_ary + attribute_names.map { |name| [name.to_s, instance_variable_get("@#{name}")] }.unshift ['class', self.class.name] + end + + def ==(other) + return false unless other.respond_to? :to_ary + to_ary == other.to_ary + end + + def shadow_object + self.class.map_java_class.new *values + end + + def load_shadow_object(shadow) + attribute_names.each do |name| + send "attribute=", name, shadow.send(name) + end + self + end + + def save + create_or_update + end + + def save! + create_or_update || raise("Not saved") + end + + def create_or_update + result = new_record? ? create : update + result != false + end + + def update + raise "Missing uid" unless uid? + self.class.map[uid] = shadow_object + @previously_changed = changes + @changed_attributes.clear + true + end + + def create + @uid ||= RubyHaze.random_uuid + self.class.map[uid] = shadow_object + @previously_changed = changes + @changed_attributes.clear + @new_record = false + uid + end + + def load + raise "Missing uid for load" if uid.blank? + found = self.class.map[uid] + raise "Record not found" unless found + load_shadow_object(found) + @changed_attributes.clear + @new_record = false + self + end + alias :reload :load + alias :reset :load + + def to_s + "<#{self.class.name}:#{object_id} #{to_ary[1..-1].map { |k, v| "#{k}=#{v}" }.join(" ")} >" + end + + alias :inspect :to_s + + def to_key + persisted? ? [uid] : nil + end + + end + + module ClassMethods + + def create(options = {}) + obj = new options + obj.save + obj + end + + def map_java_class_name + 'RubyHaze_Shadow__' + name + end + + def map_java_class + @java_class ||= RubyHaze::Persisted::ShadowClassGenerator.get map_java_class_name, attributes + end + + def map + @map ||= RubyHaze::Map.new map_java_class_name + end + + def attributes + @attributes ||= [[:uid, :string, {}]] + end + + def attribute_names() + attributes.map { |ary| ary[0] } + end + + def attribute_types() + attributes.map { |ary| ary[1] } + end + + def attribute_options() + attributes.map { |ary| ary[2] } + end + + def attribute(name, type, options = {}) + raise "Attribute [#{name}] already defined" if attribute_names.include?(name) + @attributes << [name, type, options] +# attr_accessor name + end + + def find(predicate) + map.values(predicate).map { |shadow| new.load_shadow_object shadow } + end + + def find_uids(predicate) + map.keys(predicate) + end + + end + + end +end diff --git a/lib/rubyhaze/persisted/shadow_class_generator.rb b/lib/rubyhaze/persisted/shadow_class_generator.rb new file mode 100644 index 0000000..bdd3c25 --- /dev/null +++ b/lib/rubyhaze/persisted/shadow_class_generator.rb @@ -0,0 +1,64 @@ +require 'bitescript' + +module RubyHaze + module Persisted + module ShadowClassGenerator + + def self.get(name, attributes) + RubyHaze::Persisted.const_defined?(name) ? + RubyHaze::Persisted.const_get(name) : + generate(name, attributes) + end + + def self.attribute_load_types + { + :string => :aload, + :int => :iload, + :boolean => :iload, + :double => :dload, + } + end + + def self.generate(name, attributes) + tmp_path = (ENV['RUBYHAZE_PERSISTED_TMP_PATH'] || File.join(Dir.pwd, 'tmp')) + builder = BiteScript::FileBuilder.new name + '.class' + class_dsl = [] + class_dsl << %{public_class "#{name}", object, Java::JavaIo::Serializable do} + attributes.each do |attr_name, type, options| + class_dsl << %{ public_field :#{attr_name}, send(:#{type})} + end + class_dsl << %{ public_constructor [], #{attributes.map { |ary| ary[1].to_s }.join(', ')} do} + class_dsl << %{ aload 0} + class_dsl << %{ invokespecial object, "<init>", [void]} + index = 1 + attributes.each do |attr_name, type, options| + class_dsl << %{ aload 0} + class_dsl << %{ #{attribute_load_types[type]} #{index}} + index += 1 + class_dsl << %{ putfield this, :#{attr_name}, send(:#{type})} + end + class_dsl << %{ returnvoid} + class_dsl << %{ end} + class_dsl << %{end} + class_dsl = class_dsl.join("\n") + if $DEBUG + FileUtils.mkdir_p tmp_path + filename = File.join tmp_path, name + '.bc' + File.open(filename, 'w') { |file| file.write class_dsl } + end + builder.instance_eval class_dsl, __FILE__, __LINE__ + builder.generate do |builder_filename, class_builder| + bytes = class_builder.generate + klass = JRuby.runtime.jruby_class_loader.define_class name, bytes.to_java_bytes + if $DEBUG + filename = File.join tmp_path, builder_filename + File.open(filename, 'w') { |file| file.write class_builder.generate } + end + RubyHaze::Persisted.const_set name, JavaUtilities.get_proxy_class(klass.name) + end + RubyHaze::Persisted.const_get name + end + + end + end +end \ No newline at end of file diff --git a/test/helper.rb b/test/helper.rb index 77c1c88..8d1befd 100644 --- a/test/helper.rb +++ b/test/helper.rb @@ -1,9 +1,11 @@ -require 'rubygems' require 'test/unit' +require 'forwardable' -$LOAD_PATH.unshift(File.dirname(__FILE__)) -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) -require 'rubyhaze-persisted' +require File.expand_path(File.dirname(__FILE__) + '/../lib/rubyhaze/persisted') class Test::Unit::TestCase end + +# Start a new hazelcast cluster +RubyHaze.init :group => { :username => "test_persisted", :password => "test_persisted" } + diff --git a/test/test_model.rb b/test/test_model.rb new file mode 100644 index 0000000..014063e --- /dev/null +++ b/test/test_model.rb @@ -0,0 +1,14 @@ +require File.expand_path(File.dirname(__FILE__) + '/helper') + +class LintTest < ActiveModel::TestCase + include ActiveModel::Lint::Tests + + class PersistedTestModel + include RubyHaze::Persisted + attribute :name, :string + end + + def setup + @model = PersistedTestModel.new + end +end \ No newline at end of file diff --git a/test/test_persisted.rb b/test/test_persisted.rb new file mode 100644 index 0000000..9724497 --- /dev/null +++ b/test/test_persisted.rb @@ -0,0 +1,83 @@ +require File.expand_path(File.dirname(__FILE__) + '/helper') + +class Foo + include RubyHaze::Persisted + attribute :name, :string + attribute :age, :int +end unless defined? Foo + +class TestRubyHazePersistedClassMethods < Test::Unit::TestCase + + def test_right_store + store = Foo.map + assert_equal store.class.name, "RubyHaze::Map" + assert_equal store.name, "RubyHaze_Shadow__Foo" + assert_equal store.name, RubyHaze::Map.new("RubyHaze_Shadow__Foo").name + end + + def test_right_fields + fields = Foo.attributes + assert_equal fields, [[:uid, :string, {}], [:name, :string, {}], [:age, :int, {}]] + assert_equal Foo.attribute_names, [:uid, :name, :age] + assert_equal Foo.attribute_types, [:string, :string, :int] + assert_equal Foo.attribute_options, [{}, {}, {}] + end + + def test_right_shadow_class + assert_equal Foo.map_java_class_name, "RubyHaze_Shadow__Foo" + assert_equal Foo.map_java_class.name, "Java::Default::RubyHaze_Shadow__Foo" + end + +end + +class TestRubyHazePersistedStorage < Test::Unit::TestCase + + def test_store_reload_objects + Foo.map.clear + assert_equal Foo.map.size, 0 + @a = Foo.create :name => "Leonardo", :age => 65 + assert_equal Foo.map.size, 1 + @b = Foo.create :name => "Michelangelo", :age => 45 + assert_equal Foo.map.size, 2 + @b.age = 47 + @b.reload + assert_equal Foo.map.size, 2 + assert_equal @b.age, 45 + Foo.map.clear + assert_equal Foo.map.size, 0 + end + + def test_find_through_predicates + Foo.map.clear + @a = Foo.create :name => "Leonardo", :age => 65 + @b = Foo.create :name => "Michelangelo", :age => 45 + @c = Foo.create :name => "Raffaello", :age => 32 + + res = Foo.find 'age < 40' + assert_equal res.size, 1 + assert_equal res.first, @c + assert_equal res.first.name, @c.name + + res = Foo.find 'age BETWEEN 40 AND 50' + assert_equal res.size, 1 + assert_equal res.first, @b + assert_equal res.first.name, @b.name + + res = Foo.find "name LIKE 'Leo%'" + assert_equal res.size, 1 + assert_equal res.first, @a + assert_equal res.first.name, @a.name + +# res = Foo.find "age IN (32, 65)" +# assert_equal res.size, 2 +# names = res.map{|x| x.name }.sort +# assert_equal names.first, @a.name +# assert_equal names.last, @b.name + + res = Foo.find "age < 40 AND name LIKE '%o'" + assert_equal res.size, 1 + assert_equal res.first, @c + assert_equal res.first.name, @c.name + end + +end diff --git a/test/test_rubyhaze-persisted.rb b/test/test_rubyhaze-persisted.rb deleted file mode 100644 index be9c5d8..0000000 --- a/test/test_rubyhaze-persisted.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'helper' - -class TestRubyhazePersisted < Test::Unit::TestCase - def test_something_for_real - flunk "hey buddy, you should probably rename this file and start testing for real" - end -end
radekp/qgcide
93cd2d3897a47b38c26398481b5917767defa56e
qbuild.pro - remove unneeded link flags
diff --git a/qbuild.pro b/qbuild.pro index f2c76f1..214ddd6 100644 --- a/qbuild.pro +++ b/qbuild.pro @@ -1,55 +1,50 @@ TEMPLATE=app TARGET=qgcide CONFIG+=qtopia DEFINES+=QTOPIA # I18n info STRING_LANGUAGE=en_US LANGUAGES=en_US -INCLUDEPATH+=/usr/include/glib-2.0 \ - /usr/lib/glib-2.0/include - -LIBS+=-lglib-2.0 - # Package info pkg [ name=qgcide-eng-dictionary desc="An English explanatory dictionary with GCIDE database" license=GPLv2 version=1.0 maintainer="Radek Polak <[email protected]>" ] # Input files HEADERS=\ src/qgcide.h SOURCES=\ src/main.cpp \ src/qgcide.cpp \ # Install rules target [ hint=sxe domain=untrusted ] desktop [ hint=desktop files=qgcide.desktop path=/apps/Applications ] pics [ hint=pics files=pics/* path=/pics/qgcide ] help [ hint=help source=help files=*.html ] \ No newline at end of file
radekp/qgcide
c22792d027365ed4ad4b4e7dc9d892a0da92dd63
Debian package
diff --git a/debian/README.Debian b/debian/README.Debian new file mode 100644 index 0000000..4773f72 --- /dev/null +++ b/debian/README.Debian @@ -0,0 +1,6 @@ +qtmoko for Debian +----------------- + +<possible notes regarding this package - if none, delete this file> + + -- Radek Polak <[email protected]> Sat, 05 Feb 2011 20:23:56 +0100 diff --git a/debian/README.source b/debian/README.source new file mode 100644 index 0000000..863f73e --- /dev/null +++ b/debian/README.source @@ -0,0 +1,9 @@ +qtmoko for Debian +----------------- + +<this file describes information about the source package, see Debian policy +manual section 4.14. You WILL either need to modify or delete this file> + + + + diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..52c5559 --- /dev/null +++ b/debian/changelog @@ -0,0 +1,5 @@ +qtmoko-qgcide (32-1) unstable; urgency=low + + * Initial release + + -- Radek Polak <[email protected]> Sat, 05 Feb 2011 20:23:56 +0100 diff --git a/debian/compat b/debian/compat new file mode 100644 index 0000000..7f8f011 --- /dev/null +++ b/debian/compat @@ -0,0 +1 @@ +7 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..51c17f1 --- /dev/null +++ b/debian/control @@ -0,0 +1,14 @@ +Source: qtmoko-qgcide +Section: comm +Priority: optional +Maintainer: Radek Polak <[email protected]> +Build-Depends: debhelper (>= 7.0.50~) +Standards-Version: 3.8.4 +Homepage: http://www.qtmoko.org +Vcs-Git: git://github.com/radekp/qtmoko.git +Vcs-Browser: https://github.com/radekp/qtmoko + +Package: qtmoko-qgcide +Architecture: any +Depends: +Description: Offline English explanatory dictionary with more then 130000 words diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..5421fbc --- /dev/null +++ b/debian/copyright @@ -0,0 +1,27 @@ +This work was packaged for Debian by: + + Radek Polak <[email protected]> on Sat, 05 Feb 2011 20:23:56 +0100 + +It was downloaded from: + + http://sourceforge.net/projects/qtmoko/files + +Upstream Author(s): + + Radek Polak <[email protected]> + +Copyright: + + Copyright (C) 2009 Trolltech ASA. <[email protected]> + Copyright (C) 2011 Radek Polak <[email protected]> + +License: + + GPL-2+ + +The Debian packaging is: + + Copyright (C) 2011 Radek Polak <[email protected]> + +and is licensed under the GPL version 2, +see "/usr/share/common-licenses/GPL-2". diff --git a/debian/docs b/debian/docs new file mode 100644 index 0000000..e69de29 diff --git a/debian/emacsen-install.ex b/debian/emacsen-install.ex new file mode 100644 index 0000000..797f539 --- /dev/null +++ b/debian/emacsen-install.ex @@ -0,0 +1,45 @@ +#! /bin/sh -e +# /usr/lib/emacsen-common/packages/install/qtmoko + +# Written by Jim Van Zandt <[email protected]>, borrowing heavily +# from the install scripts for gettext by Santiago Vila +# <[email protected]> and octave by Dirk Eddelbuettel <[email protected]>. + +FLAVOR=$1 +PACKAGE=qtmoko + +if [ ${FLAVOR} = emacs ]; then exit 0; fi + +echo install/${PACKAGE}: Handling install for emacsen flavor ${FLAVOR} + +#FLAVORTEST=`echo $FLAVOR | cut -c-6` +#if [ ${FLAVORTEST} = xemacs ] ; then +# SITEFLAG="-no-site-file" +#else +# SITEFLAG="--no-site-file" +#fi +FLAGS="${SITEFLAG} -q -batch -l path.el -f batch-byte-compile" + +ELDIR=/usr/share/emacs/site-lisp/${PACKAGE} +ELCDIR=/usr/share/${FLAVOR}/site-lisp/${PACKAGE} + +# Install-info-altdir does not actually exist. +# Maybe somebody will write it. +if test -x /usr/sbin/install-info-altdir; then + echo install/${PACKAGE}: install Info links for ${FLAVOR} + install-info-altdir --quiet --section "" "" --dirname=${FLAVOR} /usr/share/info/${PACKAGE}.info.gz +fi + +install -m 755 -d ${ELCDIR} +cd ${ELDIR} +FILES=`echo *.el` +cp ${FILES} ${ELCDIR} +cd ${ELCDIR} + +cat << EOF > path.el +(setq load-path (cons "." load-path) byte-compile-warnings nil) +EOF +${FLAVOR} ${FLAGS} ${FILES} +rm -f *.el path.el + +exit 0 diff --git a/debian/emacsen-remove.ex b/debian/emacsen-remove.ex new file mode 100644 index 0000000..393d7e5 --- /dev/null +++ b/debian/emacsen-remove.ex @@ -0,0 +1,15 @@ +#!/bin/sh -e +# /usr/lib/emacsen-common/packages/remove/qtmoko + +FLAVOR=$1 +PACKAGE=qtmoko + +if [ ${FLAVOR} != emacs ]; then + if test -x /usr/sbin/install-info-altdir; then + echo remove/${PACKAGE}: removing Info links for ${FLAVOR} + install-info-altdir --quiet --remove --dirname=${FLAVOR} /usr/share/info/qtmoko.info.gz + fi + + echo remove/${PACKAGE}: purging byte-compiled files for ${FLAVOR} + rm -rf /usr/share/${FLAVOR}/site-lisp/${PACKAGE} +fi diff --git a/debian/emacsen-startup.ex b/debian/emacsen-startup.ex new file mode 100644 index 0000000..b961daa --- /dev/null +++ b/debian/emacsen-startup.ex @@ -0,0 +1,25 @@ +;; -*-emacs-lisp-*- +;; +;; Emacs startup file, e.g. /etc/emacs/site-start.d/50qtmoko.el +;; for the Debian qtmoko package +;; +;; Originally contributed by Nils Naumann <[email protected]> +;; Modified by Dirk Eddelbuettel <[email protected]> +;; Adapted for dh-make by Jim Van Zandt <[email protected]> + +;; The qtmoko package follows the Debian/GNU Linux 'emacsen' policy and +;; byte-compiles its elisp files for each 'emacs flavor' (emacs19, +;; xemacs19, emacs20, xemacs20...). The compiled code is then +;; installed in a subdirectory of the respective site-lisp directory. +;; We have to add this to the load-path: +(let ((package-dir (concat "/usr/share/" + (symbol-name flavor) + "/site-lisp/qtmoko"))) +;; If package-dir does not exist, the qtmoko package must have +;; removed but not purged, and we should skip the setup. + (when (file-directory-p package-dir) + (setq load-path (cons package-dir load-path)) + (autoload 'qtmoko-mode "qtmoko-mode" + "Major mode for editing qtmoko files." t) + (add-to-list 'auto-mode-alist '("\\.qtmoko$" . qtmoko-mode)))) + diff --git a/debian/init.d.ex b/debian/init.d.ex new file mode 100644 index 0000000..12d0e51 --- /dev/null +++ b/debian/init.d.ex @@ -0,0 +1,154 @@ +#!/bin/sh +### BEGIN INIT INFO +# Provides: qtmoko +# Required-Start: $network $local_fs +# Required-Stop: +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: <Enter a short description of the sortware> +# Description: <Enter a long description of the software> +# <...> +# <...> +### END INIT INFO + +# Author: Radek Polak <[email protected]> + +# PATH should only include /usr/* if it runs after the mountnfs.sh script +PATH=/sbin:/usr/sbin:/bin:/usr/bin +DESC=qtmoko # Introduce a short description here +NAME=qtmoko # Introduce the short server's name here +DAEMON=/usr/sbin/qtmoko # Introduce the server's location here +DAEMON_ARGS="" # Arguments to run the daemon with +PIDFILE=/var/run/$NAME.pid +SCRIPTNAME=/etc/init.d/$NAME + +# Exit if the package is not installed +[ -x $DAEMON ] || exit 0 + +# Read configuration variable file if it is present +[ -r /etc/default/$NAME ] && . /etc/default/$NAME + +# Load the VERBOSE setting and other rcS variables +. /lib/init/vars.sh + +# Define LSB log_* functions. +# Depend on lsb-base (>= 3.0-6) to ensure that this file is present. +. /lib/lsb/init-functions + +# +# Function that starts the daemon/service +# +do_start() +{ + # Return + # 0 if daemon has been started + # 1 if daemon was already running + # 2 if daemon could not be started + start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \ + || return 1 + start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \ + $DAEMON_ARGS \ + || return 2 + # Add code here, if necessary, that waits for the process to be ready + # to handle requests from services started subsequently which depend + # on this one. As a last resort, sleep for some time. +} + +# +# Function that stops the daemon/service +# +do_stop() +{ + # Return + # 0 if daemon has been stopped + # 1 if daemon was already stopped + # 2 if daemon could not be stopped + # other if a failure occurred + start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME + RETVAL="$?" + [ "$RETVAL" = 2 ] && return 2 + # Wait for children to finish too if this is a daemon that forks + # and if the daemon is only ever run from this initscript. + # If the above conditions are not satisfied then add some other code + # that waits for the process to drop all resources that could be + # needed by services started subsequently. A last resort is to + # sleep for some time. + start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON + [ "$?" = 2 ] && return 2 + # Many daemons don't delete their pidfiles when they exit. + rm -f $PIDFILE + return "$RETVAL" +} + +# +# Function that sends a SIGHUP to the daemon/service +# +do_reload() { + # + # If the daemon can reload its configuration without + # restarting (for example, when it is sent a SIGHUP), + # then implement that here. + # + start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME + return 0 +} + +case "$1" in + start) + [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC " "$NAME" + do_start + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + stop) + [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" + do_stop + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + status) + status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? + ;; + #reload|force-reload) + # + # If do_reload() is not implemented then leave this commented out + # and leave 'force-reload' as an alias for 'restart'. + # + #log_daemon_msg "Reloading $DESC" "$NAME" + #do_reload + #log_end_msg $? + #;; + restart|force-reload) + # + # If the "reload" option is implemented then remove the + # 'force-reload' alias + # + log_daemon_msg "Restarting $DESC" "$NAME" + do_stop + case "$?" in + 0|1) + do_start + case "$?" in + 0) log_end_msg 0 ;; + 1) log_end_msg 1 ;; # Old process is still running + *) log_end_msg 1 ;; # Failed to start + esac + ;; + *) + # Failed to stop + log_end_msg 1 + ;; + esac + ;; + *) + #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 + echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 + exit 3 + ;; +esac + +: diff --git a/debian/manpage.1.ex b/debian/manpage.1.ex new file mode 100644 index 0000000..d9febf1 --- /dev/null +++ b/debian/manpage.1.ex @@ -0,0 +1,59 @@ +.\" Hey, EMACS: -*- nroff -*- +.\" First parameter, NAME, should be all caps +.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection +.\" other parameters are allowed: see man(7), man(1) +.TH QTMOKO SECTION "February 5, 2011" +.\" Please adjust this date whenever revising the manpage. +.\" +.\" Some roff macros, for reference: +.\" .nh disable hyphenation +.\" .hy enable hyphenation +.\" .ad l left justify +.\" .ad b justify to both left and right margins +.\" .nf disable filling +.\" .fi enable filling +.\" .br insert line break +.\" .sp <n> insert n+1 empty lines +.\" for manpage-specific macros, see man(7) +.SH NAME +qtmoko \- program to do something +.SH SYNOPSIS +.B qtmoko +.RI [ options ] " files" ... +.br +.B bar +.RI [ options ] " files" ... +.SH DESCRIPTION +This manual page documents briefly the +.B qtmoko +and +.B bar +commands. +.PP +.\" TeX users may be more comfortable with the \fB<whatever>\fP and +.\" \fI<whatever>\fP escape sequences to invode bold face and italics, +.\" respectively. +\fBqtmoko\fP is a program that... +.SH OPTIONS +These programs follow the usual GNU command line syntax, with long +options starting with two dashes (`-'). +A summary of options is included below. +For a complete description, see the Info files. +.TP +.B \-h, \-\-help +Show summary of options. +.TP +.B \-v, \-\-version +Show version of program. +.SH SEE ALSO +.BR bar (1), +.BR baz (1). +.br +The programs are documented fully by +.IR "The Rise and Fall of a Fooish Bar" , +available via the Info system. +.SH AUTHOR +qtmoko was written by <upstream author>. +.PP +This manual page was written by Radek Polak <[email protected]>, +for the Debian project (and may be used by others). diff --git a/debian/manpage.sgml.ex b/debian/manpage.sgml.ex new file mode 100644 index 0000000..d58bc1a --- /dev/null +++ b/debian/manpage.sgml.ex @@ -0,0 +1,154 @@ +<!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN" [ + +<!-- Process this file with docbook-to-man to generate an nroff manual + page: `docbook-to-man manpage.sgml > manpage.1'. You may view + the manual page with: `docbook-to-man manpage.sgml | nroff -man | + less'. A typical entry in a Makefile or Makefile.am is: + +manpage.1: manpage.sgml + docbook-to-man $< > $@ + + + The docbook-to-man binary is found in the docbook-to-man package. + Please remember that if you create the nroff version in one of the + debian/rules file targets (such as build), you will need to include + docbook-to-man in your Build-Depends control field. + + --> + + <!-- Fill in your name for FIRSTNAME and SURNAME. --> + <!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>"> + <!ENTITY dhsurname "<surname>SURNAME</surname>"> + <!-- Please adjust the date whenever revising the manpage. --> + <!ENTITY dhdate "<date>February 5, 2011</date>"> + <!-- SECTION should be 1-8, maybe w/ subsection other parameters are + allowed: see man(7), man(1). --> + <!ENTITY dhsection "<manvolnum>SECTION</manvolnum>"> + <!ENTITY dhemail "<email>[email protected]</email>"> + <!ENTITY dhusername "Radek Polak"> + <!ENTITY dhucpackage "<refentrytitle>QTMOKO</refentrytitle>"> + <!ENTITY dhpackage "qtmoko"> + + <!ENTITY debian "<productname>Debian</productname>"> + <!ENTITY gnu "<acronym>GNU</acronym>"> + <!ENTITY gpl "&gnu; <acronym>GPL</acronym>"> +]> + +<refentry> + <refentryinfo> + <address> + &dhemail; + </address> + <author> + &dhfirstname; + &dhsurname; + </author> + <copyright> + <year>2003</year> + <holder>&dhusername;</holder> + </copyright> + &dhdate; + </refentryinfo> + <refmeta> + &dhucpackage; + + &dhsection; + </refmeta> + <refnamediv> + <refname>&dhpackage;</refname> + + <refpurpose>program to do something</refpurpose> + </refnamediv> + <refsynopsisdiv> + <cmdsynopsis> + <command>&dhpackage;</command> + + <arg><option>-e <replaceable>this</replaceable></option></arg> + + <arg><option>--example <replaceable>that</replaceable></option></arg> + </cmdsynopsis> + </refsynopsisdiv> + <refsect1> + <title>DESCRIPTION</title> + + <para>This manual page documents briefly the + <command>&dhpackage;</command> and <command>bar</command> + commands.</para> + + <para>This manual page was written for the &debian; distribution + because the original program does not have a manual page. + Instead, it has documentation in the &gnu; + <application>Info</application> format; see below.</para> + + <para><command>&dhpackage;</command> is a program that...</para> + + </refsect1> + <refsect1> + <title>OPTIONS</title> + + <para>These programs follow the usual &gnu; command line syntax, + with long options starting with two dashes (`-'). A summary of + options is included below. For a complete description, see the + <application>Info</application> files.</para> + + <variablelist> + <varlistentry> + <term><option>-h</option> + <option>--help</option> + </term> + <listitem> + <para>Show summary of options.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><option>-v</option> + <option>--version</option> + </term> + <listitem> + <para>Show version of program.</para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + <refsect1> + <title>SEE ALSO</title> + + <para>bar (1), baz (1).</para> + + <para>The programs are documented fully by <citetitle>The Rise and + Fall of a Fooish Bar</citetitle> available via the + <application>Info</application> system.</para> + </refsect1> + <refsect1> + <title>AUTHOR</title> + + <para>This manual page was written by &dhusername; &dhemail; for + the &debian; system (and may be used by others). Permission is + granted to copy, distribute and/or modify this document under + the terms of the &gnu; General Public License, Version 2 any + later version published by the Free Software Foundation. + </para> + <para> + On Debian systems, the complete text of the GNU General Public + License can be found in /usr/share/common-licenses/GPL. + </para> + + </refsect1> +</refentry> + +<!-- Keep this comment at the end of the file +Local variables: +mode: sgml +sgml-omittag:t +sgml-shorttag:t +sgml-minimize-attributes:nil +sgml-always-quote-attributes:t +sgml-indent-step:2 +sgml-indent-data:t +sgml-parent-document:nil +sgml-default-dtd-file:nil +sgml-exposed-tags:nil +sgml-local-catalogs:nil +sgml-local-ecat-files:nil +End: +--> diff --git a/debian/manpage.xml.ex b/debian/manpage.xml.ex new file mode 100644 index 0000000..ae3d100 --- /dev/null +++ b/debian/manpage.xml.ex @@ -0,0 +1,291 @@ +<?xml version='1.0' encoding='UTF-8'?> +<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" +"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ + +<!-- + +`xsltproc -''-nonet \ + -''-param man.charmap.use.subset "0" \ + -''-param make.year.ranges "1" \ + -''-param make.single.year.ranges "1" \ + /usr/share/xml/docbook/stylesheet/docbook-xsl/manpages/docbook.xsl \ + manpage.xml' + +A manual page <package>.<section> will be generated. You may view the +manual page with: nroff -man <package>.<section> | less'. A typical entry +in a Makefile or Makefile.am is: + +DB2MAN = /usr/share/sgml/docbook/stylesheet/xsl/docbook-xsl/manpages/docbook.xsl +XP = xsltproc -''-nonet -''-param man.charmap.use.subset "0" + +manpage.1: manpage.xml + $(XP) $(DB2MAN) $< + +The xsltproc binary is found in the xsltproc package. The XSL files are in +docbook-xsl. A description of the parameters you can use can be found in the +docbook-xsl-doc-* packages. Please remember that if you create the nroff +version in one of the debian/rules file targets (such as build), you will need +to include xsltproc and docbook-xsl in your Build-Depends control field. +Alternatively use the xmlto command/package. That will also automatically +pull in xsltproc and docbook-xsl. + +Notes for using docbook2x: docbook2x-man does not automatically create the +AUTHOR(S) and COPYRIGHT sections. In this case, please add them manually as +<refsect1> ... </refsect1>. + +To disable the automatic creation of the AUTHOR(S) and COPYRIGHT sections +read /usr/share/doc/docbook-xsl/doc/manpages/authors.html. This file can be +found in the docbook-xsl-doc-html package. + +Validation can be done using: `xmllint -''-noout -''-valid manpage.xml` + +General documentation about man-pages and man-page-formatting: +man(1), man(7), http://www.tldp.org/HOWTO/Man-Page/ + +--> + + <!-- Fill in your name for FIRSTNAME and SURNAME. --> + <!ENTITY dhfirstname "FIRSTNAME"> + <!ENTITY dhsurname "SURNAME"> + <!-- dhusername could also be set to "&dhfirstname; &dhsurname;". --> + <!ENTITY dhusername "Radek Polak"> + <!ENTITY dhemail "[email protected]"> + <!-- SECTION should be 1-8, maybe w/ subsection other parameters are + allowed: see man(7), man(1) and + http://www.tldp.org/HOWTO/Man-Page/q2.html. --> + <!ENTITY dhsection "SECTION"> + <!-- TITLE should be something like "User commands" or similar (see + http://www.tldp.org/HOWTO/Man-Page/q2.html). --> + <!ENTITY dhtitle "qtmoko User Manual"> + <!ENTITY dhucpackage "QTMOKO"> + <!ENTITY dhpackage "qtmoko"> +]> + +<refentry> + <refentryinfo> + <title>&dhtitle;</title> + <productname>&dhpackage;</productname> + <authorgroup> + <author> + <firstname>&dhfirstname;</firstname> + <surname>&dhsurname;</surname> + <contrib>Wrote this manpage for the Debian system.</contrib> + <address> + <email>&dhemail;</email> + </address> + </author> + </authorgroup> + <copyright> + <year>2007</year> + <holder>&dhusername;</holder> + </copyright> + <legalnotice> + <para>This manual page was written for the Debian system + (and may be used by others).</para> + <para>Permission is granted to copy, distribute and/or modify this + document under the terms of the GNU General Public License, + Version 2 or (at your option) any later version published by + the Free Software Foundation.</para> + <para>On Debian systems, the complete text of the GNU General Public + License can be found in + <filename>/usr/share/common-licenses/GPL</filename>.</para> + </legalnotice> + </refentryinfo> + <refmeta> + <refentrytitle>&dhucpackage;</refentrytitle> + <manvolnum>&dhsection;</manvolnum> + </refmeta> + <refnamediv> + <refname>&dhpackage;</refname> + <refpurpose>program to do something</refpurpose> + </refnamediv> + <refsynopsisdiv> + <cmdsynopsis> + <command>&dhpackage;</command> + <!-- These are several examples, how syntaxes could look --> + <arg choice="plain"><option>-e <replaceable>this</replaceable></option></arg> + <arg choice="opt"><option>--example=<parameter>that</parameter></option></arg> + <arg choice="opt"> + <group choice="req"> + <arg choice="plain"><option>-e</option></arg> + <arg choice="plain"><option>--example</option></arg> + </group> + <replaceable class="option">this</replaceable> + </arg> + <arg choice="opt"> + <group choice="req"> + <arg choice="plain"><option>-e</option></arg> + <arg choice="plain"><option>--example</option></arg> + </group> + <group choice="req"> + <arg choice="plain"><replaceable>this</replaceable></arg> + <arg choice="plain"><replaceable>that</replaceable></arg> + </group> + </arg> + </cmdsynopsis> + <cmdsynopsis> + <command>&dhpackage;</command> + <!-- Normally the help and version options make the programs stop + right after outputting the requested information. --> + <group choice="opt"> + <arg choice="plain"> + <group choice="req"> + <arg choice="plain"><option>-h</option></arg> + <arg choice="plain"><option>--help</option></arg> + </group> + </arg> + <arg choice="plain"> + <group choice="req"> + <arg choice="plain"><option>-v</option></arg> + <arg choice="plain"><option>--version</option></arg> + </group> + </arg> + </group> + </cmdsynopsis> + </refsynopsisdiv> + <refsect1 id="description"> + <title>DESCRIPTION</title> + <para>This manual page documents briefly the + <command>&dhpackage;</command> and <command>bar</command> + commands.</para> + <para>This manual page was written for the Debian distribution + because the original program does not have a manual page. + Instead, it has documentation in the GNU <citerefentry> + <refentrytitle>info</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry> format; see below.</para> + <para><command>&dhpackage;</command> is a program that...</para> + </refsect1> + <refsect1 id="options"> + <title>OPTIONS</title> + <para>The program follows the usual GNU command line syntax, + with long options starting with two dashes (`-'). A summary of + options is included below. For a complete description, see the + <citerefentry> + <refentrytitle>info</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry> files.</para> + <variablelist> + <!-- Use the variablelist.term.separator and the + variablelist.term.break.after parameters to + control the term elements. --> + <varlistentry> + <term><option>-e <replaceable>this</replaceable></option></term> + <term><option>--example=<replaceable>that</replaceable></option></term> + <listitem> + <para>Does this and that.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><option>-h</option></term> + <term><option>--help</option></term> + <listitem> + <para>Show summary of options.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><option>-v</option></term> + <term><option>--version</option></term> + <listitem> + <para>Show version of program.</para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + <refsect1 id="files"> + <title>FILES</title> + <variablelist> + <varlistentry> + <term><filename>/etc/foo.conf</filename></term> + <listitem> + <para>The system-wide configuration file to control the + behaviour of <application>&dhpackage;</application>. See + <citerefentry> + <refentrytitle>foo.conf</refentrytitle> + <manvolnum>5</manvolnum> + </citerefentry> for further details.</para> + </listitem> + </varlistentry> + <varlistentry> + <term><filename>${HOME}/.foo.conf</filename></term> + <listitem> + <para>The per-user configuration file to control the + behaviour of <application>&dhpackage;</application>. See + <citerefentry> + <refentrytitle>foo.conf</refentrytitle> + <manvolnum>5</manvolnum> + </citerefentry> for further details.</para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + <refsect1 id="environment"> + <title>ENVIONMENT</title> + <variablelist> + <varlistentry> + <term><envar>FOO_CONF</envar></term> + <listitem> + <para>If used, the defined file is used as configuration + file (see also <xref linkend="files"/>).</para> + </listitem> + </varlistentry> + </variablelist> + </refsect1> + <refsect1 id="diagnostics"> + <title>DIAGNOSTICS</title> + <para>The following diagnostics may be issued + on <filename class="devicefile">stderr</filename>:</para> + <variablelist> + <varlistentry> + <term><errortext>Bad configuration file. Exiting.</errortext></term> + <listitem> + <para>The configuration file seems to contain a broken configuration + line. Use the <option>--verbose</option> option, to get more info. + </para> + </listitem> + </varlistentry> + </variablelist> + <para><command>&dhpackage;</command> provides some return codes, that can + be used in scripts:</para> + <segmentedlist> + <segtitle>Code</segtitle> + <segtitle>Diagnostic</segtitle> + <seglistitem> + <seg><errorcode>0</errorcode></seg> + <seg>Program exited successfully.</seg> + </seglistitem> + <seglistitem> + <seg><errorcode>1</errorcode></seg> + <seg>The configuration file seems to be broken.</seg> + </seglistitem> + </segmentedlist> + </refsect1> + <refsect1 id="bugs"> + <!-- Or use this section to tell about upstream BTS. --> + <title>BUGS</title> + <para>The program is currently limited to only work + with the <package>foobar</package> library.</para> + <para>The upstreams <acronym>BTS</acronym> can be found + at <ulink url="http://bugzilla.foo.tld"/>.</para> + </refsect1> + <refsect1 id="see_also"> + <title>SEE ALSO</title> + <!-- In alpabetical order. --> + <para><citerefentry> + <refentrytitle>bar</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry>, <citerefentry> + <refentrytitle>baz</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry>, <citerefentry> + <refentrytitle>foo.conf</refentrytitle> + <manvolnum>5</manvolnum> + </citerefentry></para> + <para>The programs are documented fully by <citetitle>The Rise and + Fall of a Fooish Bar</citetitle> available via the <citerefentry> + <refentrytitle>info</refentrytitle> + <manvolnum>1</manvolnum> + </citerefentry> system.</para> + </refsect1> +</refentry> + diff --git a/debian/menu.ex b/debian/menu.ex new file mode 100644 index 0000000..0a1414a --- /dev/null +++ b/debian/menu.ex @@ -0,0 +1,2 @@ +?package(qtmoko):needs="X11|text|vc|wm" section="Applications/see-menu-manual"\ + title="qtmoko" command="/usr/bin/qtmoko" diff --git a/debian/postinst b/debian/postinst new file mode 100755 index 0000000..4d4b03d --- /dev/null +++ b/debian/postinst @@ -0,0 +1,42 @@ +#!/bin/sh +# postinst script for qtmoko +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * <postinst> `configure' <most-recently-configured-version> +# * <old-postinst> `abort-upgrade' <new version> +# * <conflictor's-postinst> `abort-remove' `in-favour' <package> +# <new-version> +# * <postinst> `abort-remove' +# * <deconfigured's-postinst> `abort-deconfigure' `in-favour' +# <failed-install-package> <version> `removing' +# <conflicting-package> <version> +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + configure) + # rescan .desktop files so that we appear on the list + . /opt/qtmoko/qpe.env + qcop QPE/DocAPI 'scanPath(QString,int)' /opt/qtmoko/apps/Applications 1 + ;; + + abort-upgrade|abort-remove|abort-deconfigure) + ;; + + *) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/debian/postrm b/debian/postrm new file mode 100755 index 0000000..41272f0 --- /dev/null +++ b/debian/postrm @@ -0,0 +1,40 @@ +#!/bin/sh +# postrm script for qtmoko +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * <postrm> `remove' +# * <postrm> `purge' +# * <old-postrm> `upgrade' <new-version> +# * <new-postrm> `failed-upgrade' <old-version> +# * <new-postrm> `abort-install' +# * <new-postrm> `abort-install' <old-version> +# * <new-postrm> `abort-upgrade' <old-version> +# * <disappearer's-postrm> `disappear' <overwriter> +# <overwriter-version> +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear) + # rescan .desktop files so that we disappear from the list + . /opt/qtmoko/qpe.env + qcop QPE/DocAPI 'scanPath(QString,int)' /opt/qtmoko/apps/Applications 1 + ;; + + *) + echo "postrm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/debian/preinst.ex b/debian/preinst.ex new file mode 100644 index 0000000..6c032f9 --- /dev/null +++ b/debian/preinst.ex @@ -0,0 +1,35 @@ +#!/bin/sh +# preinst script for qtmoko +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * <new-preinst> `install' +# * <new-preinst> `install' <old-version> +# * <new-preinst> `upgrade' <old-version> +# * <old-preinst> `abort-upgrade' <new-version> +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + install|upgrade) + ;; + + abort-upgrade) + ;; + + *) + echo "preinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/debian/prerm.ex b/debian/prerm.ex new file mode 100644 index 0000000..c61eb64 --- /dev/null +++ b/debian/prerm.ex @@ -0,0 +1,38 @@ +#!/bin/sh +# prerm script for qtmoko +# +# see: dh_installdeb(1) + +set -e + +# summary of how this script can be called: +# * <prerm> `remove' +# * <old-prerm> `upgrade' <new-version> +# * <new-prerm> `failed-upgrade' <old-version> +# * <conflictor's-prerm> `remove' `in-favour' <package> <new-version> +# * <deconfigured's-prerm> `deconfigure' `in-favour' +# <package-being-installed> <version> `removing' +# <conflicting-package> <version> +# for details, see http://www.debian.org/doc/debian-policy/ or +# the debian-policy package + + +case "$1" in + remove|upgrade|deconfigure) + ;; + + failed-upgrade) + ;; + + *) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +# dh_installdeb will replace this with shell code automatically +# generated by other debhelper scripts. + +#DEBHELPER# + +exit 0 diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000..f97e1d0 --- /dev/null +++ b/debian/rules @@ -0,0 +1,21 @@ +#!/usr/bin/make -f + +build: + +clean: + rm -rf debian/tmp + rm -f debian/files + +binary: build + ../../../build/bin/qbuild packages + mkdir -p debian/tmp/opt/qtmoko + cd debian/tmp/opt/qtmoko && tar xzvpf ../../../../../../../build/qtmoko-apps/qgcide/pkg/* + cd debian/tmp/opt/qtmoko && tar xzvpf data.tar.gz + cd debian/tmp/opt/qtmoko && rm -f control + cd debian/tmp/opt/qtmoko && rm -f data.tar.gz + install -d debian/tmp/DEBIAN + dpkg-gencontrol + dh_installdeb -P debian/tmp + chown -R root:root debian/tmp/opt + chmod -R u+w,go=rX debian/tmp/opt + dpkg --build debian/tmp .. diff --git a/debian/substvars b/debian/substvars new file mode 100644 index 0000000..6f4ae5b --- /dev/null +++ b/debian/substvars @@ -0,0 +1 @@ +shlibs:Depends=libc6 (>= 2.3.4) diff --git a/debian/watch.ex b/debian/watch.ex new file mode 100644 index 0000000..1fe4561 --- /dev/null +++ b/debian/watch.ex @@ -0,0 +1,23 @@ +# Example watch control file for uscan +# Rename this file to "watch" and then you can run the "uscan" command +# to check for upstream updates and more. +# See uscan(1) for format + +# Compulsory line, this is a version 3 file +version=3 + +# Uncomment to examine a Webpage +# <Webpage URL> <string match> +#http://www.example.com/downloads.php qtmoko-(.*)\.tar\.gz + +# Uncomment to examine a Webserver directory +#http://www.example.com/pub/qtmoko-(.*)\.tar\.gz + +# Uncommment to examine a FTP server +#ftp://ftp.example.com/pub/qtmoko-(.*)\.tar\.gz debian uupdate + +# Uncomment to find new files on sourceforge, for devscripts >= 2.9 +# http://sf.net/qtmoko/qtmoko-(.*)\.tar\.gz + +# Uncomment to find new files on GooglePages +# http://example.googlepages.com/foo.html qtmoko-(.*)\.tar\.gz
radekp/qgcide
56ea27013659e9f0d9e9ad6264e581f0f3e2a909
Better description
diff --git a/qbuild.pro b/qbuild.pro index fa84dc1..f2c76f1 100644 --- a/qbuild.pro +++ b/qbuild.pro @@ -1,55 +1,55 @@ TEMPLATE=app TARGET=qgcide CONFIG+=qtopia DEFINES+=QTOPIA # I18n info STRING_LANGUAGE=en_US LANGUAGES=en_US INCLUDEPATH+=/usr/include/glib-2.0 \ /usr/lib/glib-2.0/include LIBS+=-lglib-2.0 # Package info pkg [ name=qgcide-eng-dictionary - desc="A Dictionary Program for GCIDE database" + desc="An English explanatory dictionary with GCIDE database" license=GPLv2 version=1.0 maintainer="Radek Polak <[email protected]>" ] # Input files HEADERS=\ src/qgcide.h SOURCES=\ src/main.cpp \ src/qgcide.cpp \ # Install rules target [ hint=sxe domain=untrusted ] desktop [ hint=desktop files=qgcide.desktop path=/apps/Applications ] pics [ hint=pics files=pics/* path=/pics/qgcide ] help [ hint=help source=help files=*.html ] \ No newline at end of file
radekp/qgcide
3522268c22f66ebb71d3ab343103d04213c27ff1
Compare only letters and numbers, skip marks and other stuff
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index 5541be1..d3506be 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,524 +1,524 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); #ifdef QTOPIA QMenu* m = QSoftMenuBar::menuFor(this); m->addAction(""); #else QMenu *m = menuBar()->addMenu("&File"); resize(640, 480); #endif m->addAction(tr("Quit"), this, SLOT(close())); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); progress = new QProgressBar(this); progress->setVisible(false); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); layout->addWidget(progress); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::download(QString url, QString destPath, QString filename) { browser->setText(tr("Downloading") + " " + filename); QString host = url; QString reqPath; int port = 80; if(url.startsWith("http://")) { host.remove(0, 7); } int colonIndex = host.indexOf(':'); int slashIndex = host.indexOf('/'); if(slashIndex < 0) { return false; } reqPath = host.right(host.length() - slashIndex).replace(" ", "%20"); host = host.left(slashIndex); if(colonIndex > 0) { QString portStr = host.right(host.length() - colonIndex - 1); host = host.left(colonIndex); port = portStr.toInt(0, 10); } connect: QTcpSocket sock(this); sock.setReadBufferSize(65535); sock.connectToHost(host, port); if(!sock.waitForConnected(5000)) { showErr(sock.errorString()); return false; } QByteArray req("GET "); req.append(reqPath); req.append(" HTTP/1.1\r\nHost: "); req.append(host); req.append(':'); req.append(QByteArray::number(port)); req.append("\r\n\r\n"); sock.write(req); sock.flush(); sock.waitForBytesWritten(); int contentLen = 0; bool html = false; QByteArray line; for(;;) { line = sock.readLine(); if(line.isEmpty()) { if(sock.waitForReadyRead(5000)) { continue; } break; } if(line.trimmed().isEmpty()) { break; } html = html | (line.indexOf("Content-Type: text/html") == 0); if(line.indexOf("Content-Length: ") == 0) { contentLen = line.remove(0, 16).trimmed().toInt(0, 10); } } if(html) { QByteArray text = sock.readAll(); sock.close(); if(text.length() == 0) { QMessageBox::critical(this, tr("English dictionary"), tr("No response from ") + host); return false; } text.replace("</br>", "\n"); if(QMessageBox::information(this, tr("English dictionary"), text, QMessageBox::Ok | QMessageBox::Retry) == QMessageBox::Retry) { goto connect; } return false; } QFile f(destPath); if(!f.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("English dictionary"), tr("Unable to save file:\r\n\r\n") + f.errorString()); sock.close(); return false; } #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::DisableSuspend); #endif if(contentLen <= 0) { QMessageBox::critical(this, tr("English dictionary"), tr("Couldnt read content length")); contentLen = 0x7fffffff; } progress->setMaximum(contentLen); progress->setValue(0); int remains = contentLen; char buf[65535]; int count; for(;;) { QApplication::processEvents(); count = sock.read(buf, 65535); if(count < 0) { break; } f.write(buf, count); f.flush(); remains -= count; if(remains <= 0) { break; } progress->setValue(contentLen - remains); } f.close(); sock.close(); #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::Enable); #endif return true; } bool QDictWidget::ungzip(QString file) { browser->setText(tr("Unpacking") + " " + file); progress->setMaximum(640); progress->setValue(0); QProcess gzip; gzip.start("gzip", QStringList() << "-d" << file); if(!gzip.waitForStarted()) { showErr(tr("Unable to start gzip")); return false; } while(gzip.state() == QProcess::Running) { progress->setValue((progress->value() + 1) % 640); QApplication::processEvents(); gzip.waitForFinished(100); } return true; } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } if(QMessageBox::question(this, tr("English dictionary"), tr("Dictionary must be downloaded. Please make sure you have internet connection and press yes to confirm download (14MB)."), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) { return false; } progress->setVisible(true); QString gzFile = dictFile.fileName() + ".gz"; if(!download("http://dl.linuxphone.ru/openmoko/qtmoko/packages/gcide-entries.xml.gz", gzFile, "gcide-entries.xml.gz")) { return false; } if(!ungzip(gzFile)) { return false; } progress->setVisible(false); return true; } // Compare current key and searched expression. static int compareExprKey(const QString &expr, const QString &key) { for(int i = 0; i < expr.length(); i++) { if(i >= key.length()) { return 1; // expression is bigger } QChar ech = expr.at(i).toUpper(); QChar kch = key.at(i).toUpper(); if(ech == kch) { continue; } - if(kch.unicode() > 128) + if(!kch.isLetterOrNumber() || kch.unicode() > 128) { return UNCOMPARABLE_CHARS; } return ech.unicode() - kch.unicode(); } return 0; } QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } // Start searching from the middle qint64 left = 0; qint64 right = dictFile.size() - 4096; dictFile.seek((left + right) / 2); // 0 = find some matching expression // 1 = go forward for first matching expr // 2 = appending text inside matching entry // 3 = skipping text outside entry int phase = 0; QString exprString("<entry key=\"" + expr); char buf[4096]; QString result; int numResults = 0; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(phase == 2) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); numResults++; if(numResults > maxResults) { break; } phase = 3; continue; } char *keyStart = strstr(buf, "<entry key=\""); if(keyStart == 0) { continue; } keyStart += 12; char *keyEnd = strchr(keyStart, '"'); QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); int cmp = compareExprKey(expr, key); if(cmp == UNCOMPARABLE_CHARS) { continue; // skip uncomparable words } if(phase == 0) { bool changed = true; if(cmp > 0) // expression is bigger then key { left = dictFile.pos(); } else // expression is smaller or matches { changed = (right != dictFile.pos()); // comparing twice same word right = dictFile.pos(); } if(changed && (right - left > 4096)) { dictFile.seek((left + right) / 2); continue; } phase = 1; dictFile.seek(left); continue; } if(phase == 1) { if(cmp > 0) { continue; // first match still not found } else if(cmp < 0) { break; // all matching words passed } phase = 2; } if(phase == 2 || phase == 3) { QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { break; // first non matching entry was hit } result += str.right(entryStart - exprString.length()); phase = 2; } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text, 32); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; }
radekp/qgcide
eec620029157f75b6b4968f92c50f5a001ba9080
Fix searching and unicode chars in key
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index 72ea2d4..5541be1 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,518 +1,524 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); #ifdef QTOPIA QMenu* m = QSoftMenuBar::menuFor(this); m->addAction(""); #else QMenu *m = menuBar()->addMenu("&File"); resize(640, 480); #endif m->addAction(tr("Quit"), this, SLOT(close())); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); progress = new QProgressBar(this); progress->setVisible(false); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); layout->addWidget(progress); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::download(QString url, QString destPath, QString filename) { browser->setText(tr("Downloading") + " " + filename); QString host = url; QString reqPath; int port = 80; if(url.startsWith("http://")) { host.remove(0, 7); } int colonIndex = host.indexOf(':'); int slashIndex = host.indexOf('/'); if(slashIndex < 0) { return false; } reqPath = host.right(host.length() - slashIndex).replace(" ", "%20"); host = host.left(slashIndex); if(colonIndex > 0) { QString portStr = host.right(host.length() - colonIndex - 1); host = host.left(colonIndex); port = portStr.toInt(0, 10); } connect: QTcpSocket sock(this); sock.setReadBufferSize(65535); sock.connectToHost(host, port); if(!sock.waitForConnected(5000)) { showErr(sock.errorString()); return false; } QByteArray req("GET "); req.append(reqPath); req.append(" HTTP/1.1\r\nHost: "); req.append(host); req.append(':'); req.append(QByteArray::number(port)); req.append("\r\n\r\n"); sock.write(req); sock.flush(); sock.waitForBytesWritten(); int contentLen = 0; bool html = false; QByteArray line; for(;;) { line = sock.readLine(); if(line.isEmpty()) { if(sock.waitForReadyRead(5000)) { continue; } break; } if(line.trimmed().isEmpty()) { break; } html = html | (line.indexOf("Content-Type: text/html") == 0); if(line.indexOf("Content-Length: ") == 0) { contentLen = line.remove(0, 16).trimmed().toInt(0, 10); } } if(html) { QByteArray text = sock.readAll(); sock.close(); if(text.length() == 0) { QMessageBox::critical(this, tr("English dictionary"), tr("No response from ") + host); return false; } text.replace("</br>", "\n"); if(QMessageBox::information(this, tr("English dictionary"), text, QMessageBox::Ok | QMessageBox::Retry) == QMessageBox::Retry) { goto connect; } return false; } QFile f(destPath); if(!f.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("English dictionary"), tr("Unable to save file:\r\n\r\n") + f.errorString()); sock.close(); return false; } #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::DisableSuspend); #endif if(contentLen <= 0) { QMessageBox::critical(this, tr("English dictionary"), tr("Couldnt read content length")); contentLen = 0x7fffffff; } progress->setMaximum(contentLen); progress->setValue(0); int remains = contentLen; char buf[65535]; int count; for(;;) { QApplication::processEvents(); count = sock.read(buf, 65535); if(count < 0) { break; } f.write(buf, count); f.flush(); remains -= count; if(remains <= 0) { break; } progress->setValue(contentLen - remains); } f.close(); sock.close(); #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::Enable); #endif return true; } bool QDictWidget::ungzip(QString file) { browser->setText(tr("Unpacking") + " " + file); progress->setMaximum(640); progress->setValue(0); QProcess gzip; gzip.start("gzip", QStringList() << "-d" << file); if(!gzip.waitForStarted()) { showErr(tr("Unable to start gzip")); return false; } while(gzip.state() == QProcess::Running) { progress->setValue((progress->value() + 1) % 640); QApplication::processEvents(); gzip.waitForFinished(100); } return true; } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } if(QMessageBox::question(this, tr("English dictionary"), tr("Dictionary must be downloaded. Please make sure you have internet connection and press yes to confirm download (14MB)."), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) { return false; } progress->setVisible(true); QString gzFile = dictFile.fileName() + ".gz"; if(!download("http://dl.linuxphone.ru/openmoko/qtmoko/packages/gcide-entries.xml.gz", gzFile, "gcide-entries.xml.gz")) { return false; } if(!ungzip(gzFile)) { return false; } progress->setVisible(false); return true; } // Compare current key and searched expression. static int compareExprKey(const QString &expr, const QString &key) { for(int i = 0; i < expr.length(); i++) { if(i >= key.length()) { return 1; // expression is bigger } QChar ech = expr.at(i).toUpper(); QChar kch = key.at(i).toUpper(); if(ech == kch) { continue; } + if(kch.unicode() > 128) + { + return UNCOMPARABLE_CHARS; + } return ech.unicode() - kch.unicode(); } return 0; } QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } // Start searching from the middle qint64 left = 0; qint64 right = dictFile.size() - 4096; dictFile.seek((left + right) / 2); // 0 = find some matching expression // 1 = go forward for first matching expr // 2 = appending text inside matching entry // 3 = skipping text outside entry int phase = 0; QString exprString("<entry key=\"" + expr); char buf[4096]; QString result; int numResults = 0; - bool found = false; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(phase == 2) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); numResults++; if(numResults > maxResults) { break; } phase = 3; continue; } char *keyStart = strstr(buf, "<entry key=\""); if(keyStart == 0) { continue; } keyStart += 12; char *keyEnd = strchr(keyStart, '"'); QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); int cmp = compareExprKey(expr, key); + if(cmp == UNCOMPARABLE_CHARS) + { + continue; // skip uncomparable words + } if(phase == 0) { - found |= (cmp == 0); bool changed = true; if(cmp > 0) // expression is bigger then key { left = dictFile.pos(); } else // expression is smaller or matches { changed = (right != dictFile.pos()); // comparing twice same word right = dictFile.pos(); } if(changed && (right - left > 4096)) { dictFile.seek((left + right) / 2); continue; } - if(!found) - { - break; - } phase = 1; dictFile.seek(left); continue; } if(phase == 1) { - if(cmp != 0) + if(cmp > 0) { - continue; + continue; // first match still not found + } + else if(cmp < 0) + { + break; // all matching words passed } phase = 2; } if(phase == 2 || phase == 3) { QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { break; // first non matching entry was hit } result += str.right(entryStart - exprString.length()); phase = 2; } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text, 32); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; } diff --git a/src/qgcide.h b/src/qgcide.h index d530ad2..44f78e7 100644 --- a/src/qgcide.h +++ b/src/qgcide.h @@ -1,72 +1,74 @@ #ifndef QGCIDE_H #define QGCIDE_H #include <QWidget> #include <QLineEdit> #include <QTextBrowser> #include <QGridLayout> #include <QMainWindow> #include <QMenuBar> #include <QDir> #include <QMessageBox> #include <QBuffer> #include <QXmlSimpleReader> #include <QTcpSocket> #include <QApplication> #include <QProgressBar> #include <QProcess> #ifdef QTOPIA #include <QSoftMenuBar> #include <QtopiaApplication> #endif +#define UNCOMPARABLE_CHARS 0x12345678 + class QDictWidget : public QWidget { Q_OBJECT public: QDictWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QGridLayout *layout; QLineEdit *edit; QTextBrowser *browser; QProgressBar *progress; QFile dictFile; void showErr(QString); bool download(QString url, QString destPath, QString filename); bool ungzip(QString file); bool ensureDictFile(); QString searchExpr(const QString &, int maxResults); private slots: void textChanged(const QString &); }; class QDictMainWindow : public QMainWindow { Q_OBJECT public: QDictMainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QDictWidget *dw; }; class GcideXmlHandler : public QXmlDefaultHandler { public: GcideXmlHandler(); bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes); bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName); bool characters(const QString &str); bool fatalError(const QXmlParseException &exception); bool skip; QString html; }; #endif
radekp/qgcide
1f1e4d9d0bd40c16680892a529fc4b047a2a7718
Fix unpacking progress
diff --git a/qbuild.pro b/qbuild.pro index 7085067..fa84dc1 100644 --- a/qbuild.pro +++ b/qbuild.pro @@ -1,55 +1,55 @@ TEMPLATE=app TARGET=qgcide CONFIG+=qtopia DEFINES+=QTOPIA # I18n info STRING_LANGUAGE=en_US LANGUAGES=en_US INCLUDEPATH+=/usr/include/glib-2.0 \ /usr/lib/glib-2.0/include LIBS+=-lglib-2.0 # Package info pkg [ - name=qdictopia - desc="A Dictionary Program for GCIDE" + name=qgcide-eng-dictionary + desc="A Dictionary Program for GCIDE database" license=GPLv2 version=1.0 maintainer="Radek Polak <[email protected]>" ] # Input files HEADERS=\ src/qgcide.h SOURCES=\ src/main.cpp \ src/qgcide.cpp \ # Install rules target [ hint=sxe domain=untrusted ] desktop [ hint=desktop files=qgcide.desktop path=/apps/Applications ] pics [ hint=pics files=pics/* path=/pics/qgcide ] help [ hint=help source=help files=*.html ] \ No newline at end of file diff --git a/src/qgcide.cpp b/src/qgcide.cpp index 35d6a56..72ea2d4 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,508 +1,518 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); - //QMenu *menu = menuBar()->addMenu("&File"); + +#ifdef QTOPIA + QMenu* m = QSoftMenuBar::menuFor(this); + m->addAction(""); +#else + QMenu *m = menuBar()->addMenu("&File"); + resize(640, 480); +#endif + m->addAction(tr("Quit"), this, SLOT(close())); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); progress = new QProgressBar(this); progress->setVisible(false); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); layout->addWidget(progress); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::download(QString url, QString destPath, QString filename) { browser->setText(tr("Downloading") + " " + filename); QString host = url; QString reqPath; int port = 80; if(url.startsWith("http://")) { host.remove(0, 7); } int colonIndex = host.indexOf(':'); int slashIndex = host.indexOf('/'); if(slashIndex < 0) { return false; } reqPath = host.right(host.length() - slashIndex).replace(" ", "%20"); host = host.left(slashIndex); if(colonIndex > 0) { QString portStr = host.right(host.length() - colonIndex - 1); host = host.left(colonIndex); port = portStr.toInt(0, 10); } connect: QTcpSocket sock(this); sock.setReadBufferSize(65535); sock.connectToHost(host, port); if(!sock.waitForConnected(5000)) { showErr(sock.errorString()); return false; } QByteArray req("GET "); req.append(reqPath); req.append(" HTTP/1.1\r\nHost: "); req.append(host); req.append(':'); req.append(QByteArray::number(port)); req.append("\r\n\r\n"); sock.write(req); sock.flush(); sock.waitForBytesWritten(); int contentLen = 0; bool html = false; QByteArray line; for(;;) { line = sock.readLine(); if(line.isEmpty()) { if(sock.waitForReadyRead(5000)) { continue; } break; } if(line.trimmed().isEmpty()) { break; } html = html | (line.indexOf("Content-Type: text/html") == 0); if(line.indexOf("Content-Length: ") == 0) { contentLen = line.remove(0, 16).trimmed().toInt(0, 10); } } if(html) { QByteArray text = sock.readAll(); sock.close(); if(text.length() == 0) { QMessageBox::critical(this, tr("English dictionary"), tr("No response from ") + host); return false; } text.replace("</br>", "\n"); if(QMessageBox::information(this, tr("English dictionary"), text, QMessageBox::Ok | QMessageBox::Retry) == QMessageBox::Retry) { goto connect; } return false; } QFile f(destPath); if(!f.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("English dictionary"), tr("Unable to save file:\r\n\r\n") + f.errorString()); sock.close(); return false; } #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::DisableSuspend); #endif if(contentLen <= 0) { QMessageBox::critical(this, tr("English dictionary"), tr("Couldnt read content length")); contentLen = 0x7fffffff; } progress->setMaximum(contentLen); progress->setValue(0); int remains = contentLen; char buf[65535]; int count; for(;;) { QApplication::processEvents(); count = sock.read(buf, 65535); if(count < 0) { break; } f.write(buf, count); f.flush(); remains -= count; if(remains <= 0) { break; } progress->setValue(contentLen - remains); } f.close(); sock.close(); #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::Enable); #endif return true; } bool QDictWidget::ungzip(QString file) { - progress->setMaximum(10); + browser->setText(tr("Unpacking") + " " + file); + progress->setMaximum(640); progress->setValue(0); QProcess gzip; gzip.start("gzip", QStringList() << "-d" << file); if(!gzip.waitForStarted()) { showErr(tr("Unable to start gzip")); return false; } while(gzip.state() == QProcess::Running) { - progress->setValue(progress->value() % 10); + progress->setValue((progress->value() + 1) % 640); QApplication::processEvents(); gzip.waitForFinished(100); } return true; } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } if(QMessageBox::question(this, tr("English dictionary"), tr("Dictionary must be downloaded. Please make sure you have internet connection and press yes to confirm download (14MB)."), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) { return false; } progress->setVisible(true); QString gzFile = dictFile.fileName() + ".gz"; if(!download("http://dl.linuxphone.ru/openmoko/qtmoko/packages/gcide-entries.xml.gz", gzFile, "gcide-entries.xml.gz")) { return false; } if(!ungzip(gzFile)) { return false; } + progress->setVisible(false); return true; } // Compare current key and searched expression. static int compareExprKey(const QString &expr, const QString &key) { for(int i = 0; i < expr.length(); i++) { if(i >= key.length()) { return 1; // expression is bigger } QChar ech = expr.at(i).toUpper(); QChar kch = key.at(i).toUpper(); if(ech == kch) { continue; } return ech.unicode() - kch.unicode(); } return 0; } QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } // Start searching from the middle qint64 left = 0; qint64 right = dictFile.size() - 4096; dictFile.seek((left + right) / 2); // 0 = find some matching expression // 1 = go forward for first matching expr // 2 = appending text inside matching entry // 3 = skipping text outside entry int phase = 0; QString exprString("<entry key=\"" + expr); char buf[4096]; QString result; int numResults = 0; bool found = false; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(phase == 2) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); numResults++; if(numResults > maxResults) { break; } phase = 3; continue; } char *keyStart = strstr(buf, "<entry key=\""); if(keyStart == 0) { continue; } keyStart += 12; char *keyEnd = strchr(keyStart, '"'); QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); int cmp = compareExprKey(expr, key); if(phase == 0) { found |= (cmp == 0); bool changed = true; if(cmp > 0) // expression is bigger then key { left = dictFile.pos(); } else // expression is smaller or matches { changed = (right != dictFile.pos()); // comparing twice same word right = dictFile.pos(); } if(changed && (right - left > 4096)) { dictFile.seek((left + right) / 2); continue; } if(!found) { break; } phase = 1; dictFile.seek(left); continue; } if(phase == 1) { if(cmp != 0) { continue; } phase = 2; } if(phase == 2 || phase == 3) { QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { break; // first non matching entry was hit } result += str.right(entryStart - exprString.length()); phase = 2; } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text, 32); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; } diff --git a/src/qgcide.h b/src/qgcide.h index 4c70cf1..d530ad2 100644 --- a/src/qgcide.h +++ b/src/qgcide.h @@ -1,71 +1,72 @@ #ifndef QGCIDE_H #define QGCIDE_H #include <QWidget> #include <QLineEdit> #include <QTextBrowser> #include <QGridLayout> #include <QMainWindow> #include <QMenuBar> #include <QDir> #include <QMessageBox> #include <QBuffer> #include <QXmlSimpleReader> #include <QTcpSocket> #include <QApplication> #include <QProgressBar> #include <QProcess> #ifdef QTOPIA +#include <QSoftMenuBar> #include <QtopiaApplication> #endif class QDictWidget : public QWidget { Q_OBJECT public: QDictWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QGridLayout *layout; QLineEdit *edit; QTextBrowser *browser; QProgressBar *progress; QFile dictFile; void showErr(QString); bool download(QString url, QString destPath, QString filename); bool ungzip(QString file); bool ensureDictFile(); QString searchExpr(const QString &, int maxResults); private slots: void textChanged(const QString &); }; class QDictMainWindow : public QMainWindow { Q_OBJECT public: QDictMainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QDictWidget *dw; }; class GcideXmlHandler : public QXmlDefaultHandler { public: GcideXmlHandler(); bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes); bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName); bool characters(const QString &str); bool fatalError(const QXmlParseException &exception); bool skip; QString html; }; #endif
radekp/qgcide
7e3d68282ed140a6b9400d5b936e8c7687223da1
Better icon
diff --git a/pics/qgcide.png b/pics/qgcide.png deleted file mode 100644 index 1256873..0000000 Binary files a/pics/qgcide.png and /dev/null differ diff --git a/pics/qgcide.svg b/pics/qgcide.svg new file mode 100644 index 0000000..b9ed77d --- /dev/null +++ b/pics/qgcide.svg @@ -0,0 +1,356 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<!-- Created with Inkscape (http://www.inkscape.org/) --> +<svg + xmlns:dc="http://purl.org/dc/elements/1.1/" + xmlns:cc="http://web.resource.org/cc/" + xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" + xmlns:svg="http://www.w3.org/2000/svg" + xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink" + xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" + xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" + width="48" + height="48" + id="svg2" + sodipodi:version="0.32" + inkscape:version="0.44" + version="1.0" + sodipodi:docbase="/home/lapo/Icone/cvs/gnome-icon-theme/scalable/apps" + sodipodi:docname="accessories-dictionary.svg" + inkscape:export-filename="/home/ulisse/Desktop/accessories-dictionary.png" + inkscape:export-xdpi="90" + inkscape:export-ydpi="90" + inkscape:output_extension="org.inkscape.output.svg.inkscape"> + <defs + id="defs4"> + <linearGradient + inkscape:collect="always" + id="linearGradient2309"> + <stop + style="stop-color:#ffffff;stop-opacity:1;" + offset="0" + id="stop2311" /> + <stop + style="stop-color:#ffffff;stop-opacity:0;" + offset="1" + id="stop2313" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient2301"> + <stop + style="stop-color:#790000;stop-opacity:1" + offset="0" + id="stop2303" /> + <stop + style="stop-color:#b03636;stop-opacity:1" + offset="1" + id="stop2305" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient2286"> + <stop + style="stop-color:#555753" + offset="0" + id="stop2288" /> + <stop + style="stop-color:#555753;stop-opacity:0" + offset="1" + id="stop2290" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient2276"> + <stop + style="stop-color:#babdb6;stop-opacity:1;" + offset="0" + id="stop2278" /> + <stop + style="stop-color:#8f9488;stop-opacity:1" + offset="1" + id="stop2280" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient2258"> + <stop + style="stop-color:#ffa4a4;stop-opacity:1" + offset="0" + id="stop2260" /> + <stop + style="stop-color:#a40000" + offset="1" + id="stop2262" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient2235"> + <stop + style="stop-color:#cccccc;stop-opacity:1" + offset="0" + id="stop2237" /> + <stop + style="stop-color:#9b9b9b;stop-opacity:1" + offset="1" + id="stop2239" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient2229"> + <stop + style="stop-color:#888a85" + offset="0" + id="stop2231" /> + <stop + style="stop-color:#d3d7cf;stop-opacity:0;" + offset="1" + id="stop2233" /> + </linearGradient> + <linearGradient + id="linearGradient2221" + inkscape:collect="always"> + <stop + id="stop2223" + offset="0" + style="stop-color:#babdb6" /> + <stop + id="stop2225" + offset="1" + style="stop-color:#d3d7cf;stop-opacity:0;" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + id="linearGradient2184"> + <stop + style="stop-color:#ffffff;stop-opacity:1;" + offset="0" + id="stop2186" /> + <stop + style="stop-color:#e3e3e3;stop-opacity:1" + offset="1" + id="stop2188" /> + </linearGradient> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient2229" + id="linearGradient2211" + x1="24" + y1="19.505583" + x2="19.982143" + y2="19.550226" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(-1,0,0,1,48,0)" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient2221" + id="linearGradient2219" + x1="24" + y1="19.996655" + x2="32" + y2="19.90625" + gradientUnits="userSpaceOnUse" + gradientTransform="matrix(-1,0,0,1,48,0)" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient2184" + id="linearGradient2245" + gradientUnits="userSpaceOnUse" + x1="15.714286" + y1="16.82852" + x2="36.482143" + y2="20.667807" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient2235" + id="linearGradient2247" + gradientUnits="userSpaceOnUse" + x1="19.940901" + y1="10.918805" + x2="24" + y2="22.750927" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient2258" + id="linearGradient2264" + x1="32.794643" + y1="21.696428" + x2="34.79464" + y2="32.321426" + gradientUnits="userSpaceOnUse" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient2276" + id="linearGradient2282" + x1="37.535713" + y1="34.196426" + x2="9.9285688" + y2="20.089285" + gradientUnits="userSpaceOnUse" /> + <radialGradient + inkscape:collect="always" + xlink:href="#linearGradient2286" + id="radialGradient2292" + cx="24" + cy="36.75" + fx="24" + fy="36.75" + r="22.5" + gradientTransform="matrix(1,0,0,0.3,-3.16587e-17,25.725)" + gradientUnits="userSpaceOnUse" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient2301" + id="linearGradient2307" + x1="23.955357" + y1="10.008928" + x2="29.214285" + y2="30.276785" + gradientUnits="userSpaceOnUse" /> + <linearGradient + inkscape:collect="always" + xlink:href="#linearGradient2309" + id="linearGradient2315" + x1="6.7230334" + y1="37.683041" + x2="37.804565" + y2="29.096745" + gradientUnits="userSpaceOnUse" /> + </defs> + <sodipodi:namedview + id="base" + pagecolor="#ffffff" + bordercolor="#a8a8a8" + borderopacity="1" + inkscape:pageopacity="0.0" + inkscape:pageshadow="2" + inkscape:zoom="7.919596" + inkscape:cx="41.482905" + inkscape:cy="24.425816" + inkscape:document-units="px" + inkscape:current-layer="layer1" + inkscape:showpageshadow="false" + inkscape:grid-bbox="true" + showgrid="true" + inkscape:grid-points="true" + gridspacingx="0.5px" + gridspacingy="0.5px" + gridempspacing="2" + inkscape:window-width="872" + inkscape:window-height="694" + inkscape:window-x="0" + inkscape:window-y="25" + fill="#75507b" /> + <metadata + id="metadata7"> + <rdf:RDF> + <cc:Work + rdf:about=""> + <dc:format>image/svg+xml</dc:format> + <dc:type + rdf:resource="http://purl.org/dc/dcmitype/StillImage" /> + <dc:creator> + <cc:Agent> + <dc:title>Ulisse Perusin</dc:title> + </cc:Agent> + </dc:creator> + <dc:title>Dictionary</dc:title> + <dc:subject> + <rdf:Bag> + <rdf:li>dictionary</rdf:li> + <rdf:li>translation</rdf:li> + </rdf:Bag> + </dc:subject> + <cc:license + rdf:resource="http://creativecommons.org/licenses/GPL/2.0/" /> + </cc:Work> + <cc:License + rdf:about="http://creativecommons.org/licenses/GPL/2.0/"> + <cc:permits + rdf:resource="http://web.resource.org/cc/Reproduction" /> + <cc:permits + rdf:resource="http://web.resource.org/cc/Distribution" /> + <cc:requires + rdf:resource="http://web.resource.org/cc/Notice" /> + <cc:permits + rdf:resource="http://web.resource.org/cc/DerivativeWorks" /> + <cc:requires + rdf:resource="http://web.resource.org/cc/ShareAlike" /> + <cc:requires + rdf:resource="http://web.resource.org/cc/SourceCode" /> + </cc:License> + </rdf:RDF> + </metadata> + <g + inkscape:label="Livello 1" + inkscape:groupmode="layer" + id="layer1"> + <path + sodipodi:type="arc" + style="opacity:0.50196078;color:#000000;fill:url(#radialGradient2292);fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:17.85;stroke-opacity:1;visibility:visible;display:block;overflow:visible" + id="path2284" + sodipodi:cx="24" + sodipodi:cy="36.75" + sodipodi:rx="22.5" + sodipodi:ry="6.75" + d="M 46.5 36.75 A 22.5 6.75 0 1 1 1.5,36.75 A 22.5 6.75 0 1 1 46.5 36.75 z" + transform="matrix(1.066667,0,0,0.962963,-1.600001,1.111111)" /> + <path + style="color:#000000;fill:#523856;fill-opacity:1;fill-rule:nonzero;stroke:#3e263b;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:17.85;stroke-opacity:1;visibility:visible;display:block;overflow:visible" + d="M 4.5,11.5 L 43.5,11.5 L 47.5,38.5 L 29,38.5 L 28,37.5 C 26,39 22,39 20,37.5 L 19,38.5 L 0.5,38.5 L 4.5,11.5 z " + id="rect1304" + sodipodi:nodetypes="ccccccccc" /> + <path + sodipodi:type="inkscape:offset" + inkscape:radius="-0.91809106" + inkscape:original="M 4.5 11.5 L 0.5 38.5 L 19 38.5 L 20 37.5 C 22 39 26 39 28 37.5 L 29 38.5 L 47.5 38.5 L 43.5 11.5 L 4.5 11.5 z " + xlink:href="#rect1304" + style="opacity:0.13333333;color:#000000;fill:none;fill-opacity:1;fill-rule:nonzero;stroke:#ffffff;stroke-width:1;stroke-linecap:round;stroke-linejoin:round;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:17.85;stroke-opacity:1;visibility:visible;display:block;overflow:visible" + id="path2274" + inkscape:href="#rect1304" + d="M 5.28125,12.40625 L 1.5625,37.59375 L 18.59375,37.59375 L 19.34375,36.84375 C 19.667151,36.507336 20.191452,36.467006 20.5625,36.75 C 21.327469,37.323727 22.653015,37.71875 24,37.71875 C 25.346985,37.71875 26.672531,37.323727 27.4375,36.75 C 27.808548,36.467006 28.332849,36.507336 28.65625,36.84375 L 29.40625,37.59375 L 46.4375,37.59375 L 42.71875,12.40625 L 5.28125,12.40625 z " /> + <path + style="fill:url(#linearGradient2282);fill-opacity:1.0;fill-rule:evenodd;stroke:#888a85;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 2,36.5 C 7.6666667,36.5 16,35 19,36.5 C 22,34 26,34 29,36.5 C 32,35 41,36.5 46,36.5 L 45.5,34 C 38.5,31.5 29,28.5 24,33 C 19,28.5 9.5,31.5 2.5,34 L 2,36.5 z " + id="path2180" + sodipodi:nodetypes="cccccccc" /> + <path + sodipodi:type="inkscape:offset" + inkscape:radius="-1.0582203" + inkscape:original="M 14 30.875 C 10.125 31.375 6 32.75 2.5 34 L 2 36.5 C 7.6666667 36.5 16 35 19 36.5 C 22 34 26 34 29 36.5 C 32 35 41 36.5 46 36.5 L 45.5 34 C 38.5 31.5 29 28.5 24 33 C 21.5 30.75 17.875 30.375 14 30.875 z " + xlink:href="#path2180" + style="opacity:0.30196078;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:url(#linearGradient2315);stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + id="path2266" + inkscape:href="#path2180" + d="M 14.375,31.9375 C 10.963293,32.392394 7.260823,33.622273 3.90625,34.8125 L 3.8125,35.34375 C 6.2979599,35.262594 9.0476285,35.037732 11.6875,34.875 C 14.462294,34.703951 16.881256,34.711661 18.78125,35.40625 C 20.133116,34.409774 21.661646,33.894157 23.21875,33.75 C 21.042747,31.830616 17.941674,31.461944 14.375,31.9375 z M 28.625,31.9375 C 27.145571,32.213473 25.86037,32.798142 24.78125,33.75 C 26.338354,33.894157 27.866884,34.409774 29.21875,35.40625 C 31.163554,34.697135 33.704549,34.703523 36.5625,34.875 C 39.261382,35.036933 41.920385,35.260963 44.1875,35.34375 L 44.09375,34.8125 C 40.739177,33.622273 37.036707,32.392394 33.625,31.9375 C 31.827105,31.697781 30.128781,31.656984 28.625,31.9375 z " /> + <path + style="fill:url(#linearGradient2245);fill-opacity:1;fill-rule:evenodd;stroke:url(#linearGradient2247);stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + d="M 2.5,34 C 9,31.5 20,29 24,33 C 28,29 39,31.5 45.5,34 L 42.5,10.5 C 37,8 27.5,6 24,9 C 20,6 12,8 5.5,10.5 L 2.5,34 z " + id="path2182" + sodipodi:nodetypes="ccccccc" /> + <path + style="color:#000000;fill:url(#linearGradient2219);fill-opacity:1.0;fill-rule:nonzero;stroke:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dashoffset:17.85;stroke-opacity:1;visibility:visible;display:block;overflow:visible" + d="M 24,9.5 C 22,8 19.5,7.5 16,8 L 16,30.5 C 18,29.5 22,30.5 24,32.5 L 24,9.5 z " + id="rect2192" + sodipodi:nodetypes="ccccc" /> + <path + style="color:#000000;fill:url(#linearGradient2211);fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;marker:none;marker-start:none;marker-mid:none;marker-end:none;stroke-miterlimit:4;stroke-dashoffset:17.85;stroke-opacity:1;visibility:visible;display:block;overflow:visible" + d="M 24,9.5 C 25.221264,8.803878 26.327771,7.9069322 28,8 L 29,30.5 C 27.5,30 25.5,31.5 24,32.5 L 24,9.5 z " + id="path2195" + sodipodi:nodetypes="ccccc" /> + <path + sodipodi:type="inkscape:offset" + inkscape:radius="-0.92850536" + inkscape:original="M 20.34375 7.625 C 16.101562 7.0390625 10.375 8.625 5.5 10.5 L 2.5 34 C 9 31.5 20 29 24 33 C 28 29 39 31.5 45.5 34 L 42.5 10.5 C 37 8 27.5 6 24 9 C 23 8.25 21.757812 7.8203125 20.34375 7.625 z " + xlink:href="#path2182" + style="opacity:0.65098039;fill:none;fill-opacity:1;fill-rule:evenodd;stroke:#ffffff;stroke-width:1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" + id="path2243" + inkscape:href="#path2182" + d="M 17.03125,8.375 C 14.611845,8.6563261 11.827815,9.5624782 8.78125,10.71875 L 4.25,32.59375 C 7.5567067,31.338728 11.345145,30.271354 14.90625,29.9375 C 16.969491,29.744071 18.927893,29.768608 20.625,30.125 C 21.963283,30.406039 23.09173,31.003906 24,31.8125 C 24.90827,31.003906 26.036717,30.406039 27.375,30.125 C 29.072107,29.768608 31.030509,29.744071 33.09375,29.9375 C 36.654855,30.271354 40.443293,31.338728 43.75,32.59375 L 39.1875,10.6875 C 36.612085,9.5579242 33.750698,8.6570052 31.15625,8.375 C 28.420939,8.0776836 26.053467,8.4675643 24.59375,9.71875 C 24.262671,9.9972426 23.783138,10.010203 23.4375,9.75 C 21.660341,8.417131 19.571761,8.0795918 17.03125,8.375 z " /> + <path + style="fill:url(#linearGradient2264);fill-opacity:1.0;fill-rule:evenodd;stroke:url(#linearGradient2307);stroke-width:1;stroke-linecap:square;stroke-linejoin:miter;stroke-opacity:1;stroke-miterlimit:4;stroke-dasharray:none" + d="M 24.455357,8.7321429 C 24.5,20.5 34,20 33.5,30.5 L 32.5,34.5 L 34,34 L 35,35 L 35.5,31 C 36,20 24.544643,19.089286 24.5,8.5 L 24.455357,8.7321429 z " + id="path2227" + sodipodi:nodetypes="cccccccc" /> + </g> +</svg>
radekp/qgcide
9820d0ca7bdba64ccaca1b32d15fc08eade35b27
Fix searching, after found move to left
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index 62650f6..35d6a56 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,504 +1,508 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); //QMenu *menu = menuBar()->addMenu("&File"); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); progress = new QProgressBar(this); progress->setVisible(false); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); layout->addWidget(progress); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::download(QString url, QString destPath, QString filename) { browser->setText(tr("Downloading") + " " + filename); QString host = url; QString reqPath; int port = 80; if(url.startsWith("http://")) { host.remove(0, 7); } int colonIndex = host.indexOf(':'); int slashIndex = host.indexOf('/'); if(slashIndex < 0) { return false; } reqPath = host.right(host.length() - slashIndex).replace(" ", "%20"); host = host.left(slashIndex); if(colonIndex > 0) { QString portStr = host.right(host.length() - colonIndex - 1); host = host.left(colonIndex); port = portStr.toInt(0, 10); } connect: QTcpSocket sock(this); sock.setReadBufferSize(65535); sock.connectToHost(host, port); if(!sock.waitForConnected(5000)) { showErr(sock.errorString()); return false; } QByteArray req("GET "); req.append(reqPath); req.append(" HTTP/1.1\r\nHost: "); req.append(host); req.append(':'); req.append(QByteArray::number(port)); req.append("\r\n\r\n"); sock.write(req); sock.flush(); sock.waitForBytesWritten(); int contentLen = 0; bool html = false; QByteArray line; for(;;) { line = sock.readLine(); if(line.isEmpty()) { if(sock.waitForReadyRead(5000)) { continue; } break; } if(line.trimmed().isEmpty()) { break; } html = html | (line.indexOf("Content-Type: text/html") == 0); if(line.indexOf("Content-Length: ") == 0) { contentLen = line.remove(0, 16).trimmed().toInt(0, 10); } } if(html) { QByteArray text = sock.readAll(); sock.close(); if(text.length() == 0) { QMessageBox::critical(this, tr("English dictionary"), tr("No response from ") + host); return false; } text.replace("</br>", "\n"); if(QMessageBox::information(this, tr("English dictionary"), text, QMessageBox::Ok | QMessageBox::Retry) == QMessageBox::Retry) { goto connect; } return false; } QFile f(destPath); if(!f.open(QFile::WriteOnly)) { QMessageBox::critical(this, tr("English dictionary"), tr("Unable to save file:\r\n\r\n") + f.errorString()); sock.close(); return false; } #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::DisableSuspend); #endif if(contentLen <= 0) { QMessageBox::critical(this, tr("English dictionary"), tr("Couldnt read content length")); contentLen = 0x7fffffff; } progress->setMaximum(contentLen); progress->setValue(0); int remains = contentLen; char buf[65535]; int count; for(;;) { QApplication::processEvents(); count = sock.read(buf, 65535); if(count < 0) { break; } f.write(buf, count); f.flush(); remains -= count; if(remains <= 0) { break; } progress->setValue(contentLen - remains); } f.close(); sock.close(); #ifdef QTOPIA QtopiaApplication::setPowerConstraint(QtopiaApplication::Enable); #endif return true; } bool QDictWidget::ungzip(QString file) { progress->setMaximum(10); progress->setValue(0); QProcess gzip; gzip.start("gzip", QStringList() << "-d" << file); if(!gzip.waitForStarted()) { showErr(tr("Unable to start gzip")); return false; } while(gzip.state() == QProcess::Running) { progress->setValue(progress->value() % 10); QApplication::processEvents(); gzip.waitForFinished(100); } return true; } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } if(QMessageBox::question(this, tr("English dictionary"), tr("Dictionary must be downloaded. Please make sure you have internet connection and press yes to confirm download (14MB)."), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) { return false; } progress->setVisible(true); QString gzFile = dictFile.fileName() + ".gz"; if(!download("http://dl.linuxphone.ru/openmoko/qtmoko/packages/gcide-entries.xml.gz", gzFile, "gcide-entries.xml.gz")) { return false; } if(!ungzip(gzFile)) { return false; } return true; } // Compare current key and searched expression. static int compareExprKey(const QString &expr, const QString &key) { for(int i = 0; i < expr.length(); i++) { if(i >= key.length()) { return 1; // expression is bigger } QChar ech = expr.at(i).toUpper(); QChar kch = key.at(i).toUpper(); if(ech == kch) { continue; } return ech.unicode() - kch.unicode(); } return 0; } QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } // Start searching from the middle qint64 left = 0; qint64 right = dictFile.size() - 4096; dictFile.seek((left + right) / 2); // 0 = find some matching expression // 1 = go forward for first matching expr // 2 = appending text inside matching entry // 3 = skipping text outside entry int phase = 0; QString exprString("<entry key=\"" + expr); char buf[4096]; QString result; int numResults = 0; + bool found = false; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(phase == 2) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); numResults++; if(numResults > maxResults) { break; } phase = 3; continue; } char *keyStart = strstr(buf, "<entry key=\""); if(keyStart == 0) { continue; } keyStart += 12; char *keyEnd = strchr(keyStart, '"'); QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); int cmp = compareExprKey(expr, key); if(phase == 0) { + found |= (cmp == 0); bool changed = true; if(cmp > 0) // expression is bigger then key { left = dictFile.pos(); } else // expression is smaller or matches { changed = (right != dictFile.pos()); // comparing twice same word right = dictFile.pos(); } if(changed && (right - left > 4096)) { dictFile.seek((left + right) / 2); continue; } - if(cmp != 0) + if(!found) { break; } phase = 1; + dictFile.seek(left); + continue; } if(phase == 1) { if(cmp != 0) { continue; } phase = 2; } if(phase == 2 || phase == 3) { QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { break; // first non matching entry was hit } result += str.right(entryStart - exprString.length()); phase = 2; } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text, 32); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; }
radekp/qgcide
964d205d445b42c4546194f13eff174101fc24e7
Fix qtopia build
diff --git a/src/qgcide.h b/src/qgcide.h index 44d6efc..4c70cf1 100644 --- a/src/qgcide.h +++ b/src/qgcide.h @@ -1,67 +1,71 @@ #ifndef QGCIDE_H #define QGCIDE_H #include <QWidget> #include <QLineEdit> #include <QTextBrowser> #include <QGridLayout> #include <QMainWindow> #include <QMenuBar> #include <QDir> #include <QMessageBox> #include <QBuffer> #include <QXmlSimpleReader> #include <QTcpSocket> #include <QApplication> #include <QProgressBar> #include <QProcess> +#ifdef QTOPIA +#include <QtopiaApplication> +#endif + class QDictWidget : public QWidget { Q_OBJECT public: QDictWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QGridLayout *layout; QLineEdit *edit; QTextBrowser *browser; QProgressBar *progress; QFile dictFile; void showErr(QString); bool download(QString url, QString destPath, QString filename); bool ungzip(QString file); bool ensureDictFile(); QString searchExpr(const QString &, int maxResults); private slots: void textChanged(const QString &); }; class QDictMainWindow : public QMainWindow { Q_OBJECT public: QDictMainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QDictWidget *dw; }; class GcideXmlHandler : public QXmlDefaultHandler { public: GcideXmlHandler(); bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes); bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName); bool characters(const QString &str); bool fatalError(const QXmlParseException &exception); bool skip; QString html; }; #endif
radekp/qgcide
9474461c26a94bf4158f23d299f10753d97ccf3a
Implement dictionary downloading
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index e090820..62650f6 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,318 +1,504 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); - QMenu *menu = menuBar()->addMenu("&File"); + //QMenu *menu = menuBar()->addMenu("&File"); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); + progress = new QProgressBar(this); + progress->setVisible(false); + layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); + layout->addWidget(progress); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } +bool QDictWidget::download(QString url, QString destPath, QString filename) +{ + browser->setText(tr("Downloading") + " " + filename); + + QString host = url; + QString reqPath; + int port = 80; + + if(url.startsWith("http://")) + { + host.remove(0, 7); + } + + int colonIndex = host.indexOf(':'); + int slashIndex = host.indexOf('/'); + if(slashIndex < 0) + { + return false; + } + reqPath = host.right(host.length() - slashIndex).replace(" ", "%20"); + host = host.left(slashIndex); + if(colonIndex > 0) + { + QString portStr = host.right(host.length() - colonIndex - 1); + host = host.left(colonIndex); + port = portStr.toInt(0, 10); + } + +connect: + QTcpSocket sock(this); + sock.setReadBufferSize(65535); + sock.connectToHost(host, port); + if(!sock.waitForConnected(5000)) + { + showErr(sock.errorString()); + return false; + } + + QByteArray req("GET "); + req.append(reqPath); + req.append(" HTTP/1.1\r\nHost: "); + req.append(host); + req.append(':'); + req.append(QByteArray::number(port)); + req.append("\r\n\r\n"); + + sock.write(req); + sock.flush(); + sock.waitForBytesWritten(); + + int contentLen = 0; + bool html = false; + QByteArray line; + for(;;) + { + line = sock.readLine(); + if(line.isEmpty()) + { + if(sock.waitForReadyRead(5000)) + { + continue; + } + break; + } + if(line.trimmed().isEmpty()) + { + break; + } + html = html | (line.indexOf("Content-Type: text/html") == 0); + if(line.indexOf("Content-Length: ") == 0) + { + contentLen = line.remove(0, 16).trimmed().toInt(0, 10); + } + } + + if(html) + { + QByteArray text = sock.readAll(); + sock.close(); + if(text.length() == 0) + { + QMessageBox::critical(this, tr("English dictionary"), + tr("No response from ") + host); + return false; + } + text.replace("</br>", "\n"); + if(QMessageBox::information(this, tr("English dictionary"), text, + QMessageBox::Ok | QMessageBox::Retry) == QMessageBox::Retry) + { + goto connect; + } + + return false; + } + + QFile f(destPath); + if(!f.open(QFile::WriteOnly)) + { + QMessageBox::critical(this, tr("English dictionary"), + tr("Unable to save file:\r\n\r\n") + f.errorString()); + sock.close(); + return false; + } + +#ifdef QTOPIA + QtopiaApplication::setPowerConstraint(QtopiaApplication::DisableSuspend); +#endif + + if(contentLen <= 0) + { + QMessageBox::critical(this, tr("English dictionary"), tr("Couldnt read content length")); + contentLen = 0x7fffffff; + } + progress->setMaximum(contentLen); + progress->setValue(0); + int remains = contentLen; + + char buf[65535]; + int count; + for(;;) + { + QApplication::processEvents(); + count = sock.read(buf, 65535); + if(count < 0) + { + break; + } + f.write(buf, count); + f.flush(); + remains -= count; + if(remains <= 0) + { + break; + } + progress->setValue(contentLen - remains); + } + f.close(); + sock.close(); + +#ifdef QTOPIA + QtopiaApplication::setPowerConstraint(QtopiaApplication::Enable); +#endif + + return true; +} + +bool QDictWidget::ungzip(QString file) +{ + progress->setMaximum(10); + progress->setValue(0); + + QProcess gzip; + gzip.start("gzip", QStringList() << "-d" << file); + if(!gzip.waitForStarted()) + { + showErr(tr("Unable to start gzip")); + return false; + } + while(gzip.state() == QProcess::Running) + { + progress->setValue(progress->value() % 10); + QApplication::processEvents(); + gzip.waitForFinished(100); + } + return true; +} + bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } - // TODO: download from internet - return false; + if(QMessageBox::question(this, tr("English dictionary"), + tr("Dictionary must be downloaded. Please make sure you have internet connection and press yes to confirm download (14MB)."), + QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) + { + return false; + } + progress->setVisible(true); + QString gzFile = dictFile.fileName() + ".gz"; + if(!download("http://dl.linuxphone.ru/openmoko/qtmoko/packages/gcide-entries.xml.gz", gzFile, "gcide-entries.xml.gz")) + { + return false; + } + if(!ungzip(gzFile)) + { + return false; + } + return true; } // Compare current key and searched expression. static int compareExprKey(const QString &expr, const QString &key) { for(int i = 0; i < expr.length(); i++) { if(i >= key.length()) { return 1; // expression is bigger } QChar ech = expr.at(i).toUpper(); QChar kch = key.at(i).toUpper(); if(ech == kch) { continue; } return ech.unicode() - kch.unicode(); } return 0; } QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } // Start searching from the middle qint64 left = 0; qint64 right = dictFile.size() - 4096; dictFile.seek((left + right) / 2); // 0 = find some matching expression // 1 = go forward for first matching expr // 2 = appending text inside matching entry // 3 = skipping text outside entry int phase = 0; QString exprString("<entry key=\"" + expr); char buf[4096]; QString result; int numResults = 0; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(phase == 2) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); numResults++; if(numResults > maxResults) { break; } phase = 3; continue; } char *keyStart = strstr(buf, "<entry key=\""); if(keyStart == 0) { continue; } keyStart += 12; char *keyEnd = strchr(keyStart, '"'); QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); int cmp = compareExprKey(expr, key); if(phase == 0) { bool changed = true; if(cmp > 0) // expression is bigger then key { left = dictFile.pos(); } else // expression is smaller or matches { changed = (right != dictFile.pos()); // comparing twice same word right = dictFile.pos(); } if(changed && (right - left > 4096)) { dictFile.seek((left + right) / 2); continue; } if(cmp != 0) { break; } phase = 1; } if(phase == 1) { if(cmp != 0) { continue; } phase = 2; } if(phase == 2 || phase == 3) { QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { break; // first non matching entry was hit } result += str.right(entryStart - exprString.length()); phase = 2; } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text, 32); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; } diff --git a/src/qgcide.h b/src/qgcide.h index 4ba7647..44d6efc 100644 --- a/src/qgcide.h +++ b/src/qgcide.h @@ -1,60 +1,67 @@ #ifndef QGCIDE_H #define QGCIDE_H #include <QWidget> #include <QLineEdit> #include <QTextBrowser> #include <QGridLayout> #include <QMainWindow> #include <QMenuBar> #include <QDir> #include <QMessageBox> #include <QBuffer> #include <QXmlSimpleReader> +#include <QTcpSocket> +#include <QApplication> +#include <QProgressBar> +#include <QProcess> class QDictWidget : public QWidget { Q_OBJECT public: QDictWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QGridLayout *layout; QLineEdit *edit; QTextBrowser *browser; + QProgressBar *progress; QFile dictFile; void showErr(QString); + bool download(QString url, QString destPath, QString filename); + bool ungzip(QString file); bool ensureDictFile(); QString searchExpr(const QString &, int maxResults); private slots: void textChanged(const QString &); }; class QDictMainWindow : public QMainWindow { Q_OBJECT public: QDictMainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QDictWidget *dw; }; class GcideXmlHandler : public QXmlDefaultHandler { public: GcideXmlHandler(); bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes); bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName); bool characters(const QString &str); bool fatalError(const QXmlParseException &exception); bool skip; QString html; }; #endif
radekp/qgcide
caf06813fff58cdb100946361b42fdb739e26bce
fix slowness when expression does not exist
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index d62449b..e090820 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,314 +1,318 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); QMenu *menu = menuBar()->addMenu("&File"); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } // TODO: download from internet return false; } // Compare current key and searched expression. static int compareExprKey(const QString &expr, const QString &key) { for(int i = 0; i < expr.length(); i++) { if(i >= key.length()) { return 1; // expression is bigger } QChar ech = expr.at(i).toUpper(); QChar kch = key.at(i).toUpper(); if(ech == kch) { continue; } return ech.unicode() - kch.unicode(); } return 0; } QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } // Start searching from the middle qint64 left = 0; qint64 right = dictFile.size() - 4096; dictFile.seek((left + right) / 2); // 0 = find some matching expression // 1 = go forward for first matching expr // 2 = appending text inside matching entry // 3 = skipping text outside entry int phase = 0; QString exprString("<entry key=\"" + expr); char buf[4096]; QString result; int numResults = 0; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(phase == 2) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); numResults++; if(numResults > maxResults) { break; } phase = 3; continue; } char *keyStart = strstr(buf, "<entry key=\""); if(keyStart == 0) { continue; } keyStart += 12; char *keyEnd = strchr(keyStart, '"'); QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); int cmp = compareExprKey(expr, key); if(phase == 0) { bool changed = true; if(cmp > 0) // expression is bigger then key { left = dictFile.pos(); } else // expression is smaller or matches { changed = (right != dictFile.pos()); // comparing twice same word right = dictFile.pos(); } - if(changed) + if(changed && (right - left > 4096)) { dictFile.seek((left + right) / 2); continue; } + if(cmp != 0) + { + break; + } phase = 1; } if(phase == 1) { if(cmp != 0) { continue; } phase = 2; } if(phase == 2 || phase == 3) { QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { break; // first non matching entry was hit } result += str.right(entryStart - exprString.length()); phase = 2; } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text, 32); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; }
radekp/qgcide
d938d8327443629498171c8f5a558b89aee40855
Get rid of backward searching
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index 14da85d..d62449b 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,337 +1,314 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); QMenu *menu = menuBar()->addMenu("&File"); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } // TODO: download from internet return false; } // Compare current key and searched expression. static int compareExprKey(const QString &expr, const QString &key) { for(int i = 0; i < expr.length(); i++) { if(i >= key.length()) { return 1; // expression is bigger } QChar ech = expr.at(i).toUpper(); QChar kch = key.at(i).toUpper(); if(ech == kch) { continue; } return ech.unicode() - kch.unicode(); } return 0; } QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } // Start searching from the middle qint64 left = 0; qint64 right = dictFile.size() - 4096; dictFile.seek((left + right) / 2); // 0 = find some matching expression - // 1 = go backwards to find first non matching expr - // 2 = go forward for first matching expr - // 3 = appending text inside matching entry - // 4 = skipping text outside entry + // 1 = go forward for first matching expr + // 2 = appending text inside matching entry + // 3 = skipping text outside entry int phase = 0; QString exprString("<entry key=\"" + expr); char buf[4096]; QString result; int numResults = 0; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } - if(phase == 3) + if(phase == 2) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); numResults++; if(numResults > maxResults) { break; } - phase = 4; + phase = 3; continue; } char *keyStart = strstr(buf, "<entry key=\""); if(keyStart == 0) { continue; } keyStart += 12; char *keyEnd = strchr(keyStart, '"'); QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); int cmp = compareExprKey(expr, key); if(phase == 0) { - if(cmp == 0) + bool changed = true; + if(cmp > 0) // expression is bigger then key { - phase = 1; + left = dictFile.pos(); } - else + else // expression is smaller or matches + { + changed = (right != dictFile.pos()); // comparing twice same word + right = dictFile.pos(); + } + if(changed) { - if(cmp > 0) // expression is bigger then key - { - left = dictFile.pos(); - } - else - { - right = dictFile.pos(); - } - if(right - left <= 32) - { - break; // not found - } dictFile.seek((left + right) / 2); continue; } + phase = 1; } if(phase == 1) - { - if(cmp == 0) // we have match, let's move backwards - { - qint64 newPos = dictFile.pos() - 65535; - if(newPos <= 0) - { - newPos = 0; - phase = 2; - } - dictFile.seek(newPos); - } - else - { - phase = 2; - } - } - if(phase == 2) { if(cmp != 0) { continue; } - phase = 3; + phase = 2; } - if(phase == 3 || phase == 4) + if(phase == 2 || phase == 3) { QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { break; // first non matching entry was hit } result += str.right(entryStart - exprString.length()); - phase = 3; + phase = 2; } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text, 32); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; }
radekp/qgcide
2a4d221a8da1abad6584aae8402ee9bce3975c25
Speedup using binary search, backward search is still slow
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index 717abd8..14da85d 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,248 +1,337 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); QMenu *menu = menuBar()->addMenu("&File"); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } // TODO: download from internet + return false; } -QString QDictWidget::searchExpr(const QString &expr) +// Compare current key and searched expression. +static int compareExprKey(const QString &expr, const QString &key) +{ + for(int i = 0; i < expr.length(); i++) + { + if(i >= key.length()) + { + return 1; // expression is bigger + } + QChar ech = expr.at(i).toUpper(); + QChar kch = key.at(i).toUpper(); + if(ech == kch) + { + continue; + } + return ech.unicode() - kch.unicode(); + } + return 0; +} + +QString QDictWidget::searchExpr(const QString &expr, int maxResults) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } + + // Start searching from the middle + qint64 left = 0; + qint64 right = dictFile.size() - 4096; + dictFile.seek((left + right) / 2); + + // 0 = find some matching expression + // 1 = go backwards to find first non matching expr + // 2 = go forward for first matching expr + // 3 = appending text inside matching entry + // 4 = skipping text outside entry + int phase = 0; + QString exprString("<entry key=\"" + expr); - char buf[4096]; - bool found = false; + char buf[4096]; QString result; + int numResults = 0; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } - if(found) + if(phase == 3) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); - found = false; + numResults++; + if(numResults > maxResults) + { + break; + } + phase = 4; continue; } - if(!strstr(buf, "<entry key=\"")) + char *keyStart = strstr(buf, "<entry key=\""); + if(keyStart == 0) { continue; } - QString str = QString::fromUtf8(buf); - int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); - if(entryStart < 0) + keyStart += 12; + char *keyEnd = strchr(keyStart, '"'); + QString key = QString::fromUtf8(keyStart, keyEnd - keyStart); + int cmp = compareExprKey(expr, key); + if(phase == 0) { - if(result.length() > 0) + if(cmp == 0) { - break; + phase = 1; } else { + if(cmp > 0) // expression is bigger then key + { + left = dictFile.pos(); + } + else + { + right = dictFile.pos(); + } + if(right - left <= 32) + { + break; // not found + } + dictFile.seek((left + right) / 2); continue; } } - result += str.right(entryStart - exprString.length()); - found = true; + if(phase == 1) + { + if(cmp == 0) // we have match, let's move backwards + { + qint64 newPos = dictFile.pos() - 65535; + if(newPos <= 0) + { + newPos = 0; + phase = 2; + } + dictFile.seek(newPos); + } + else + { + phase = 2; + } + } + if(phase == 2) + { + if(cmp != 0) + { + continue; + } + phase = 3; + } + if(phase == 3 || phase == 4) + { + QString str = QString::fromUtf8(buf); + int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); + if(entryStart < 0) + { + break; // first non matching entry was hit + } + result += str.right(entryStart - exprString.length()); + phase = 3; + } } dictFile.close(); if(result.length() == 0) { result = tr("Expression not found"); } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; - xml += searchExpr(text); + xml += searchExpr(text, 32); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") - .arg(exception.lineNumber()) - .arg(exception.columnNumber()) - .arg(exception.message()); + .arg(exception.lineNumber()) + .arg(exception.columnNumber()) + .arg(exception.message()); return false; } diff --git a/src/qgcide.h b/src/qgcide.h index c5300d8..4ba7647 100644 --- a/src/qgcide.h +++ b/src/qgcide.h @@ -1,60 +1,60 @@ #ifndef QGCIDE_H #define QGCIDE_H #include <QWidget> #include <QLineEdit> #include <QTextBrowser> #include <QGridLayout> #include <QMainWindow> #include <QMenuBar> #include <QDir> #include <QMessageBox> #include <QBuffer> #include <QXmlSimpleReader> class QDictWidget : public QWidget { Q_OBJECT public: QDictWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QGridLayout *layout; QLineEdit *edit; QTextBrowser *browser; QFile dictFile; void showErr(QString); bool ensureDictFile(); - QString searchExpr(const QString &); + QString searchExpr(const QString &, int maxResults); private slots: void textChanged(const QString &); }; class QDictMainWindow : public QMainWindow { Q_OBJECT public: QDictMainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QDictWidget *dw; }; class GcideXmlHandler : public QXmlDefaultHandler { public: GcideXmlHandler(); bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &attributes); bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName); bool characters(const QString &str); bool fatalError(const QXmlParseException &exception); bool skip; QString html; }; #endif
radekp/qgcide
36bcbbd0f23a343da64e2b0421c75fb195631de5
Stop searching after expression no more matches
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index 54efccd..717abd8 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,240 +1,248 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); QMenu *menu = menuBar()->addMenu("&File"); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } // TODO: download from internet } QString QDictWidget::searchExpr(const QString &expr) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } QString exprString("<entry key=\"" + expr); char buf[4096]; bool found = false; QString result; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { - if(result.length() == 0) - { - result = tr("Phrase not found"); - } + break; } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(found) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); found = false; continue; } if(!strstr(buf, "<entry key=\"")) { continue; } QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { - continue; + if(result.length() > 0) + { + break; + } + else + { + continue; + } } result += str.right(entryStart - exprString.length()); found = true; } dictFile.close(); + if(result.length() == 0) + { + result = tr("Expression not found"); + } return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } else if(qName == "def") // definition { skip = false; } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } else if(qName == "def") { skip = true; } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; }
radekp/qgcide
60483b6494e66c9ab74fba9960ef984a18a95ccd
Add definitions to output
diff --git a/src/qgcide.cpp b/src/qgcide.cpp index 558f63c..54efccd 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,232 +1,240 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); QMenu *menu = menuBar()->addMenu("&File"); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); edit = new QLineEdit(this); connect(edit, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&))); browser = new QTextBrowser(this); layout->addWidget(edit, 0, 0); layout->addWidget(browser, 1, 0); setLayout(layout); } void QDictWidget::showErr(QString err) { QMessageBox::critical(this, tr("English dictionary"), err); } bool QDictWidget::ensureDictFile() { if(dictFile.exists()) { return true; } QDir baseDir("/media/card"); if(!baseDir.exists()) { baseDir = QDir::home(); } QDir dictDir(baseDir.path() + "/.qgcide"); if(!dictDir.exists()) { if(!baseDir.mkdir(".qgcide")) { showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); return false; } } dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); if(dictFile.exists()) { return true; } // TODO: download from internet } QString QDictWidget::searchExpr(const QString &expr) { if(!ensureDictFile()) { return ""; } if(!dictFile.open(QFile::ReadOnly)) { return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); } QString exprString("<entry key=\"" + expr); char buf[4096]; bool found = false; QString result; for(;;) { int readRes = dictFile.readLine(&buf[0], 4096); if(readRes < 0) { if(dictFile.atEnd()) { if(result.length() == 0) { result = tr("Phrase not found"); } } else { result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); } break; } if(readRes == 0) { continue; // empty line } if(found) { QString line(buf); int entryEnd = line.indexOf("</entry>"); if(entryEnd < 0) { result += line; continue; } result += line.left(entryEnd + 8); found = false; continue; } if(!strstr(buf, "<entry key=\"")) { continue; } QString str = QString::fromUtf8(buf); int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); if(entryStart < 0) { continue; } result += str.right(entryStart - exprString.length()); found = true; } dictFile.close(); return result; } static QString toHtml(QString &xml) { QByteArray bytes = xml.toUtf8(); QBuffer buf(&bytes); QXmlInputSource source(&buf); GcideXmlHandler handler; QXmlSimpleReader reader; reader.setContentHandler(&handler); reader.setErrorHandler(&handler); reader.parse(source); return handler.html; } void QDictWidget::textChanged(const QString &text) { QString xml = "<entries>"; xml += searchExpr(text); xml += "</entries>"; QString html = toHtml(xml); browser->setText(html); } GcideXmlHandler::GcideXmlHandler() { } bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName, const QXmlAttributes &attributes) { if(qName == "ex") // expression { html += "<b>"; } + else if(qName == "def") // definition + { + skip = false; + } else if(qName == "sn") // senses <sn no="1">....</sn> { if(html.endsWith("</ol>")) { html.chop(5); } else { html += "<ol>"; } html += "<li>"; skip = false; } if(qName == "entry") // <entry key="Hell"> { html += "<h1>"; html += attributes.value("key"); html += "</h1>"; skip = true; } else if(qName == "entries") { html += "<html>"; } return true; } bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { if(qName == "ex") { html += "</b>"; } + else if(qName == "def") + { + skip = true; + } else if(qName == "sn") { html += "</li></ol>"; } else if(qName == "entry") { html += "<br><br>"; } else if(qName == "entries") { html += "</html>"; } return true; } bool GcideXmlHandler::characters(const QString &str) { if(skip) { return true; } html += str.trimmed(); return true; } bool GcideXmlHandler::fatalError(const QXmlParseException &exception) { html += QObject::tr("Parse error at line %1, column %2:\n%3") .arg(exception.lineNumber()) .arg(exception.columnNumber()) .arg(exception.message()); return false; }
radekp/qgcide
28162eb338ac234c773fe048bf970347b5912867
First working version
diff --git a/qgcide.pro b/qgcide.pro index 70d8717..4cb0e8d 100644 --- a/qgcide.pro +++ b/qgcide.pro @@ -1,15 +1,15 @@ #------------------------------------------------- # # Project created by QtCreator 2009-04-14T22:32:40 # #------------------------------------------------- TARGET = qgcide TEMPLATE = app -QT += core gui network +QT += core gui network xml SOURCES += src/main.cpp\ src/qgcide.cpp HEADERS += src/qgcide.h diff --git a/src/qgcide.cpp b/src/qgcide.cpp index feff7ae..558f63c 100644 --- a/src/qgcide.cpp +++ b/src/qgcide.cpp @@ -1,31 +1,232 @@ #include "qgcide.h" QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) { setWindowTitle(tr("English dictionary")); QMenu *menu = menuBar()->addMenu("&File"); dw = new QDictWidget(this); setCentralWidget(dw); } QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) { layout = new QGridLayout(this); - textEdit = new QTextEdit(this); - connect(textEdit, SIGNAL(textChanged(const QString&)), - this, SLOT(textChanged(const QString&))); + edit = new QLineEdit(this); + connect(edit, SIGNAL(textChanged(const QString&)), + this, SLOT(textChanged(const QString&))); - textBrowser = new QTextBrowser(this); + browser = new QTextBrowser(this); - layout->addWidget(textEdit, 0, 0); - layout->addWidget(textBrowser, 1, 0); + layout->addWidget(edit, 0, 0); + layout->addWidget(browser, 1, 0); setLayout(layout); } -bool QDictWidget::textChanged(const QString& text) +void QDictWidget::showErr(QString err) { + QMessageBox::critical(this, tr("English dictionary"), err); +} + +bool QDictWidget::ensureDictFile() +{ + if(dictFile.exists()) + { + return true; + } + QDir baseDir("/media/card"); + if(!baseDir.exists()) + { + baseDir = QDir::home(); + } + QDir dictDir(baseDir.path() + "/.qgcide"); + if(!dictDir.exists()) + { + if(!baseDir.mkdir(".qgcide")) + { + showErr(tr("Unable to create dictionary dir ") + dictDir.absolutePath()); + return false; + } + } + dictFile.setFileName(dictDir.absolutePath() + "/gcide-entries.xml"); + if(dictFile.exists()) + { + return true; + } + // TODO: download from internet +} +QString QDictWidget::searchExpr(const QString &expr) +{ + if(!ensureDictFile()) + { + return ""; + } + if(!dictFile.open(QFile::ReadOnly)) + { + return tr("Unable to open dictionary file ") + dictFile.fileName() + "\n\n" + dictFile.errorString(); + } + QString exprString("<entry key=\"" + expr); + char buf[4096]; + bool found = false; + QString result; + for(;;) + { + int readRes = dictFile.readLine(&buf[0], 4096); + if(readRes < 0) + { + if(dictFile.atEnd()) + { + if(result.length() == 0) + { + result = tr("Phrase not found"); + } + } + else + { + result += tr("Error reading from dictionary file") + ":\n\n" + dictFile.errorString(); + } + break; + } + if(readRes == 0) + { + continue; // empty line + } + if(found) + { + QString line(buf); + int entryEnd = line.indexOf("</entry>"); + if(entryEnd < 0) + { + result += line; + continue; + } + result += line.left(entryEnd + 8); + found = false; + continue; + } + if(!strstr(buf, "<entry key=\"")) + { + continue; + } + QString str = QString::fromUtf8(buf); + int entryStart = str.indexOf(exprString, 0, Qt::CaseInsensitive); + if(entryStart < 0) + { + continue; + } + result += str.right(entryStart - exprString.length()); + found = true; + } + dictFile.close(); + return result; +} + +static QString toHtml(QString &xml) +{ + QByteArray bytes = xml.toUtf8(); + QBuffer buf(&bytes); + QXmlInputSource source(&buf); + GcideXmlHandler handler; + QXmlSimpleReader reader; + reader.setContentHandler(&handler); + reader.setErrorHandler(&handler); + reader.parse(source); + return handler.html; } + +void QDictWidget::textChanged(const QString &text) +{ + QString xml = "<entries>"; + xml += searchExpr(text); + xml += "</entries>"; + QString html = toHtml(xml); + browser->setText(html); +} + +GcideXmlHandler::GcideXmlHandler() +{ +} + +bool GcideXmlHandler::startElement(const QString & /* namespaceURI */, + const QString & /* localName */, + const QString &qName, + const QXmlAttributes &attributes) +{ + if(qName == "ex") // expression + { + html += "<b>"; + } + else if(qName == "sn") // senses <sn no="1">....</sn> + { + if(html.endsWith("</ol>")) + { + html.chop(5); + } + else + { + html += "<ol>"; + } + html += "<li>"; + skip = false; + } + if(qName == "entry") // <entry key="Hell"> + { + html += "<h1>"; + html += attributes.value("key"); + html += "</h1>"; + skip = true; + } + else if(qName == "entries") + { + html += "<html>"; + } + + return true; +} + +bool GcideXmlHandler::endElement(const QString & /* namespaceURI */, + const QString & /* localName */, + const QString &qName) +{ + if(qName == "ex") + { + html += "</b>"; + } + else if(qName == "sn") + { + html += "</li></ol>"; + } + else if(qName == "entry") + { + html += "<br><br>"; + } + else if(qName == "entries") + { + html += "</html>"; + } + return true; +} + +bool GcideXmlHandler::characters(const QString &str) +{ + if(skip) + { + return true; + } + html += str.trimmed(); + return true; +} + + +bool GcideXmlHandler::fatalError(const QXmlParseException &exception) +{ + html += QObject::tr("Parse error at line %1, column %2:\n%3") + .arg(exception.lineNumber()) + .arg(exception.columnNumber()) + .arg(exception.message()); + return false; +} + diff --git a/src/qgcide.h b/src/qgcide.h index 5363a64..c5300d8 100644 --- a/src/qgcide.h +++ b/src/qgcide.h @@ -1,36 +1,60 @@ #ifndef QGCIDE_H #define QGCIDE_H #include <QWidget> -#include <QTextEdit> +#include <QLineEdit> #include <QTextBrowser> #include <QGridLayout> #include <QMainWindow> #include <QMenuBar> +#include <QDir> +#include <QMessageBox> +#include <QBuffer> +#include <QXmlSimpleReader> class QDictWidget : public QWidget { Q_OBJECT public: QDictWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QGridLayout *layout; - QTextEdit *textEdit; - QTextBrowser *textBrowser; + QLineEdit *edit; + QTextBrowser *browser; + QFile dictFile; + void showErr(QString); + bool ensureDictFile(); + QString searchExpr(const QString &); private slots: - bool textChanged(const QString& text); + void textChanged(const QString &); }; class QDictMainWindow : public QMainWindow { Q_OBJECT public: QDictMainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); private: QDictWidget *dw; }; +class GcideXmlHandler : public QXmlDefaultHandler +{ +public: + GcideXmlHandler(); + + bool startElement(const QString &namespaceURI, const QString &localName, + const QString &qName, const QXmlAttributes &attributes); + bool endElement(const QString &namespaceURI, const QString &localName, + const QString &qName); + bool characters(const QString &str); + bool fatalError(const QXmlParseException &exception); + + bool skip; + QString html; +}; + #endif
radekp/qgcide
11aeb5f90085078253664bad87dbfbd828f82370
QGcide - English dictionary app working with GCIDE database
diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..bff37be --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +Radek Polak <[email protected]> \ No newline at end of file diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..214d43f --- /dev/null +++ b/Makefile @@ -0,0 +1,204 @@ +############################################################################# +# Makefile for building: qgcide +# Generated by qmake (2.01a) (Qt 4.6.1) on: Fri Apr 30 13:43:56 2010 +# Project: qgcide.pro +# Template: app +# Command: /home/radek/qtsdk-2010.01/qt/bin/qmake -spec ../../../../qtsdk-2010.01/qt/mkspecs/linux-g++-64 -unix CONFIG+=debug -o Makefile qgcide.pro +############################################################################# + +####### Compiler, tools and options + +CC = gcc +CXX = g++ +DEFINES = -DQT_GUI_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -DQT_SHARED +CFLAGS = -m64 -pipe -g -Wall -W -D_REENTRANT $(DEFINES) +CXXFLAGS = -m64 -pipe -g -Wall -W -D_REENTRANT $(DEFINES) +INCPATH = -I../../../../qtsdk-2010.01/qt/mkspecs/linux-g++-64 -I. -I../../../../qtsdk-2010.01/qt/include/QtCore -I../../../../qtsdk-2010.01/qt/include/QtNetwork -I../../../../qtsdk-2010.01/qt/include/QtGui -I../../../../qtsdk-2010.01/qt/include -I. +LINK = g++ +LFLAGS = -m64 -Wl,-rpath,/home/radek/qtsdk-2010.01/qt/lib +LIBS = $(SUBLIBS) -L/home/radek/qtsdk-2010.01/qt/lib -lQtGui -L/home/radek/qtsdk-2010.01/qt/lib -L/usr/X11R6/lib64 -lQtNetwork -lQtCore -lpthread +AR = ar cqs +RANLIB = +QMAKE = /home/radek/qtsdk-2010.01/qt/bin/qmake +TAR = tar -cf +COMPRESS = gzip -9f +COPY = cp -f +SED = sed +COPY_FILE = $(COPY) +COPY_DIR = $(COPY) -r +STRIP = strip +INSTALL_FILE = install -m 644 -p +INSTALL_DIR = $(COPY_DIR) +INSTALL_PROGRAM = install -m 755 -p +DEL_FILE = rm -f +SYMLINK = ln -f -s +DEL_DIR = rmdir +MOVE = mv -f +CHK_DIR_EXISTS= test -d +MKDIR = mkdir -p + +####### Output directory + +OBJECTS_DIR = ./ + +####### Files + +SOURCES = src/main.cpp \ + src/qgcide.cpp +OBJECTS = main.o \ + qgcide.o +DIST = ../../../../qtsdk-2010.01/qt/mkspecs/common/g++.conf \ + ../../../../qtsdk-2010.01/qt/mkspecs/common/unix.conf \ + ../../../../qtsdk-2010.01/qt/mkspecs/common/linux.conf \ + ../../../../qtsdk-2010.01/qt/mkspecs/qconfig.pri \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/qt_functions.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/qt_config.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/exclusive_builds.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/default_pre.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/debug.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/default_post.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/warn_on.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/qt.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/unix/thread.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/moc.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/resources.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/uic.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/yacc.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/lex.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/include_source_dir.prf \ + qgcide.pro +QMAKE_TARGET = qgcide +DESTDIR = +TARGET = qgcide + +first: all +####### Implicit rules + +.SUFFIXES: .o .c .cpp .cc .cxx .C + +.cpp.o: + $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" + +.cc.o: + $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" + +.cxx.o: + $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" + +.C.o: + $(CXX) -c $(CXXFLAGS) $(INCPATH) -o "$@" "$<" + +.c.o: + $(CC) -c $(CFLAGS) $(INCPATH) -o "$@" "$<" + +####### Build rules + +all: Makefile $(TARGET) + +$(TARGET): $(OBJECTS) + $(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS) + +Makefile: qgcide.pro ../../../../qtsdk-2010.01/qt/mkspecs/linux-g++-64/qmake.conf ../../../../qtsdk-2010.01/qt/mkspecs/common/g++.conf \ + ../../../../qtsdk-2010.01/qt/mkspecs/common/unix.conf \ + ../../../../qtsdk-2010.01/qt/mkspecs/common/linux.conf \ + ../../../../qtsdk-2010.01/qt/mkspecs/qconfig.pri \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/qt_functions.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/qt_config.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/exclusive_builds.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/default_pre.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/debug.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/default_post.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/warn_on.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/qt.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/unix/thread.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/moc.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/resources.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/uic.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/yacc.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/lex.prf \ + ../../../../qtsdk-2010.01/qt/mkspecs/features/include_source_dir.prf \ + /home/radek/qtsdk-2010.01/qt/lib/libQtGui.prl \ + /home/radek/qtsdk-2010.01/qt/lib/libQtCore.prl \ + /home/radek/qtsdk-2010.01/qt/lib/libQtNetwork.prl + $(QMAKE) -spec ../../../../qtsdk-2010.01/qt/mkspecs/linux-g++-64 -unix CONFIG+=debug -o Makefile qgcide.pro +../../../../qtsdk-2010.01/qt/mkspecs/common/g++.conf: +../../../../qtsdk-2010.01/qt/mkspecs/common/unix.conf: +../../../../qtsdk-2010.01/qt/mkspecs/common/linux.conf: +../../../../qtsdk-2010.01/qt/mkspecs/qconfig.pri: +../../../../qtsdk-2010.01/qt/mkspecs/features/qt_functions.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/qt_config.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/exclusive_builds.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/default_pre.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/debug.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/default_post.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/warn_on.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/qt.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/unix/thread.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/moc.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/resources.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/uic.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/yacc.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/lex.prf: +../../../../qtsdk-2010.01/qt/mkspecs/features/include_source_dir.prf: +/home/radek/qtsdk-2010.01/qt/lib/libQtGui.prl: +/home/radek/qtsdk-2010.01/qt/lib/libQtCore.prl: +/home/radek/qtsdk-2010.01/qt/lib/libQtNetwork.prl: +qmake: FORCE + @$(QMAKE) -spec ../../../../qtsdk-2010.01/qt/mkspecs/linux-g++-64 -unix CONFIG+=debug -o Makefile qgcide.pro + +dist: + @$(CHK_DIR_EXISTS) .tmp/qgcide1.0.0 || $(MKDIR) .tmp/qgcide1.0.0 + $(COPY_FILE) --parents $(SOURCES) $(DIST) .tmp/qgcide1.0.0/ && $(COPY_FILE) --parents src/qgcide.h .tmp/qgcide1.0.0/ && $(COPY_FILE) --parents src/main.cpp src/qgcide.cpp .tmp/qgcide1.0.0/ && (cd `dirname .tmp/qgcide1.0.0` && $(TAR) qgcide1.0.0.tar qgcide1.0.0 && $(COMPRESS) qgcide1.0.0.tar) && $(MOVE) `dirname .tmp/qgcide1.0.0`/qgcide1.0.0.tar.gz . && $(DEL_FILE) -r .tmp/qgcide1.0.0 + + +clean:compiler_clean + -$(DEL_FILE) $(OBJECTS) + -$(DEL_FILE) *~ core *.core + + +####### Sub-libraries + +distclean: clean + -$(DEL_FILE) $(TARGET) + -$(DEL_FILE) Makefile + + +mocclean: compiler_moc_header_clean compiler_moc_source_clean + +mocables: compiler_moc_header_make_all compiler_moc_source_make_all + +compiler_moc_header_make_all: +compiler_moc_header_clean: +compiler_rcc_make_all: +compiler_rcc_clean: +compiler_image_collection_make_all: qmake_image_collection.cpp +compiler_image_collection_clean: + -$(DEL_FILE) qmake_image_collection.cpp +compiler_moc_source_make_all: +compiler_moc_source_clean: +compiler_uic_make_all: +compiler_uic_clean: +compiler_yacc_decl_make_all: +compiler_yacc_decl_clean: +compiler_yacc_impl_make_all: +compiler_yacc_impl_clean: +compiler_lex_make_all: +compiler_lex_clean: +compiler_clean: + +####### Compile + +main.o: src/main.cpp src/qgcide.h + $(CXX) -c $(CXXFLAGS) $(INCPATH) -o main.o src/main.cpp + +qgcide.o: src/qgcide.cpp src/qgcide.h + $(CXX) -c $(CXXFLAGS) $(INCPATH) -o qgcide.o src/qgcide.cpp + +####### Install + +install: FORCE + +uninstall: FORCE + +FORCE: + diff --git a/README b/README new file mode 100644 index 0000000..07c38a1 --- /dev/null +++ b/README @@ -0,0 +1,4 @@ +Qgcide is simple english explanatory dictionary frontent which uses database +from GCIDE project http://www.ibiblio.org/webster/ + +Dictionary will be downloaded when programs starts up. \ No newline at end of file diff --git a/help/html/qgcide.html b/help/html/qgcide.html new file mode 100644 index 0000000..ab51b5c --- /dev/null +++ b/help/html/qgcide.html @@ -0,0 +1,10 @@ + <html> + <head><title>QDictopia</title></head> + <body> + <!--#if expr="$USERGUIDE"--> + <h2>QDictopia</h2> + <!--#endif--> + <p><img src=":image/qdictopia/QDictopia"></p> + <p> A dictionary program ported from StarDict.</p> + </body> + </html> diff --git a/pics/qgcide.png b/pics/qgcide.png new file mode 100644 index 0000000..1256873 Binary files /dev/null and b/pics/qgcide.png differ diff --git a/qbuild.pro b/qbuild.pro new file mode 100644 index 0000000..7085067 --- /dev/null +++ b/qbuild.pro @@ -0,0 +1,55 @@ +TEMPLATE=app +TARGET=qgcide + +CONFIG+=qtopia +DEFINES+=QTOPIA + +# I18n info +STRING_LANGUAGE=en_US +LANGUAGES=en_US + +INCLUDEPATH+=/usr/include/glib-2.0 \ + /usr/lib/glib-2.0/include + +LIBS+=-lglib-2.0 + +# Package info +pkg [ + name=qdictopia + desc="A Dictionary Program for GCIDE" + license=GPLv2 + version=1.0 + maintainer="Radek Polak <[email protected]>" +] + +# Input files +HEADERS=\ + src/qgcide.h + +SOURCES=\ + src/main.cpp \ + src/qgcide.cpp \ + +# Install rules +target [ + hint=sxe + domain=untrusted +] + +desktop [ + hint=desktop + files=qgcide.desktop + path=/apps/Applications +] + +pics [ + hint=pics + files=pics/* + path=/pics/qgcide +] + +help [ + hint=help + source=help + files=*.html +] \ No newline at end of file diff --git a/qgcide.desktop b/qgcide.desktop new file mode 100644 index 0000000..095980c --- /dev/null +++ b/qgcide.desktop @@ -0,0 +1,10 @@ +[Translation] +File=QtopiaApplications +Context=QGcide +[Desktop Entry] +Comment[]=An English Dictionary Program +Exec=qgcide +Icon=qgcide/qgcide +Type=Application +Name[]=English Dictionary +Categories=MainApplications diff --git a/qgcide.pro b/qgcide.pro new file mode 100644 index 0000000..70d8717 --- /dev/null +++ b/qgcide.pro @@ -0,0 +1,15 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2009-04-14T22:32:40 +# +#------------------------------------------------- + +TARGET = qgcide +TEMPLATE = app + +QT += core gui network + +SOURCES += src/main.cpp\ + src/qgcide.cpp + +HEADERS += src/qgcide.h diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..35963ed --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,22 @@ +#ifdef QTOPIA + +#include <qtopiaapplication.h> +#include "qgcide.h" + +QTOPIA_ADD_APPLICATION(QTOPIA_TARGET, QDictMainWindow) +QTOPIA_MAIN + +#else // QTOPIA + +#include <QtGui/QApplication> +#include "qgcide.h" + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + QDictMainWindow w; + w.show(); + return a.exec(); +} + +#endif // QTOPIA diff --git a/src/qgcide.cpp b/src/qgcide.cpp new file mode 100644 index 0000000..feff7ae --- /dev/null +++ b/src/qgcide.cpp @@ -0,0 +1,31 @@ +#include "qgcide.h" + +QDictMainWindow::QDictMainWindow(QWidget* parent, Qt::WindowFlags f) : QMainWindow(parent, f) +{ + setWindowTitle(tr("English dictionary")); + QMenu *menu = menuBar()->addMenu("&File"); + + dw = new QDictWidget(this); + setCentralWidget(dw); +} + +QDictWidget::QDictWidget(QWidget* parent, Qt::WindowFlags f) : QWidget(parent, f) +{ + layout = new QGridLayout(this); + + textEdit = new QTextEdit(this); + connect(textEdit, SIGNAL(textChanged(const QString&)), + this, SLOT(textChanged(const QString&))); + + textBrowser = new QTextBrowser(this); + + layout->addWidget(textEdit, 0, 0); + layout->addWidget(textBrowser, 1, 0); + + setLayout(layout); +} + +bool QDictWidget::textChanged(const QString& text) +{ + +} diff --git a/src/qgcide.h b/src/qgcide.h new file mode 100644 index 0000000..5363a64 --- /dev/null +++ b/src/qgcide.h @@ -0,0 +1,36 @@ +#ifndef QGCIDE_H +#define QGCIDE_H + +#include <QWidget> +#include <QTextEdit> +#include <QTextBrowser> +#include <QGridLayout> +#include <QMainWindow> +#include <QMenuBar> + +class QDictWidget : public QWidget +{ + Q_OBJECT +public: + QDictWidget(QWidget* parent = 0, Qt::WindowFlags f = 0); + +private: + QGridLayout *layout; + QTextEdit *textEdit; + QTextBrowser *textBrowser; + +private slots: + bool textChanged(const QString& text); +}; + +class QDictMainWindow : public QMainWindow +{ + Q_OBJECT +public: + QDictMainWindow(QWidget* parent = 0, Qt::WindowFlags f = 0); + +private: + QDictWidget *dw; +}; + +#endif
benmyles/chimera
3044c1cbca42cfa4627eb523b374bab14f008a61
simpler postinstall
diff --git a/PostInstall.txt b/PostInstall.txt index e5e8b83..f1f9af8 100644 --- a/PostInstall.txt +++ b/PostInstall.txt @@ -1,18 +1,8 @@ -== CHIMERA ISSUES/NOTES: +Documentation on Chimera is available at: + http://wiki.github.com/benmyles/chimera/ -* Experimental. Not yet tested in production environment, use at your own risk. -* Only tested with Ruby 1.9. Why not upgrade? -* Test coverage needs to be improved. -* Documentation is lacking. At the moment reading the tests and sample test/models.rb - file are your best bet. - -== USEFUL LINKS: - -* Source: http://github.com/benmyles/chimera -* Docs: http://github.com/benmyles/chimera#readme -* Wiki: http://wiki.github.com/benmyles/chimera/ -* Discussion: http://groups.google.com/group/chimera-lib -* Email: ben dot myles at gmail dot com -* Twitter: benmyles +Note that Chimera is experimental and in early stages of development. Although it +has a fairly rich feature set it is not yet production tested, and could use a +more comprehensive test suite.
benmyles/chimera
ff854e0a2cd651b28a7530b9b151232ecdd84fdf
bump version
diff --git a/lib/chimera.rb b/lib/chimera.rb index 9e00d0e..c2e8481 100644 --- a/lib/chimera.rb +++ b/lib/chimera.rb @@ -1,35 +1,35 @@ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) gem 'uuidtools','= 2.1.1' gem 'activemodel','= 3.0.0.beta' gem "yajl-ruby", "= 0.7.4" gem "fast-stemmer", "= 1.0.0" gem "typhoeus", "= 0.1.22" require 'fast_stemmer' require 'digest/sha1' require 'uuidtools' require 'yajl' require 'yaml' require 'active_model' require 'active_support/all' require 'redis' require 'typhoeus' require 'riak_raw' require "chimera/error" require "chimera/attributes" require "chimera/indexes" require "chimera/geo_indexes" require "chimera/associations" require "chimera/redis_objects" require "chimera/finders" require "chimera/persistence" require "chimera/base" module Chimera - VERSION = '0.0.4' + VERSION = '0.0.5' end \ No newline at end of file diff --git a/pkg/chimera-0.0.4.gem b/pkg/chimera-0.0.4.gem index 51b0726..332909e 100644 Binary files a/pkg/chimera-0.0.4.gem and b/pkg/chimera-0.0.4.gem differ
benmyles/chimera
06e81010345f1599009c2f75764fff3eff5a76a0
fix github url in readme
diff --git a/README.rdoc b/README.rdoc index 27f4604..aacfb44 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,131 +1,131 @@ = chimera * http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). !! Chimera is alpha. It's not production tested and needs a better test suite. !! !! It's also only tested in Ruby 1.9. !! == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. * Uses Typhoeus for communicating with Riak. * Surfaces siblings from Riak so that conflicts can be managed and resolved. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Only tested with Ruby 1.9. Why not upgrade? * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :union) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :intersect) => [] You can also paginate results by specifying the left index and right index of the result set: Car.find_with_index(:description, :q => "rigid boat", :type => :intersect, :lindex => 10, :rindex => 20) * See tests for more usage examples == REQUIREMENTS: * Latest Riak from bitbucket: http://hg.basho.com/riak/wiki/Home -* Latest Redis from Git: git://github.com/pietern/redis.git +* Latest Redis from Git: http://github.com/antirez/redis * Ruby 1.9 * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == USEFUL LINKS: * Discussion: http://groups.google.com/group/chimera-lib * Email: ben dot myles at gmail dot com * Twitter: benmyles == LICENSE: (The MIT License) Copyright (c) 2010 Ben Myles 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. \ No newline at end of file
benmyles/chimera
1c5426329f5e78ce9d4b08c7172a673564f898ff
added pagination example to README
diff --git a/README.rdoc b/README.rdoc index 2fa9a8f..27f4604 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,127 +1,131 @@ = chimera * http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). !! Chimera is alpha. It's not production tested and needs a better test suite. !! !! It's also only tested in Ruby 1.9. !! == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. * Uses Typhoeus for communicating with Riak. * Surfaces siblings from Riak so that conflicts can be managed and resolved. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Only tested with Ruby 1.9. Why not upgrade? * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :union) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :intersect) => [] +You can also paginate results by specifying the left index and right index of the result set: + + Car.find_with_index(:description, :q => "rigid boat", :type => :intersect, :lindex => 10, :rindex => 20) + * See tests for more usage examples == REQUIREMENTS: * Latest Riak from bitbucket: http://hg.basho.com/riak/wiki/Home * Latest Redis from Git: git://github.com/pietern/redis.git * Ruby 1.9 * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == USEFUL LINKS: * Discussion: http://groups.google.com/group/chimera-lib * Email: ben dot myles at gmail dot com * Twitter: benmyles == LICENSE: (The MIT License) Copyright (c) 2010 Ben Myles 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. \ No newline at end of file
benmyles/chimera
9235f7e2d691669b2dbe3d7d1cd59babfcf7884b
implemented MAX_FINDER_THREADS
diff --git a/lib/chimera.rb b/lib/chimera.rb index 197bec2..9e00d0e 100644 --- a/lib/chimera.rb +++ b/lib/chimera.rb @@ -1,34 +1,35 @@ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) gem 'uuidtools','= 2.1.1' gem 'activemodel','= 3.0.0.beta' gem "yajl-ruby", "= 0.7.4" gem "fast-stemmer", "= 1.0.0" gem "typhoeus", "= 0.1.22" require 'fast_stemmer' require 'digest/sha1' require 'uuidtools' require 'yajl' require 'yaml' require 'active_model' +require 'active_support/all' require 'redis' require 'typhoeus' require 'riak_raw' require "chimera/error" require "chimera/attributes" require "chimera/indexes" require "chimera/geo_indexes" require "chimera/associations" require "chimera/redis_objects" require "chimera/finders" require "chimera/persistence" require "chimera/base" module Chimera VERSION = '0.0.4' end \ No newline at end of file diff --git a/lib/chimera/finders.rb b/lib/chimera/finders.rb index 4be3a02..aee3c42 100644 --- a/lib/chimera/finders.rb +++ b/lib/chimera/finders.rb @@ -1,61 +1,65 @@ module Chimera module Finders + MAX_FINDER_THREADS = 20 + def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def each self.find_with_index(:all) { |obj| yield(obj) } end def find(key,opts={}) find_many([[key,opts]])[0] end def find_many(key_opts_arr) found = [] - threads = [] key_opts_arr = Array(key_opts_arr).collect { |e| Array(e) } - key_opts_arr.each do |key,opts| - opts ||= {} - threads << Thread.new do - if key - resp = self.connection(:riak_raw).fetch(self.to_s, key, opts) - case resp.code - when 300 then - # siblings - obj = self.new({},key,false) - obj.riak_response = resp - obj.load_sibling_attributes - found << obj - when 200 then - if resp.body and yaml_hash = YAML.load(resp.body) - hash = {} - yaml_hash.each { |k,v| hash[k.to_sym] = v } - obj = self.new(hash,key,false) - obj.riak_response = resp - found << obj - else + key_opts_arr.in_groups_of(Chimera::Finders::MAX_FINDER_THREADS).each do |key_opts_arr_group| + threads = [] + key_opts_arr_group.compact.each do |key,opts| + opts ||= {} + threads << Thread.new do + if key + resp = self.connection(:riak_raw).fetch(self.to_s, key, opts) + case resp.code + when 300 then + # siblings obj = self.new({},key,false) obj.riak_response = resp + obj.load_sibling_attributes found << obj - end - when 404 then - nil - else - raise(Chimera::Error::UnhandledRiakResponseCode.new(resp.code.to_s)) - end # case - end - end # Thread.new - end # keys.each - threads.each { |th| th.join } + when 200 then + if resp.body and yaml_hash = YAML.load(resp.body) + hash = {} + yaml_hash.each { |k,v| hash[k.to_sym] = v } + obj = self.new(hash,key,false) + obj.riak_response = resp + found << obj + else + obj = self.new({},key,false) + obj.riak_response = resp + found << obj + end + when 404 then + nil + else + raise(Chimera::Error::UnhandledRiakResponseCode.new(resp.code.to_s)) + end # case + end + end # Thread.new + end # key_opts_arr_group.each + threads.each { |th| th.join } + end # key_opts_arr.in_groups_of(10).each do |key_opts_arr_group| found end # find_many end # ClassMethods module InstanceMethods end # InstanceMethods end end \ No newline at end of file diff --git a/lib/chimera/indexes.rb b/lib/chimera/indexes.rb index db454b0..223b9d9 100644 --- a/lib/chimera/indexes.rb +++ b/lib/chimera/indexes.rb @@ -1,196 +1,196 @@ module Chimera module Indexes SEARCH_EXCLUDE_LIST = %w(a an and as at but by for in into of on onto to the) def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def defined_indexes @defined_indexes || {} end # available types include: # find, unique, search, geo def index(name, type = :find) @defined_indexes ||= {} @defined_indexes[name.to_sym] = type end def find_with_index(name, opts_or_query=nil) if opts_or_query.is_a?(Hash) q = opts_or_query[:q].to_s offset = opts_or_query[:offset] || opts_or_query[:lindex] || 0 limit = opts_or_query[:limit] || opts_or_query[:rindex] || -1 else q = opts_or_query.to_s offset = 0 limit = -1 end if name.to_sym == :all llen = self.connection(:redis).llen(self.key_for_all_index) limit = llen if limit > llen || limit == -1 curr = offset while(curr < limit) max_index = [curr+9,limit-1].min keys = self.connection(:redis).lrange(self.key_for_all_index, curr, max_index).compact - find_many(keys).each { |obj| yield(obj) } + self.find_many(keys).each { |obj| yield(obj) } curr += 10 end elsif props = self.defined_indexes[name.to_sym] case props[:type] when :find then if q and !q.blank? index_key = self.key_for_index(:find, name, q) self.find_many(self.connection(:redis).zrange(index_key, offset, limit)) end when :unique then if q and !q.blank? index_key = self.key_for_index(:unique, name, q) Array(self.find(self.connection(:redis).get(index_key))) end when :search then if opts_or_query.is_a?(Hash) opts_or_query[:type] ||= :intersect end keys = [] q.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) keys << self.key_for_index(:search, name, word) end if keys.size > 0 result_set_key = UUIDTools::UUID.random_create.to_s if opts_or_query.is_a?(Hash) and opts_or_query[:type] == :union #self.find_many(self.connection(:redis).sunion(keys.join(" "))) self.connection(:redis).zunion(result_set_key, keys.size, keys.join(" ")) else #self.find_many(self.connection(:redis).sinter(keys.join(" "))) self.connection(:redis).zinter(result_set_key, keys.size, keys.join(" ")) end results = self.find_many(self.connection(:redis).zrange(result_set_key, offset, limit)) self.connection(:redis).del(result_set_key) results end # if keys.size when :geo then find_with_geo_index(name, opts_or_query) end # case end # if props end def key_for_index(type, name, val) case type.to_sym when :find, :unique, :search then "#{self.to_s}::Indexes::#{type}::#{name}::#{digest(val)}" end end def key_for_all_index "#{self.to_s}::Indexes::All" end def digest(val) Digest::SHA1.hexdigest(val) end end # ClassMethods module InstanceMethods def destroy_indexes remove_from_all_index self.class.defined_indexes.each do |name, props| case props[:type] when :find then if val = @orig_attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:find, name,val.to_s) self.class.connection(:redis).zrem(index_key, self.id) end when :unique then if val = @orig_attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) self.class.connection(:redis).del(index_key) end when :search then if val = @orig_attributes[name.to_sym] and !val.blank? val.to_s.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) index_key = self.class.key_for_index(:search, name, word) #self.class.connection(:redis).srem(index_key, self.id) self.class.connection(:redis).zrem(index_key, self.id) end end end end destroy_geo_indexes end def check_index_constraints self.class.defined_indexes.each do |name, props| case props[:type] when :unique then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) if k = self.class.connection(:redis).get(index_key) if k.to_s != self.id.to_s raise(Chimera::Error::UniqueConstraintViolation, val) end end end # if val end # case end end def create_indexes add_to_all_index self.class.defined_indexes.each do |name, props| case props[:type] when :find then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:find, name, val.to_s) self.class.connection(:redis).zadd(index_key, Time.now.utc.to_f, self.id) end when :unique then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) if self.class.connection(:redis).exists(index_key) raise(Chimera::Error::UniqueConstraintViolation, val) else self.class.connection(:redis).set(index_key, self.id) end end when :search then if val = @attributes[name.to_sym] and !val.blank? val.to_s.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) index_key = self.class.key_for_index(:search, name, word) #self.class.connection(:redis).sadd(index_key, self.id) self.class.connection(:redis).zadd(index_key, Time.now.utc.to_f, self.id) end end end end create_geo_indexes end def update_indexes destroy_indexes destroy_geo_indexes create_indexes create_geo_indexes end def remove_from_all_index self.class.connection(:redis).lrem(self.class.key_for_all_index, 0, self.id) end def add_to_all_index self.class.connection(:redis).lpush(self.class.key_for_all_index, self.id) end end # InstanceMethods end end \ No newline at end of file
benmyles/chimera
d4195786d406706ba5136d585ede39b95a239712
all indexes and associations now support paging
diff --git a/lib/chimera/indexes.rb b/lib/chimera/indexes.rb index 4a55605..db454b0 100644 --- a/lib/chimera/indexes.rb +++ b/lib/chimera/indexes.rb @@ -1,183 +1,196 @@ module Chimera module Indexes SEARCH_EXCLUDE_LIST = %w(a an and as at but by for in into of on onto to the) def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def defined_indexes @defined_indexes || {} end # available types include: # find, unique, search, geo def index(name, type = :find) @defined_indexes ||= {} @defined_indexes[name.to_sym] = type end def find_with_index(name, opts_or_query=nil) if opts_or_query.is_a?(Hash) q = opts_or_query[:q].to_s - offset = opts_or_query[:offset] || 0 - limit = opts_or_query[:limit] || -1 + offset = opts_or_query[:offset] || opts_or_query[:lindex] || 0 + limit = opts_or_query[:limit] || opts_or_query[:rindex] || -1 else q = opts_or_query.to_s offset = 0 limit = -1 end + if name.to_sym == :all llen = self.connection(:redis).llen(self.key_for_all_index) - limit = llen if limit > llen + limit = llen if limit > llen || limit == -1 curr = offset while(curr < limit) max_index = [curr+9,limit-1].min keys = self.connection(:redis).lrange(self.key_for_all_index, curr, max_index).compact find_many(keys).each { |obj| yield(obj) } curr += 10 end elsif props = self.defined_indexes[name.to_sym] case props[:type] when :find then if q and !q.blank? index_key = self.key_for_index(:find, name, q) - self.find_many(self.connection(:redis).smembers(index_key)) + self.find_many(self.connection(:redis).zrange(index_key, offset, limit)) end when :unique then if q and !q.blank? index_key = self.key_for_index(:unique, name, q) Array(self.find(self.connection(:redis).get(index_key))) end when :search then + if opts_or_query.is_a?(Hash) + opts_or_query[:type] ||= :intersect + end + keys = [] q.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) keys << self.key_for_index(:search, name, word) end if keys.size > 0 + result_set_key = UUIDTools::UUID.random_create.to_s if opts_or_query.is_a?(Hash) and opts_or_query[:type] == :union - self.find_many(self.connection(:redis).sunion(keys.join(" "))) + #self.find_many(self.connection(:redis).sunion(keys.join(" "))) + self.connection(:redis).zunion(result_set_key, keys.size, keys.join(" ")) else - self.find_many(self.connection(:redis).sinter(keys.join(" "))) + #self.find_many(self.connection(:redis).sinter(keys.join(" "))) + self.connection(:redis).zinter(result_set_key, keys.size, keys.join(" ")) end - end + results = self.find_many(self.connection(:redis).zrange(result_set_key, offset, limit)) + self.connection(:redis).del(result_set_key) + results + end # if keys.size when :geo then find_with_geo_index(name, opts_or_query) end # case end # if props end def key_for_index(type, name, val) case type.to_sym when :find, :unique, :search then "#{self.to_s}::Indexes::#{type}::#{name}::#{digest(val)}" end end def key_for_all_index "#{self.to_s}::Indexes::All" end def digest(val) Digest::SHA1.hexdigest(val) end end # ClassMethods module InstanceMethods def destroy_indexes remove_from_all_index self.class.defined_indexes.each do |name, props| case props[:type] when :find then if val = @orig_attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:find, name,val.to_s) - self.class.connection(:redis).srem(index_key, self.id) + self.class.connection(:redis).zrem(index_key, self.id) end when :unique then if val = @orig_attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) self.class.connection(:redis).del(index_key) end when :search then if val = @orig_attributes[name.to_sym] and !val.blank? val.to_s.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) index_key = self.class.key_for_index(:search, name, word) - self.class.connection(:redis).srem(index_key, self.id) + #self.class.connection(:redis).srem(index_key, self.id) + self.class.connection(:redis).zrem(index_key, self.id) end end end end destroy_geo_indexes end def check_index_constraints self.class.defined_indexes.each do |name, props| case props[:type] when :unique then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) if k = self.class.connection(:redis).get(index_key) if k.to_s != self.id.to_s raise(Chimera::Error::UniqueConstraintViolation, val) end end end # if val end # case end end def create_indexes add_to_all_index self.class.defined_indexes.each do |name, props| case props[:type] when :find then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:find, name, val.to_s) - self.class.connection(:redis).sadd(index_key, self.id) + self.class.connection(:redis).zadd(index_key, Time.now.utc.to_f, self.id) end when :unique then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) if self.class.connection(:redis).exists(index_key) raise(Chimera::Error::UniqueConstraintViolation, val) else self.class.connection(:redis).set(index_key, self.id) end end when :search then if val = @attributes[name.to_sym] and !val.blank? val.to_s.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) index_key = self.class.key_for_index(:search, name, word) - self.class.connection(:redis).sadd(index_key, self.id) + #self.class.connection(:redis).sadd(index_key, self.id) + self.class.connection(:redis).zadd(index_key, Time.now.utc.to_f, self.id) end end end end create_geo_indexes end def update_indexes destroy_indexes destroy_geo_indexes create_indexes create_geo_indexes end def remove_from_all_index self.class.connection(:redis).lrem(self.class.key_for_all_index, 0, self.id) end def add_to_all_index self.class.connection(:redis).lpush(self.class.key_for_all_index, self.id) end end # InstanceMethods end end \ No newline at end of file diff --git a/test/test_chimera.rb b/test/test_chimera.rb index 3514e58..0177932 100644 --- a/test/test_chimera.rb +++ b/test/test_chimera.rb @@ -1,299 +1,316 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestChimera < Test::Unit::TestCase def setup Car.each { |c| c.destroy } Car.connection(:redis).flush_all Car.allow_multi = true end def test_geo_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.id = Car.new_uuid c.curr_location = [37.12122, 121.43392] assert c.save c2 = Car.new c2.make = "Toyota" c2.model = "Hilux" c2.year = 2010 c2.sku = 1001 c2.curr_location = [37.12222, 121.43792] c2.id = Car.new_uuid assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c,c2].sort, found.sort c2.curr_location = [38.0, 122.0] assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c].sort, found.sort found = Car.find_with_index(:curr_location, {:coordinate => [38.0-0.05, 122.0+0.05], :steps => 5}) assert_equal [c2].sort, found.sort end def test_search_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.comments = "cat dog chicken dolphin whale panther" c.id = Car.new_uuid assert c.save c2 = Car.new c2.make = "Porsche" c2.model = "911" c2.year = 2010 c2.sku = 1001 c2.comments = "cat dog chicken" c2.id = Car.new_uuid assert c2.save c3 = Car.new c3.make = "Porsche" c3.model = "911" c3.year = 2010 c3.sku = 1002 c3.comments = "dog chicken dolphin whale" c3.id = Car.new_uuid assert c3.save assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, "dog").sort + + assert_equal [c,c2].sort, Car.find_with_index(:comments, {:q => "dog", :type => :intersect, :lindex => 0, :rindex => 1}).sort + assert_equal [c,c2].sort, Car.find_with_index(:comments, {:q => "dog chicken cat", :lindex => 0, :rindex => 1}).sort + assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :union}).sort assert_equal [c,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :intersect}).sort end def test_indexes c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert !c.new? assert_equal [c], Car.find_with_index(:comments, "fast") assert_equal [c], Car.find_with_index(:comments, "purple") assert_equal [], Car.find_with_index(:comments, "blue") assert_equal [c], Car.find_with_index(:year, 2010) assert_equal [c], Car.find_with_index(:sku, 1001) c2 = Car.new c2.make = "Honda" c2.model = "Accord" c2.year = 2010 c2.sku = 1001 c2.id = Car.new_uuid assert_raise(Chimera::Error::UniqueConstraintViolation) { c2.save } c2.sku = 1002 assert c2.save c3 = Car.new c3.make = "Honda" c3.model = "Civic" c3.year = 2010 c3.sku = 1003 c3.id = Car.new_uuid assert c3.save assert_equal 3, Car.find_with_index(:year, 2010).size assert Car.find_with_index(:year, 2010).include?(c) assert Car.find_with_index(:year, 2010).include?(c2) assert Car.find_with_index(:year, 2010).include?(c3) count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 3, count count = 0 Car.each { |car| count += 1 } assert_equal 3, count c2.destroy count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 2, count count = 0 Car.each { |car| count += 1 } assert_equal 2, count end def test_associations u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_equal 0, u.friends.size chris = User.new chris.id = User.new_uuid chris.name = "Chris" assert chris.save assert_equal 0, u.friends.size u.friends << chris assert_equal 1, u.friends.size chris.destroy assert_equal 0, u.friends.size c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert_equal 0, u.cars.size u.cars << c assert_equal 1, u.cars.size assert_equal [c], u.cars.all assert_equal 1, c.association_memberships.all_associations.size u.cars.remove(c) assert_equal 0, c.association_memberships.all_associations.size end def test_model_attribute u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_nil u.favorite_car c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save u.favorite_car = c assert u.save assert_equal c, u.favorite_car u = User.find(u.id) assert_equal c, u.favorite_car u.favorite_car = nil assert u.save assert_nil u.favorite_car u.favorite_car = c assert u.save assert_equal c, u.favorite_car c.destroy assert_equal c, u.favorite_car u = User.find(u.id) assert_nil u.favorite_car end def test_redis_objects u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_equal false, User.connection(:redis).exists(u.num_logins.key) assert_equal 0, u.num_logins.count u.num_logins.incr assert_equal 1, u.num_logins.count assert_equal true, User.connection(:redis).exists(u.num_logins.key) u.num_logins.incr_by 10 assert_equal 11, u.num_logins.count u.destroy assert_equal false, User.connection(:redis).exists(u.num_logins.key) end def test_rich_attributes u = User.new u.id = User.new_uuid u.updated_at = Time.now.utc assert u.updated_at.is_a?(Time) u.name = "ben" assert u.save u = User.find(u.id) assert u.updated_at.is_a?(Time) end # see http://blog.basho.com/2010/01/29/why-vector-clocks-are-easy/ def test_conflicts Car.connection(:riak_raw).client_id = "Client1" c = Car.new c.id = Car.new_uuid c.make = "Nissan" c.model = "Versa" c.year = 2009 assert c.save c2 = c.clone Car.connection(:riak_raw).client_id = "Client2" c2.year = 2008 assert c2.save assert !c2.in_conflict? Car.connection(:riak_raw).client_id = "Client3" c.year = 2007 assert c.save assert c.in_conflict? assert_raise(Chimera::Error::CannotSaveWithConflicts) { c.save } c2 = Car.find(c.id) assert_raise(Chimera::Error::CannotSaveWithConflicts) { c2.save } c.attributes = c.sibling_attributes.first[1].dup c.year = 2006 assert c.resolve_and_save assert !c.in_conflict? c = Car.find(c.id) assert !c.in_conflict? assert_equal 2006, c.year end def test_limits_on_associations u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save 1.upto(33) do |i| c = Car.new c.id = Car.new_uuid c.make = "Nissan #{i}" c.model = "Versa #{i}" c.year = 2009 assert c.save u.cars << c end assert_equal 33, u.cars.all.size assert_equal 25, u.cars.all(0,25).size assert_equal 7, u.cars.all(10,17).size assert_equal 1, u.cars.all(0,1).size end + + def test_zinter + redis = User.connection(:redis) + redis.zadd("zset0",0,"key0") + redis.zadd("zset0",1,"key1") + redis.zadd("zset0",2,"key2") + + redis.zadd("zset1",0,"key2") + redis.zadd("zset1",5,"key5") + + redis.zinter("zset3","2","zset0","zset1") + assert_equal ["key2"], redis.zrange("zset3","0","-1") + end end
benmyles/chimera
d797b81dc7aaf83d3a4b79260c33c6ab712022ea
paging for :all indexes
diff --git a/lib/chimera/indexes.rb b/lib/chimera/indexes.rb index c739911..4a55605 100644 --- a/lib/chimera/indexes.rb +++ b/lib/chimera/indexes.rb @@ -1,177 +1,183 @@ module Chimera module Indexes SEARCH_EXCLUDE_LIST = %w(a an and as at but by for in into of on onto to the) def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def defined_indexes @defined_indexes || {} end # available types include: # find, unique, search, geo def index(name, type = :find) @defined_indexes ||= {} @defined_indexes[name.to_sym] = type end def find_with_index(name, opts_or_query=nil) if opts_or_query.is_a?(Hash) q = opts_or_query[:q].to_s + offset = opts_or_query[:offset] || 0 + limit = opts_or_query[:limit] || -1 else q = opts_or_query.to_s + offset = 0 + limit = -1 end if name.to_sym == :all llen = self.connection(:redis).llen(self.key_for_all_index) - curr = 0 - while(curr < llen) - keys = self.connection(:redis).lrange(self.key_for_all_index, curr, curr+9).compact + limit = llen if limit > llen + curr = offset + while(curr < limit) + max_index = [curr+9,limit-1].min + keys = self.connection(:redis).lrange(self.key_for_all_index, curr, max_index).compact find_many(keys).each { |obj| yield(obj) } curr += 10 end elsif props = self.defined_indexes[name.to_sym] case props[:type] when :find then if q and !q.blank? index_key = self.key_for_index(:find, name, q) self.find_many(self.connection(:redis).smembers(index_key)) end when :unique then if q and !q.blank? index_key = self.key_for_index(:unique, name, q) Array(self.find(self.connection(:redis).get(index_key))) end when :search then keys = [] q.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) keys << self.key_for_index(:search, name, word) end if keys.size > 0 if opts_or_query.is_a?(Hash) and opts_or_query[:type] == :union self.find_many(self.connection(:redis).sunion(keys.join(" "))) else self.find_many(self.connection(:redis).sinter(keys.join(" "))) end end when :geo then find_with_geo_index(name, opts_or_query) end # case end # if props end def key_for_index(type, name, val) case type.to_sym when :find, :unique, :search then "#{self.to_s}::Indexes::#{type}::#{name}::#{digest(val)}" end end def key_for_all_index "#{self.to_s}::Indexes::All" end def digest(val) Digest::SHA1.hexdigest(val) end end # ClassMethods module InstanceMethods def destroy_indexes remove_from_all_index self.class.defined_indexes.each do |name, props| case props[:type] when :find then if val = @orig_attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:find, name,val.to_s) self.class.connection(:redis).srem(index_key, self.id) end when :unique then if val = @orig_attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) self.class.connection(:redis).del(index_key) end when :search then if val = @orig_attributes[name.to_sym] and !val.blank? val.to_s.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) index_key = self.class.key_for_index(:search, name, word) self.class.connection(:redis).srem(index_key, self.id) end end end end destroy_geo_indexes end def check_index_constraints self.class.defined_indexes.each do |name, props| case props[:type] when :unique then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) if k = self.class.connection(:redis).get(index_key) if k.to_s != self.id.to_s raise(Chimera::Error::UniqueConstraintViolation, val) end end end # if val end # case end end def create_indexes add_to_all_index self.class.defined_indexes.each do |name, props| case props[:type] when :find then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:find, name, val.to_s) self.class.connection(:redis).sadd(index_key, self.id) end when :unique then if val = @attributes[name.to_sym] and !val.blank? index_key = self.class.key_for_index(:unique, name,val.to_s) if self.class.connection(:redis).exists(index_key) raise(Chimera::Error::UniqueConstraintViolation, val) else self.class.connection(:redis).set(index_key, self.id) end end when :search then if val = @attributes[name.to_sym] and !val.blank? val.to_s.split(" ").each do |word| word = word.downcase.stem next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) index_key = self.class.key_for_index(:search, name, word) self.class.connection(:redis).sadd(index_key, self.id) end end end end create_geo_indexes end def update_indexes destroy_indexes destroy_geo_indexes create_indexes create_geo_indexes end def remove_from_all_index self.class.connection(:redis).lrem(self.class.key_for_all_index, 0, self.id) end def add_to_all_index self.class.connection(:redis).lpush(self.class.key_for_all_index, self.id) end end # InstanceMethods end end \ No newline at end of file
benmyles/chimera
a153f4a8aa3cc6a182e18be41fb4b86b7d9193ae
implemented paging for associations
diff --git a/lib/chimera/associations.rb b/lib/chimera/associations.rb index 34c11ab..301f579 100644 --- a/lib/chimera/associations.rb +++ b/lib/chimera/associations.rb @@ -1,148 +1,148 @@ module Chimera module Associations def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def defined_associations @defined_associations || {} end # association :friends, User def association(name, class_sym) @defined_associations ||= {} @defined_associations[name.to_sym] = class_sym define_method("#{name}") do @associations ||= {} @associations[name] ||= Chimera::AssociationProxies::Association.new(self,name,class_sym) end end end # ClassMethods module InstanceMethods def destroy_associations (@associations || {}).each do |name, association| association.destroy end end def association_memberships @association_memberships ||= Chimera::AssociationProxies::AssociationMemberships.new(self) end end # InstanceMethods end module AssociationProxies class AssociationMemberships attr_accessor :model def initialize(_model) @model = _model end def key "#{model.class.to_s}::AssociationProxies::AssociationMemberships::#{model.id}" end def add(assoc_key) self.model.class.connection(:redis).lpush(self.key, assoc_key) end def remove(assoc_key) self.model.class.connection(:redis).lrem(self.key, 0, assoc_key) end def destroy remove_from_all_associations self.model.class.connection(:redis).del(self.key) end def remove_from_all_associations self.each_association { |assoc| assoc.remove(self.model) } end def each_association llen = self.model.class.connection(:redis).llen(self.key) 0.upto(llen-1) do |i| assoc_key = self.model.class.connection(:redis).lindex(self.key, i) yield Chimera::AssociationProxies::Association.find(assoc_key) end true end def all_associations all = []; self.each_association { |ass| all << ass }; all end end class Association attr_accessor :model, :name, :klass def self.find(assoc_key) parts = assoc_key.split("::") model_klass = parts[0] name = parts[3] assoc_klass = parts[4] model_id = parts[5] self.new(eval(model_klass).find(model_id), name, assoc_klass.to_sym) end def initialize(_model, _name, class_sym) @model = _model @name = _name @klass = eval(class_sym.to_s.camelize) raise(Chimera::Error::MissingId) unless model.id end def key "#{model.class.to_s}::AssociationProxies::Association::#{name}::#{klass.to_s}::#{model.id}" end def <<(obj) raise(Chimera::Error::AssociationClassMismatch) unless obj.class.to_s == self.klass.to_s self.model.class.connection(:redis).lpush(self.key, obj.id) obj.association_memberships.add(self.key) true end def remove(obj) raise(Chimera::Error::AssociationClassMismatch) unless obj.class.to_s == self.klass.to_s self.model.class.connection(:redis).lrem(self.key, 0, obj.id) obj.association_memberships.remove(self.key) true end def size self.model.class.connection(:redis).llen(self.key) end - def each(limit=nil) + def each(offset=0, limit=nil) llen = self.model.class.connection(:redis).llen(self.key) limit ||= llen - curr = 0 + curr = offset while(curr < limit) max_index = [curr+9,limit-1].min keys = self.model.class.connection(:redis).lrange(self.key, curr, max_index).compact self.klass.find_many(keys).each { |obj| yield(obj) } curr += 10 end true end - def all - found = []; self.each { |o| found << o }; found + def all(offset=0, limit=nil) + found = []; self.each(offset,limit) { |o| found << o }; found end def destroy(delete_associated=true) if delete_associated == true self.each { |obj| obj.destroy } else self.each { |obj| obj.association_memberships.remove(self.key) } end self.model.class.connection(:redis).del(self.key) end end # Association end # AssociationProxies end \ No newline at end of file diff --git a/pkg/chimera-0.0.4.gem b/pkg/chimera-0.0.4.gem new file mode 100644 index 0000000..51b0726 Binary files /dev/null and b/pkg/chimera-0.0.4.gem differ diff --git a/test/test_chimera.rb b/test/test_chimera.rb index 8b2b03d..3514e58 100644 --- a/test/test_chimera.rb +++ b/test/test_chimera.rb @@ -1,277 +1,299 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestChimera < Test::Unit::TestCase def setup Car.each { |c| c.destroy } Car.connection(:redis).flush_all Car.allow_multi = true end def test_geo_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.id = Car.new_uuid c.curr_location = [37.12122, 121.43392] assert c.save c2 = Car.new c2.make = "Toyota" c2.model = "Hilux" c2.year = 2010 c2.sku = 1001 c2.curr_location = [37.12222, 121.43792] c2.id = Car.new_uuid assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c,c2].sort, found.sort c2.curr_location = [38.0, 122.0] assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c].sort, found.sort found = Car.find_with_index(:curr_location, {:coordinate => [38.0-0.05, 122.0+0.05], :steps => 5}) assert_equal [c2].sort, found.sort end def test_search_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.comments = "cat dog chicken dolphin whale panther" c.id = Car.new_uuid assert c.save c2 = Car.new c2.make = "Porsche" c2.model = "911" c2.year = 2010 c2.sku = 1001 c2.comments = "cat dog chicken" c2.id = Car.new_uuid assert c2.save c3 = Car.new c3.make = "Porsche" c3.model = "911" c3.year = 2010 c3.sku = 1002 c3.comments = "dog chicken dolphin whale" c3.id = Car.new_uuid assert c3.save assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, "dog").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :union}).sort assert_equal [c,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :intersect}).sort end def test_indexes c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert !c.new? assert_equal [c], Car.find_with_index(:comments, "fast") assert_equal [c], Car.find_with_index(:comments, "purple") assert_equal [], Car.find_with_index(:comments, "blue") assert_equal [c], Car.find_with_index(:year, 2010) assert_equal [c], Car.find_with_index(:sku, 1001) c2 = Car.new c2.make = "Honda" c2.model = "Accord" c2.year = 2010 c2.sku = 1001 c2.id = Car.new_uuid assert_raise(Chimera::Error::UniqueConstraintViolation) { c2.save } c2.sku = 1002 assert c2.save c3 = Car.new c3.make = "Honda" c3.model = "Civic" c3.year = 2010 c3.sku = 1003 c3.id = Car.new_uuid assert c3.save assert_equal 3, Car.find_with_index(:year, 2010).size assert Car.find_with_index(:year, 2010).include?(c) assert Car.find_with_index(:year, 2010).include?(c2) assert Car.find_with_index(:year, 2010).include?(c3) count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 3, count count = 0 Car.each { |car| count += 1 } assert_equal 3, count c2.destroy count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 2, count count = 0 Car.each { |car| count += 1 } assert_equal 2, count end def test_associations u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_equal 0, u.friends.size chris = User.new chris.id = User.new_uuid chris.name = "Chris" assert chris.save assert_equal 0, u.friends.size u.friends << chris assert_equal 1, u.friends.size chris.destroy assert_equal 0, u.friends.size c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert_equal 0, u.cars.size u.cars << c assert_equal 1, u.cars.size assert_equal [c], u.cars.all assert_equal 1, c.association_memberships.all_associations.size u.cars.remove(c) assert_equal 0, c.association_memberships.all_associations.size end def test_model_attribute u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_nil u.favorite_car c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save u.favorite_car = c assert u.save assert_equal c, u.favorite_car u = User.find(u.id) assert_equal c, u.favorite_car u.favorite_car = nil assert u.save assert_nil u.favorite_car u.favorite_car = c assert u.save assert_equal c, u.favorite_car c.destroy assert_equal c, u.favorite_car u = User.find(u.id) assert_nil u.favorite_car end def test_redis_objects u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_equal false, User.connection(:redis).exists(u.num_logins.key) assert_equal 0, u.num_logins.count u.num_logins.incr assert_equal 1, u.num_logins.count assert_equal true, User.connection(:redis).exists(u.num_logins.key) u.num_logins.incr_by 10 assert_equal 11, u.num_logins.count u.destroy assert_equal false, User.connection(:redis).exists(u.num_logins.key) end def test_rich_attributes u = User.new u.id = User.new_uuid u.updated_at = Time.now.utc assert u.updated_at.is_a?(Time) u.name = "ben" assert u.save u = User.find(u.id) assert u.updated_at.is_a?(Time) end # see http://blog.basho.com/2010/01/29/why-vector-clocks-are-easy/ def test_conflicts Car.connection(:riak_raw).client_id = "Client1" c = Car.new c.id = Car.new_uuid c.make = "Nissan" c.model = "Versa" c.year = 2009 assert c.save c2 = c.clone Car.connection(:riak_raw).client_id = "Client2" c2.year = 2008 assert c2.save assert !c2.in_conflict? Car.connection(:riak_raw).client_id = "Client3" c.year = 2007 assert c.save assert c.in_conflict? assert_raise(Chimera::Error::CannotSaveWithConflicts) { c.save } c2 = Car.find(c.id) assert_raise(Chimera::Error::CannotSaveWithConflicts) { c2.save } c.attributes = c.sibling_attributes.first[1].dup c.year = 2006 assert c.resolve_and_save assert !c.in_conflict? c = Car.find(c.id) assert !c.in_conflict? assert_equal 2006, c.year end + + def test_limits_on_associations + u = User.new + u.id = User.new_uuid + u.name = "Ben" + assert u.save + + 1.upto(33) do |i| + c = Car.new + c.id = Car.new_uuid + c.make = "Nissan #{i}" + c.model = "Versa #{i}" + c.year = 2009 + assert c.save + u.cars << c + end + + assert_equal 33, u.cars.all.size + assert_equal 25, u.cars.all(0,25).size + assert_equal 7, u.cars.all(10,17).size + assert_equal 1, u.cars.all(0,1).size + end end
benmyles/chimera
18d8f861d8398625056330e17fcd6e51e3f631a3
dont bundle typhoeus
diff --git a/Manifest.txt b/Manifest.txt index 4212f2b..7eb5079 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,57 +1,45 @@ doc/examples/config.yml doc/NOTES doc/redis6379.conf History.txt lib/chimera/associations.rb lib/chimera/attributes.rb lib/chimera/base.rb lib/chimera/config.rb lib/chimera/error.rb lib/chimera/finders.rb lib/chimera/geo_indexes.rb lib/chimera/indexes.rb lib/chimera/persistence.rb lib/chimera/redis_objects.rb lib/chimera.rb lib/redis/counter.rb lib/redis/dist_redis.rb lib/redis/hash_ring.rb lib/redis/helpers lib/redis/helpers/core_commands.rb lib/redis/helpers/serialize.rb lib/redis/list.rb lib/redis/lock.rb lib/redis/objects lib/redis/objects/counters.rb lib/redis/objects/lists.rb lib/redis/objects/locks.rb lib/redis/objects/sets.rb lib/redis/objects/values.rb lib/redis/objects.rb lib/redis/pipeline.rb lib/redis/set.rb lib/redis/value.rb lib/redis.rb lib/riak_raw.rb -lib/typhoeus/.gitignore -lib/typhoeus/easy.rb -lib/typhoeus/filter.rb -lib/typhoeus/hydra.rb -lib/typhoeus/multi.rb -lib/typhoeus/remote.rb -lib/typhoeus/remote_method.rb -lib/typhoeus/remote_proxy_object.rb -lib/typhoeus/request.rb -lib/typhoeus/response.rb -lib/typhoeus/service.rb -lib/typhoeus.rb Manifest.txt PostInstall.txt Rakefile README.rdoc script/console script/destroy script/generate test/models.rb test/test_chimera.rb test/test_helper.rb diff --git a/Rakefile b/Rakefile index e227c10..cb9d9cc 100644 --- a/Rakefile +++ b/Rakefile @@ -1,30 +1,31 @@ require 'rubygems' gem 'hoe', '>= 2.1.0' require 'hoe' require 'fileutils' require './lib/chimera' Hoe.plugin :newgem # Hoe.plugin :website # Hoe.plugin :cucumberfeatures # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) $hoe = Hoe.spec 'chimera' do self.developer 'Ben Myles', '[email protected]' self.post_install_message = 'PostInstall.txt' # TODO remove if post-install message not required self.rubyforge_name = self.name # TODO this is default value # self.extra_deps = [['activesupport','>= 2.0.2']] self.extra_deps = [["activesupport","= 3.0.0.beta"], ["uuidtools","= 2.1.1"], ["activemodel",'= 3.0.0.beta'], ["yajl-ruby","= 0.7.4"], - ["fast-stemmer", "= 1.0.0"]] + ["fast-stemmer", "= 1.0.0"], + ["typhoeus", "= 0.1.22"]] end require 'newgem/tasks' Dir['tasks/**/*.rake'].each { |t| load t } # TODO - want other tests/tasks run by default? Add them to the list # remove_task :default # task :default => [:spec, :features] diff --git a/lib/chimera.rb b/lib/chimera.rb index a5c5755..197bec2 100644 --- a/lib/chimera.rb +++ b/lib/chimera.rb @@ -1,33 +1,34 @@ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) gem 'uuidtools','= 2.1.1' gem 'activemodel','= 3.0.0.beta' gem "yajl-ruby", "= 0.7.4" gem "fast-stemmer", "= 1.0.0" +gem "typhoeus", "= 0.1.22" require 'fast_stemmer' require 'digest/sha1' require 'uuidtools' require 'yajl' require 'yaml' require 'active_model' require 'redis' require 'typhoeus' require 'riak_raw' require "chimera/error" require "chimera/attributes" require "chimera/indexes" require "chimera/geo_indexes" require "chimera/associations" require "chimera/redis_objects" require "chimera/finders" require "chimera/persistence" require "chimera/base" module Chimera VERSION = '0.0.4' end \ No newline at end of file diff --git a/lib/chimera/associations.rb b/lib/chimera/associations.rb index cce33c0..34c11ab 100644 --- a/lib/chimera/associations.rb +++ b/lib/chimera/associations.rb @@ -1,146 +1,148 @@ module Chimera module Associations def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def defined_associations @defined_associations || {} end # association :friends, User def association(name, class_sym) @defined_associations ||= {} @defined_associations[name.to_sym] = class_sym define_method("#{name}") do @associations ||= {} @associations[name] ||= Chimera::AssociationProxies::Association.new(self,name,class_sym) end end end # ClassMethods module InstanceMethods def destroy_associations (@associations || {}).each do |name, association| association.destroy end end def association_memberships @association_memberships ||= Chimera::AssociationProxies::AssociationMemberships.new(self) end end # InstanceMethods end module AssociationProxies class AssociationMemberships attr_accessor :model def initialize(_model) @model = _model end def key "#{model.class.to_s}::AssociationProxies::AssociationMemberships::#{model.id}" end def add(assoc_key) self.model.class.connection(:redis).lpush(self.key, assoc_key) end def remove(assoc_key) self.model.class.connection(:redis).lrem(self.key, 0, assoc_key) end def destroy remove_from_all_associations self.model.class.connection(:redis).del(self.key) end def remove_from_all_associations self.each_association { |assoc| assoc.remove(self.model) } end def each_association llen = self.model.class.connection(:redis).llen(self.key) 0.upto(llen-1) do |i| assoc_key = self.model.class.connection(:redis).lindex(self.key, i) yield Chimera::AssociationProxies::Association.find(assoc_key) end true end def all_associations all = []; self.each_association { |ass| all << ass }; all end end class Association attr_accessor :model, :name, :klass def self.find(assoc_key) parts = assoc_key.split("::") model_klass = parts[0] name = parts[3] assoc_klass = parts[4] model_id = parts[5] self.new(eval(model_klass).find(model_id), name, assoc_klass.to_sym) end def initialize(_model, _name, class_sym) @model = _model @name = _name @klass = eval(class_sym.to_s.camelize) raise(Chimera::Error::MissingId) unless model.id end def key "#{model.class.to_s}::AssociationProxies::Association::#{name}::#{klass.to_s}::#{model.id}" end def <<(obj) raise(Chimera::Error::AssociationClassMismatch) unless obj.class.to_s == self.klass.to_s self.model.class.connection(:redis).lpush(self.key, obj.id) obj.association_memberships.add(self.key) true end def remove(obj) raise(Chimera::Error::AssociationClassMismatch) unless obj.class.to_s == self.klass.to_s self.model.class.connection(:redis).lrem(self.key, 0, obj.id) obj.association_memberships.remove(self.key) true end def size self.model.class.connection(:redis).llen(self.key) end - def each + def each(limit=nil) llen = self.model.class.connection(:redis).llen(self.key) + limit ||= llen curr = 0 - while(curr < llen) - keys = self.model.class.connection(:redis).lrange(self.key, curr, curr+9).compact + while(curr < limit) + max_index = [curr+9,limit-1].min + keys = self.model.class.connection(:redis).lrange(self.key, curr, max_index).compact self.klass.find_many(keys).each { |obj| yield(obj) } curr += 10 end true end def all found = []; self.each { |o| found << o }; found end def destroy(delete_associated=true) if delete_associated == true self.each { |obj| obj.destroy } else self.each { |obj| obj.association_memberships.remove(self.key) } end self.model.class.connection(:redis).del(self.key) end end # Association end # AssociationProxies end \ No newline at end of file diff --git a/lib/typhoeus.rb b/lib/typhoeus.rb deleted file mode 100644 index 44cdb77..0000000 --- a/lib/typhoeus.rb +++ /dev/null @@ -1,55 +0,0 @@ -$LOAD_PATH.unshift(File.dirname(__FILE__)) unless $LOAD_PATH.include?(File.dirname(__FILE__)) - -require 'rack/utils' -require 'digest/sha2' -require 'typhoeus/easy' -require 'typhoeus/multi' -require 'typhoeus/native' -require 'typhoeus/filter' -require 'typhoeus/remote_method' -require 'typhoeus/remote' -require 'typhoeus/remote_proxy_object' -require 'typhoeus/response' -require 'typhoeus/request' -require 'typhoeus/hydra' - -module Typhoeus - VERSION = "0.1.22" - - def self.easy_object_pool - @easy_objects ||= [] - end - - def self.init_easy_object_pool - 20.times do - easy_object_pool << Typhoeus::Easy.new - end - end - - def self.release_easy_object(easy) - easy.reset - easy_object_pool << easy - end - - def self.get_easy_object - if easy_object_pool.empty? - Typhoeus::Easy.new - else - easy_object_pool.pop - end - end - - def self.add_easy_request(easy_object) - Thread.current[:curl_multi] ||= Typhoeus::Multi.new - Thread.current[:curl_multi].add(easy_object) - end - - def self.perform_easy_requests - multi = Thread.current[:curl_multi] - start_time = Time.now - multi.easy_handles.each do |easy| - easy.start_time = start_time - end - multi.perform - end -end diff --git a/lib/typhoeus/.gitignore b/lib/typhoeus/.gitignore deleted file mode 100644 index 08d271f..0000000 --- a/lib/typhoeus/.gitignore +++ /dev/null @@ -1 +0,0 @@ -native.bundle \ No newline at end of file diff --git a/lib/typhoeus/easy.rb b/lib/typhoeus/easy.rb deleted file mode 100644 index 7fbbe54..0000000 --- a/lib/typhoeus/easy.rb +++ /dev/null @@ -1,253 +0,0 @@ -module Typhoeus - class Easy - attr_reader :response_body, :response_header, :method, :headers, :url - attr_accessor :start_time - - CURLINFO_STRING = 1048576 - OPTION_VALUES = { - :CURLOPT_URL => 10002, - :CURLOPT_HTTPGET => 80, - :CURLOPT_HTTPPOST => 10024, - :CURLOPT_UPLOAD => 46, - :CURLOPT_CUSTOMREQUEST => 10036, - :CURLOPT_POSTFIELDS => 10015, - :CURLOPT_POSTFIELDSIZE => 60, - :CURLOPT_USERAGENT => 10018, - :CURLOPT_TIMEOUT_MS => 155, - :CURLOPT_NOSIGNAL => 99, - :CURLOPT_HTTPHEADER => 10023, - :CURLOPT_FOLLOWLOCATION => 52, - :CURLOPT_MAXREDIRS => 68, - :CURLOPT_HTTPAUTH => 107, - :CURLOPT_USERPWD => 10000 + 5, - :CURLOPT_VERBOSE => 41, - :CURLOPT_PROXY => 10004, - :CURLOPT_VERIFYPEER => 64, - :CURLOPT_NOBODY => 44 - } - INFO_VALUES = { - :CURLINFO_RESPONSE_CODE => 2097154, - :CURLINFO_TOTAL_TIME => 3145731, - :CURLINFO_HTTPAUTH_AVAIL => 0x200000 + 23 - } - AUTH_TYPES = { - :CURLAUTH_BASIC => 1, - :CURLAUTH_DIGEST => 2, - :CURLAUTH_GSSNEGOTIATE => 4, - :CURLAUTH_NTLM => 8, - :CURLAUTH_DIGEST_IE => 16 - } - - def initialize - @method = :get - @post_dat_set = nil - @headers = {} - end - - def headers=(hash) - @headers = hash - end - - def proxy=(proxy) - set_option(OPTION_VALUES[:CURLOPT_PROXY], proxy) - end - - def auth=(authinfo) - set_option(OPTION_VALUES[:CURLOPT_USERPWD], "#{authinfo[:username]}:#{authinfo[:password]}") - set_option(OPTION_VALUES[:CURLOPT_HTTPAUTH], authinfo[:method]) if authinfo[:method] - end - - def auth_methods - get_info_long(INFO_VALUES[:CURLINFO_HTTPAUTH_AVAIL]) - end - - def verbose=(boolean) - set_option(OPTION_VALUES[:CURLOPT_VERBOSE], !!boolean ? 1 : 0) - end - - def total_time_taken - get_info_double(INFO_VALUES[:CURLINFO_TOTAL_TIME]) - end - - def response_code - get_info_long(INFO_VALUES[:CURLINFO_RESPONSE_CODE]) - end - - def follow_location=(boolean) - if boolean - set_option(OPTION_VALUES[:CURLOPT_FOLLOWLOCATION], 1) - else - set_option(OPTION_VALUES[:CURLOPT_FOLLOWLOCATION], 0) - end - end - - def max_redirects=(redirects) - set_option(OPTION_VALUES[:CURLOPT_MAXREDIRS], redirects) - end - - def timeout=(milliseconds) - @timeout = milliseconds - set_option(OPTION_VALUES[:CURLOPT_NOSIGNAL], 1) - set_option(OPTION_VALUES[:CURLOPT_TIMEOUT_MS], milliseconds) - end - - def timed_out? - @timeout && total_time_taken > @timeout && response_code == 0 - end - - def request_body=(request_body) - @request_body = request_body - if @method == :put - easy_set_request_body(@request_body) - headers["Transfer-Encoding"] = "" - headers["Expect"] = "" - else - self.post_data = request_body - end - end - - def user_agent=(user_agent) - set_option(OPTION_VALUES[:CURLOPT_USERAGENT], user_agent) - end - - def url=(url) - @url = url - set_option(OPTION_VALUES[:CURLOPT_URL], url) - end - - def disable_ssl_peer_verification - set_option(OPTION_VALUES[:CURLOPT_VERIFYPEER], 0) - end - - def method=(method) - @method = method - if method == :get - set_option(OPTION_VALUES[:CURLOPT_HTTPGET], 1) - elsif method == :post - set_option(OPTION_VALUES[:CURLOPT_HTTPPOST], 1) - self.post_data = "" - elsif method == :put - set_option(OPTION_VALUES[:CURLOPT_UPLOAD], 1) - self.request_body = "" unless @request_body - elsif method == :head - set_option(OPTION_VALUES[:CURLOPT_NOBODY], 1) - else - set_option(OPTION_VALUES[:CURLOPT_CUSTOMREQUEST], "DELETE") - end - end - - def post_data=(data) - @post_data_set = true - set_option(OPTION_VALUES[:CURLOPT_POSTFIELDS], data) - set_option(OPTION_VALUES[:CURLOPT_POSTFIELDSIZE], data.length) - end - - def params=(params) - params_string = params.keys.collect do |k| - value = params[k] - if value.is_a? Hash - value.keys.collect {|sk| Rack::Utils.escape("#{k}[#{sk}]") + "=" + Rack::Utils.escape(value[sk].to_s)} - elsif value.is_a? Array - key = Rack::Utils.escape(k.to_s) - value.collect { |v| "#{key}=#{Rack::Utils.escape(v.to_s)}" }.join('&') - else - "#{Rack::Utils.escape(k.to_s)}=#{Rack::Utils.escape(params[k].to_s)}" - end - end.flatten.join("&") - - if method == :post - self.post_data = params_string - else - self.url = "#{url}?#{params_string}" - end - end - - def set_option(option, value) - if value.class == String - easy_setopt_string(option, value) - else - easy_setopt_long(option, value) - end - end - - def perform - set_headers() - easy_perform() - response_code() - end - - def set_headers - headers.each_pair do |key, value| - easy_add_header("#{key}: #{value}") - end - easy_set_headers() unless headers.empty? - end - - # gets called when finished and response code is 200-299 - def success - @success.call(self) if @success - end - - def on_success(&block) - @success = block - end - - def on_success=(block) - @success = block - end - - # gets called when finished and response code is 300-599 - def failure - @failure.call(self) if @failure - end - - def on_failure(&block) - @failure = block - end - - def on_failure=(block) - @failure = block - end - - def retries - @retries ||= 0 - end - - def increment_retries - @retries ||= 0 - @retries += 1 - end - - def max_retries - @max_retries ||= 40 - end - - def max_retries? - retries >= max_retries - end - - def reset - @retries = 0 - @response_code = 0 - @response_header = "" - @response_body = "" - easy_reset() - end - - def get_info_string(option) - easy_getinfo_string(option) - end - - def get_info_long(option) - easy_getinfo_long(option) - end - - def get_info_double(option) - easy_getinfo_double(option) - end - - def curl_version - version - end - end -end diff --git a/lib/typhoeus/filter.rb b/lib/typhoeus/filter.rb deleted file mode 100644 index 9f970e9..0000000 --- a/lib/typhoeus/filter.rb +++ /dev/null @@ -1,28 +0,0 @@ -module Typhoeus - class Filter - attr_reader :method_name - - def initialize(method_name, options = {}) - @method_name = method_name - @options = options - end - - def apply_filter?(method_name) - if @options[:only] - if @options[:only].instance_of? Symbol - @options[:only] == method_name - else - @options[:only].include?(method_name) - end - elsif @options[:except] - if @options[:except].instance_of? Symbol - @options[:except] != method_name - else - !@options[:except].include?(method_name) - end - else - true - end - end - end -end \ No newline at end of file diff --git a/lib/typhoeus/hydra.rb b/lib/typhoeus/hydra.rb deleted file mode 100644 index 1a69138..0000000 --- a/lib/typhoeus/hydra.rb +++ /dev/null @@ -1,210 +0,0 @@ -module Typhoeus - class Hydra - def initialize(options = {}) - @memoize_requests = true - @multi = Multi.new - @easy_pool = [] - initial_pool_size = options[:initial_pool_size] || 10 - @max_concurrency = options[:max_concurrency] || 200 - initial_pool_size.times { @easy_pool << Easy.new } - @stubs = [] - @memoized_requests = {} - @retrieved_from_cache = {} - @queued_requests = [] - @running_requests = 0 - end - - def self.hydra - @hydra ||= new - end - - def self.hydra=(val) - @hydra = val - end - - def clear_stubs - @stubs = [] - end - - def fire_and_forget - @queued_requests.each {|r| queue(r, false)} - @multi.fire_and_forget - end - - def queue(request, obey_concurrency_limit = true) - return if assign_to_stub(request) - - if @running_requests >= @max_concurrency && obey_concurrency_limit - @queued_requests << request - else - if request.method == :get - if @memoize_requests && @memoized_requests.has_key?(request.url) - if response = @retrieved_from_cache[request.url] - request.response = response - request.call_handlers - else - @memoized_requests[request.url] << request - end - else - @memoized_requests[request.url] = [] if @memoize_requests - get_from_cache_or_queue(request) - end - else - get_from_cache_or_queue(request) - end - end - end - - def run - @stubs.each do |m| - m.requests.each do |request| - m.response.request = request - handle_request(request, m.response) - end - end - @multi.perform - @memoized_requests = {} - @retrieved_from_cache = {} - end - - def disable_memoization - @memoize_requests = false - end - - def cache_getter(&block) - @cache_getter = block - end - - def cache_setter(&block) - @cache_setter = block - end - - def on_complete(&block) - @on_complete = block - end - - def on_complete=(proc) - @on_complete = proc - end - - def stub(method, url) - @stubs << HydraMock.new(url, method) - @stubs.last - end - - def assign_to_stub(request) - m = @stubs.detect {|stub| stub.matches? request} - m && m.add_request(request) - end - private :assign_to_stub - - def get_from_cache_or_queue(request) - if @cache_getter - val = @cache_getter.call(request) - if val - @retrieved_from_cache[request.url] = val - handle_request(request, val, false) - else - @multi.add(get_easy_object(request)) - end - else - @multi.add(get_easy_object(request)) - end - end - private :get_from_cache_or_queue - - def get_easy_object(request) - @running_requests += 1 - easy = @easy_pool.pop || Easy.new - easy.url = request.url - easy.method = request.method - easy.params = request.params if request.method == :post && !request.params.nil? - easy.headers = request.headers if request.headers - easy.request_body = request.body if request.body - easy.timeout = request.timeout if request.timeout - easy.follow_location = request.follow_location if request.follow_location - easy.max_redirects = request.max_redirects if request.max_redirects - easy.proxy = request.proxy if request.proxy - easy.disable_ssl_peer_verification if request.disable_ssl_peer_verification - - easy.on_success do |easy| - queue_next - handle_request(request, response_from_easy(easy, request)) - release_easy_object(easy) - end - easy.on_failure do |easy| - queue_next - handle_request(request, response_from_easy(easy, request)) - release_easy_object(easy) - end - easy.set_headers - easy - end - private :get_easy_object - - def queue_next - @running_requests -= 1 - queue(@queued_requests.pop) unless @queued_requests.empty? - end - private :queue_next - - def release_easy_object(easy) - easy.reset - @easy_pool.push easy - end - private :release_easy_object - - def handle_request(request, response, live_request = true) - request.response = response - - if live_request && request.cache_timeout && @cache_setter - @cache_setter.call(request) - end - @on_complete.call(response) if @on_complete - - request.call_handlers - if requests = @memoized_requests[request.url] - requests.each do |r| - r.response = response - r.call_handlers - end - end - end - private :handle_request - - def response_from_easy(easy, request) - Response.new(:code => easy.response_code, - :headers => easy.response_header, - :body => easy.response_body, - :time => easy.total_time_taken, - :request => request) - end - private :response_from_easy - end - - class HydraMock - attr_reader :url, :method, :response, :requests - - def initialize(url, method) - @url = url - @method = method - @requests = [] - end - - def add_request(request) - @requests << request - end - - def and_return(val) - @response = val - end - - def matches?(request) - if url.kind_of?(String) - request.method == method && request.url == url - else - request.method == method && url =~ request.url - end - end - end -end diff --git a/lib/typhoeus/multi.rb b/lib/typhoeus/multi.rb deleted file mode 100644 index acf0731..0000000 --- a/lib/typhoeus/multi.rb +++ /dev/null @@ -1,34 +0,0 @@ -module Typhoeus - class Multi - attr_reader :easy_handles - - def initialize - reset_easy_handles - end - - def remove(easy) - multi_remove_handle(easy) - end - - def add(easy) - @easy_handles << easy - multi_add_handle(easy) - end - - def perform() - while active_handle_count > 0 do - multi_perform - end - reset_easy_handles - end - - def cleanup() - multi_cleanup - end - - private - def reset_easy_handles - @easy_handles = [] - end - end -end diff --git a/lib/typhoeus/remote.rb b/lib/typhoeus/remote.rb deleted file mode 100644 index d54d061..0000000 --- a/lib/typhoeus/remote.rb +++ /dev/null @@ -1,306 +0,0 @@ -module Typhoeus - USER_AGENT = "Typhoeus - http://github.com/pauldix/typhoeus/tree/master" - - def self.included(base) - base.extend ClassMethods - end - - class MockExpectedError < StandardError; end - - module ClassMethods - def allow_net_connect - @allow_net_connect = true if @allow_net_connect.nil? - @allow_net_connect - end - - def allow_net_connect=(value) - @allow_net_connect = value - end - - def mock(method, args = {}) - @remote_mocks ||= {} - @remote_mocks[method] ||= {} - args[:code] ||= 200 - args[:body] ||= "" - args[:headers] ||= "" - args[:time] ||= 0 - url = args.delete(:url) - url ||= :catch_all - params = args.delete(:params) - - key = mock_key_for(url, params) - - @remote_mocks[method][key] = args - end - - # Returns a key for a given URL and passed in - # set of Typhoeus options to be used to store/retrieve - # a corresponding mock. - def mock_key_for(url, params = nil) - if url == :catch_all - url - else - key = url - if params and !params.empty? - key += flatten_and_sort_hash(params).to_s - end - key - end - end - - def flatten_and_sort_hash(params) - params = params.dup - - # Flatten any sub-hashes to a single string. - params.keys.each do |key| - if params[key].is_a?(Hash) - params[key] = params[key].sort_by { |k, v| k.to_s.downcase }.to_s - end - end - - params.sort_by { |k, v| k.to_s.downcase } - end - - def get_mock(method, url, options) - return nil unless @remote_mocks - if @remote_mocks.has_key? method - extra_response_args = { :requested_http_method => method, - :requested_url => url, - :start_time => Time.now } - mock_key = mock_key_for(url, options[:params]) - if @remote_mocks[method].has_key? mock_key - get_mock_and_run_handlers(method, - @remote_mocks[method][mock_key].merge( - extra_response_args), - options) - elsif @remote_mocks[method].has_key? :catch_all - get_mock_and_run_handlers(method, - @remote_mocks[method][:catch_all].merge( - extra_response_args), - options) - else - nil - end - else - nil - end - end - - def enforce_allow_net_connect!(http_verb, url, params = nil) - if !allow_net_connect - message = "Real HTTP connections are disabled. Unregistered request: " << - "#{http_verb.to_s.upcase} #{url}\n" << - " Try: mock(:#{http_verb}, :url => \"#{url}\"" - if params - message << ",\n :params => #{params.inspect}" - end - - message << ")" - - raise MockExpectedError, message - end - end - - def check_expected_headers!(response_args, options) - missing_headers = {} - - response_args[:expected_headers].each do |key, value| - if options[:headers].nil? - missing_headers[key] = [value, nil] - elsif ((options[:headers][key] && value != :anything) && - options[:headers][key] != value) - - missing_headers[key] = [value, options[:headers][key]] - end - end - - unless missing_headers.empty? - raise headers_error_summary(response_args, options, missing_headers, 'expected') - end - end - - def check_unexpected_headers!(response_args, options) - bad_headers = {} - response_args[:unexpected_headers].each do |key, value| - if (options[:headers][key] && value == :anything) || - (options[:headers][key] == value) - bad_headers[key] = [value, options[:headers][key]] - end - end - - unless bad_headers.empty? - raise headers_error_summary(response_args, options, bad_headers, 'did not expect') - end - end - - def headers_error_summary(response_args, options, missing_headers, lead_in) - error = "#{lead_in} the following headers: #{response_args[:expected_headers].inspect}, but received: #{options[:headers].inspect}\n\n" - error << "Differences:\n" - error << "------------\n" - missing_headers.each do |key, values| - error << " - #{key}: #{lead_in} #{values[0].inspect}, got #{values[1].inspect}\n" - end - - error - end - private :headers_error_summary - - def get_mock_and_run_handlers(method, response_args, options) - response = Response.new(response_args) - - if response_args.has_key? :expected_body - raise "#{method} expected body of \"#{response_args[:expected_body]}\" but received #{options[:body]}" if response_args[:expected_body] != options[:body] - end - - if response_args.has_key? :expected_headers - check_expected_headers!(response_args, options) - end - - if response_args.has_key? :unexpected_headers - check_unexpected_headers!(response_args, options) - end - - if response.code >= 200 && response.code < 300 && options.has_key?(:on_success) - response = options[:on_success].call(response) - elsif options.has_key?(:on_failure) - response = options[:on_failure].call(response) - end - - encode_nil_response(response) - end - - [:get, :post, :put, :delete].each do |method| - line = __LINE__ + 2 # get any errors on the correct line num - code = <<-SRC - def #{method.to_s}(url, options = {}) - mock_object = get_mock(:#{method.to_s}, url, options) - unless mock_object.nil? - decode_nil_response(mock_object) - else - enforce_allow_net_connect!(:#{method.to_s}, url, options[:params]) - remote_proxy_object(url, :#{method.to_s}, options) - end - end - SRC - module_eval(code, "./lib/typhoeus/remote.rb", line) - end - - def remote_proxy_object(url, method, options) - easy = Typhoeus.get_easy_object - - easy.url = url - easy.method = method - easy.headers = options[:headers] if options.has_key?(:headers) - easy.headers["User-Agent"] = (options[:user_agent] || Typhoeus::USER_AGENT) - easy.params = options[:params] if options[:params] - easy.request_body = options[:body] if options[:body] - easy.timeout = options[:timeout] if options[:timeout] - easy.set_headers - - proxy = Typhoeus::RemoteProxyObject.new(clear_memoized_proxy_objects, easy, options) - set_memoized_proxy_object(method, url, options, proxy) - end - - def remote_defaults(options) - @remote_defaults ||= {} - @remote_defaults.merge!(options) if options - @remote_defaults - end - - # If we get subclassed, make sure that child inherits the remote defaults - # of the parent class. - def inherited(child) - child.__send__(:remote_defaults, @remote_defaults) - end - - def call_remote_method(method_name, args) - m = @remote_methods[method_name] - - base_uri = args.delete(:base_uri) || m.base_uri || "" - - if args.has_key? :path - path = args.delete(:path) - else - path = m.interpolate_path_with_arguments(args) - end - path ||= "" - - http_method = m.http_method - url = base_uri + path - options = m.merge_options(args) - - # proxy_object = memoized_proxy_object(http_method, url, options) - # return proxy_object unless proxy_object.nil? - # - # if m.cache_responses? - # object = @cache.get(get_memcache_response_key(method_name, args)) - # if object - # set_memoized_proxy_object(http_method, url, options, object) - # return object - # end - # end - - proxy = memoized_proxy_object(http_method, url, options) - unless proxy - if m.cache_responses? - options[:cache] = @cache - options[:cache_key] = get_memcache_response_key(method_name, args) - options[:cache_timeout] = m.cache_ttl - end - proxy = send(http_method, url, options) - end - proxy - end - - def set_memoized_proxy_object(http_method, url, options, object) - @memoized_proxy_objects ||= {} - @memoized_proxy_objects["#{http_method}_#{url}_#{options.to_s}"] = object - end - - def memoized_proxy_object(http_method, url, options) - @memoized_proxy_objects ||= {} - @memoized_proxy_objects["#{http_method}_#{url}_#{options.to_s}"] - end - - def clear_memoized_proxy_objects - lambda { @memoized_proxy_objects = {} } - end - - def get_memcache_response_key(remote_method_name, args) - result = "#{remote_method_name.to_s}-#{args.to_s}" - (Digest::SHA2.new << result).to_s - end - - def cache=(cache) - @cache = cache - end - - def define_remote_method(name, args = {}) - @remote_defaults ||= {} - args[:method] ||= @remote_defaults[:method] - args[:on_success] ||= @remote_defaults[:on_success] - args[:on_failure] ||= @remote_defaults[:on_failure] - args[:base_uri] ||= @remote_defaults[:base_uri] - args[:path] ||= @remote_defaults[:path] - m = RemoteMethod.new(args) - - @remote_methods ||= {} - @remote_methods[name] = m - - class_eval <<-SRC - def self.#{name.to_s}(args = {}) - call_remote_method(:#{name.to_s}, args) - end - SRC - end - - private - def encode_nil_response(response) - response == nil ? :__nil__ : response - end - - def decode_nil_response(response) - response == :__nil__ ? nil : response - end - end # ClassMethods -end diff --git a/lib/typhoeus/remote_method.rb b/lib/typhoeus/remote_method.rb deleted file mode 100644 index c863ff2..0000000 --- a/lib/typhoeus/remote_method.rb +++ /dev/null @@ -1,108 +0,0 @@ -module Typhoeus - class RemoteMethod - attr_accessor :http_method, :options, :base_uri, :path, :on_success, :on_failure, :cache_ttl - - def initialize(options = {}) - @http_method = options.delete(:method) || :get - @options = options - @base_uri = options.delete(:base_uri) - @path = options.delete(:path) - @on_success = options[:on_success] - @on_failure = options[:on_failure] - @cache_responses = options.delete(:cache_responses) - @memoize_responses = options.delete(:memoize_responses) || @cache_responses - @cache_ttl = @cache_responses == true ? 0 : @cache_responses - @keys = nil - - clear_cache - end - - def cache_responses? - @cache_responses - end - - def memoize_responses? - @memoize_responses - end - - def args_options_key(args, options) - "#{args.to_s}+#{options.to_s}" - end - - def calling(args, options) - @called_methods[args_options_key(args, options)] = true - end - - def already_called?(args, options) - @called_methods.has_key? args_options_key(args, options) - end - - def add_response_block(block, args, options) - @response_blocks[args_options_key(args, options)] << block - end - - def call_response_blocks(result, args, options) - key = args_options_key(args, options) - @response_blocks[key].each {|block| block.call(result)} - @response_blocks.delete(key) - @called_methods.delete(key) - end - - def clear_cache - @response_blocks = Hash.new {|h, k| h[k] = []} - @called_methods = {} - end - - def merge_options(new_options) - merged = options.merge(new_options) - if options.has_key?(:params) && new_options.has_key?(:params) - merged[:params] = options[:params].merge(new_options[:params]) - end - argument_names.each {|a| merged.delete(a)} - merged.delete(:on_success) if merged[:on_success].nil? - merged.delete(:on_failure) if merged[:on_failure].nil? - merged - end - - def interpolate_path_with_arguments(args) - interpolated_path = @path - argument_names.each do |arg| - interpolated_path = interpolated_path.gsub(":#{arg}", args[arg].to_s) - end - interpolated_path - end - - def argument_names - return @keys if @keys - pattern, keys = compile(@path) - @keys = keys.collect {|k| k.to_sym} - end - - # rippped from Sinatra. clean up stuff we don't need later - def compile(path) - path ||= "" - keys = [] - if path.respond_to? :to_str - special_chars = %w{. + ( )} - pattern = - path.gsub(/((:\w+)|[\*#{special_chars.join}])/) do |match| - case match - when "*" - keys << 'splat' - "(.*?)" - when *special_chars - Regexp.escape(match) - else - keys << $2[1..-1] - "([^/?&#]+)" - end - end - [/^#{pattern}$/, keys] - elsif path.respond_to? :match - [path, keys] - else - raise TypeError, path - end - end - end -end diff --git a/lib/typhoeus/remote_proxy_object.rb b/lib/typhoeus/remote_proxy_object.rb deleted file mode 100644 index fc9ad7e..0000000 --- a/lib/typhoeus/remote_proxy_object.rb +++ /dev/null @@ -1,48 +0,0 @@ -module Typhoeus - class RemoteProxyObject - instance_methods.each { |m| undef_method m unless m =~ /^__|object_id/ } - - def initialize(clear_memoized_store_proc, easy, options = {}) - @clear_memoized_store_proc = clear_memoized_store_proc - @easy = easy - @success = options[:on_success] - @failure = options[:on_failure] - @cache = options.delete(:cache) - @cache_key = options.delete(:cache_key) - @timeout = options.delete(:cache_timeout) - Typhoeus.add_easy_request(@easy) - end - - def method_missing(sym, *args, &block) - unless @proxied_object - if @cache && @cache_key - @proxied_object = @cache.get(@cache_key) rescue nil - end - - unless @proxied_object - Typhoeus.perform_easy_requests - response = Response.new(:code => @easy.response_code, - :headers => @easy.response_header, - :body => @easy.response_body, - :time => @easy.total_time_taken, - :requested_url => @easy.url, - :requested_http_method => @easy.method, - :start_time => @easy.start_time) - if @easy.response_code >= 200 && @easy.response_code < 300 - Typhoeus.release_easy_object(@easy) - @proxied_object = @success.nil? ? response : @success.call(response) - - if @cache && @cache_key - @cache.set(@cache_key, @proxied_object, @timeout) - end - else - @proxied_object = @failure.nil? ? response : @failure.call(response) - end - @clear_memoized_store_proc.call - end - end - - @proxied_object.__send__(sym, *args, &block) - end - end -end diff --git a/lib/typhoeus/request.rb b/lib/typhoeus/request.rb deleted file mode 100644 index e91f154..0000000 --- a/lib/typhoeus/request.rb +++ /dev/null @@ -1,124 +0,0 @@ -module Typhoeus - class Request - attr_accessor :method, :params, :body, :headers, :timeout, :user_agent, :response, :cache_timeout, :follow_location, :max_redirects, :proxy, :disable_ssl_peer_verification - attr_reader :url - - def initialize(url, options = {}) - @method = options[:method] || :get - @params = options[:params] - @body = options[:body] - @timeout = options[:timeout] - @headers = options[:headers] || {} - @user_agent = options[:user_agent] || Typhoeus::USER_AGENT - @cache_timeout = options[:cache_timeout] - @follow_location = options[:follow_location] - @max_redirects = options[:max_redirects] - @proxy = options[:proxy] - @disable_ssl_peer_verification = options[:disable_ssl_peer_verification] - - if @method == :post - @url = url - else - @url = @params ? "#{url}?#{params_string}" : url - end - @on_complete = nil - @after_complete = nil - @handled_response = nil - end - - def host - slash_location = @url.index('/', 8) - if slash_location - @url.slice(0, slash_location) - else - query_string_location = @url.index('?') - return query_string_location ? @url.slice(0, query_string_location) : @url - end - end - - def headers - @headers["User-Agent"] = @user_agent - @headers - end - - def params_string - params.keys.sort.collect do |k| - value = params[k] - if value.is_a? Hash - value.keys.collect {|sk| Rack::Utils.escape("#{k}[#{sk}]") + "=" + Rack::Utils.escape(value[sk].to_s)} - elsif value.is_a? Array - key = Rack::Utils.escape(k.to_s) - value.collect { |v| "#{key}=#{Rack::Utils.escape(v.to_s)}" }.join('&') - else - "#{Rack::Utils.escape(k.to_s)}=#{Rack::Utils.escape(params[k].to_s)}" - end - end.flatten.join("&") - end - - def on_complete(&block) - @on_complete = block - end - - def on_complete=(proc) - @on_complete = proc - end - - def after_complete(&block) - @after_complete = block - end - - def after_complete=(proc) - @after_complete = proc - end - - def call_handlers - if @on_complete - @handled_response = @on_complete.call(response) - call_after_complete - end - end - - def call_after_complete - @after_complete.call(@handled_response) if @after_complete - end - - def handled_response=(val) - @handled_response = val - end - - def handled_response - @handled_response || response - end - - def cache_key - Digest::SHA1.hexdigest(url) - end - - def self.run(url, params) - r = new(url, params) - Typhoeus::Hydra.hydra.queue r - Typhoeus::Hydra.hydra.run - r.response - end - - def self.get(url, params = {}) - run(url, params.merge(:method => :get)) - end - - def self.post(url, params = {}) - run(url, params.merge(:method => :post)) - end - - def self.put(url, params = {}) - run(url, params.merge(:method => :put)) - end - - def self.delete(url, params = {}) - run(url, params.merge(:method => :delete)) - end - - def self.head(url, params = {}) - run(url, params.merge(:method => :head)) - end - end -end diff --git a/lib/typhoeus/response.rb b/lib/typhoeus/response.rb deleted file mode 100644 index 6222499..0000000 --- a/lib/typhoeus/response.rb +++ /dev/null @@ -1,39 +0,0 @@ -module Typhoeus - class Response - attr_accessor :request - attr_reader :code, :headers, :body, :time, - :requested_url, :requested_remote_method, - :requested_http_method, :start_time - - def initialize(params = {}) - @code = params[:code] - @headers = params[:headers] - @body = params[:body] - @time = params[:time] - @requested_url = params[:requested_url] - @requested_http_method = params[:requested_http_method] - @start_time = params[:start_time] - @request = params[:request] - end - - def headers_hash - headers.split("\n").map {|o| o.strip}.inject({}) do |hash, o| - if o.empty? - hash - else - i = o.index(":") || o.size - key = o.slice(0, i) - value = o.slice(i + 1, o.size) - value = value.strip unless value.nil? - if hash.has_key? key - hash[key] = [hash[key], value].flatten - else - hash[key] = value - end - - hash - end - end - end - end -end diff --git a/lib/typhoeus/service.rb b/lib/typhoeus/service.rb deleted file mode 100644 index 732a946..0000000 --- a/lib/typhoeus/service.rb +++ /dev/null @@ -1,20 +0,0 @@ -module Typhoeus - class Service - def initialize(host, port) - @host = host - @port = port - end - - def get(resource, params) - end - - def put(resource, params) - end - - def post(resource, params) - end - - def delete(resource, params) - end - end -end \ No newline at end of file
benmyles/chimera
dbf360fc7fa1e54dba6b3921c3425c5c8ee18e81
added destroy_all method
diff --git a/lib/chimera/base.rb b/lib/chimera/base.rb index c45d6da..a4fe8be 100644 --- a/lib/chimera/base.rb +++ b/lib/chimera/base.rb @@ -1,99 +1,103 @@ module Chimera def self.config_path=(path) @config_path = path @config = YAML.load_file(@config_path) end def self.config @config || raise(Chimera::Error::MissingConfig) end class Base include Chimera::Attributes include Chimera::Indexes include Chimera::GeoIndexes include Chimera::Associations include Chimera::RedisObjects include Chimera::Finders include Chimera::Persistence include ActiveModel::Validations extend ActiveModel::Naming extend ActiveModel::Callbacks define_model_callbacks :create, :save, :destroy attr_accessor :id, :attributes, :orig_attributes, :riak_response, :associations, :sibling_attributes def self.use_config(key) @config = (Chimera.config[key.to_sym] || raise(Chimera::Error::MissingConfig,":#{key}")) end def self.config @config ||= (Chimera.config[:default] || raise(Chimera::Error::MissingConfig,":default")) end def self.connection(server) Thread.current["Chimera::#{self.to_s}::#{server}::connection"] ||= new_connection(server) end def self.new_connection(server) case server.to_sym when :redis Redis.new(self.config[:redis]) when :riak_raw RiakRaw::Client.new(self.config[:riak_raw][:host], self.config[:riak_raw][:port]) else nil end end def self.bucket_key self.to_s end def self.bucket(keys=false) self.connection(:riak_raw).bucket(self.bucket_key,keys) end def self.new_uuid UUIDTools::UUID.random_create.to_s end + def self.destroy_all + self.each { |o| o.destroy } + end + def inspect "#<#{self.to_s}: @id=#{self.id}, @new=#{@new}>" end def ==(obj) obj.class.to_s == self.class.to_s && !obj.new? && !self.new? && obj.id == self.id end def <=>(obj) self.id.to_s <=> obj.id.to_s end def initialize(attributes={},id=nil,is_new=true) @attributes = attributes @orig_attributes = @attributes.clone @id = id @new = is_new @sibling_attributes = nil end def id=(val) if self.new? @id = val else raise(Chimera::Error::AttemptToModifyId) end end protected def read_attribute_for_validation(key) @attributes[key.to_sym] end end # Base end # Chimera \ No newline at end of file
benmyles/chimera
dea3853358e6487095889bc44a36ba9d005198e1
support for riak siblings so that we can manage conflicts
diff --git a/lib/chimera/base.rb b/lib/chimera/base.rb index f9b663a..c45d6da 100644 --- a/lib/chimera/base.rb +++ b/lib/chimera/base.rb @@ -1,95 +1,99 @@ module Chimera def self.config_path=(path) @config_path = path @config = YAML.load_file(@config_path) end def self.config @config || raise(Chimera::Error::MissingConfig) end class Base include Chimera::Attributes include Chimera::Indexes include Chimera::GeoIndexes include Chimera::Associations include Chimera::RedisObjects include Chimera::Finders include Chimera::Persistence include ActiveModel::Validations extend ActiveModel::Naming extend ActiveModel::Callbacks define_model_callbacks :create, :save, :destroy - attr_accessor :id, :attributes, :orig_attributes, :riak_response, :associations + attr_accessor :id, :attributes, :orig_attributes, :riak_response, :associations, + :sibling_attributes def self.use_config(key) @config = (Chimera.config[key.to_sym] || raise(Chimera::Error::MissingConfig,":#{key}")) end def self.config @config ||= (Chimera.config[:default] || raise(Chimera::Error::MissingConfig,":default")) end def self.connection(server) - Thread.current["Chimera::#{self.to_s}::#{server}::connection"] ||= begin - case server.to_sym - when :redis - Redis.new(self.config[:redis]) - when :riak_raw - RiakRaw::Client.new(self.config[:riak_raw][:host], self.config[:riak_raw][:port]) - else - nil - end + Thread.current["Chimera::#{self.to_s}::#{server}::connection"] ||= new_connection(server) + end + + def self.new_connection(server) + case server.to_sym + when :redis + Redis.new(self.config[:redis]) + when :riak_raw + RiakRaw::Client.new(self.config[:riak_raw][:host], self.config[:riak_raw][:port]) + else + nil end end def self.bucket_key self.to_s end def self.bucket(keys=false) self.connection(:riak_raw).bucket(self.bucket_key,keys) end def self.new_uuid UUIDTools::UUID.random_create.to_s end def inspect "#<#{self.to_s}: @id=#{self.id}, @new=#{@new}>" end def ==(obj) obj.class.to_s == self.class.to_s && !obj.new? && !self.new? && obj.id == self.id end def <=>(obj) self.id.to_s <=> obj.id.to_s end def initialize(attributes={},id=nil,is_new=true) @attributes = attributes @orig_attributes = @attributes.clone @id = id @new = is_new + @sibling_attributes = nil end def id=(val) if self.new? @id = val else raise(Chimera::Error::AttemptToModifyId) end end protected def read_attribute_for_validation(key) @attributes[key.to_sym] end end # Base end # Chimera \ No newline at end of file diff --git a/lib/chimera/error.rb b/lib/chimera/error.rb index 70b744e..1ad5c1a 100644 --- a/lib/chimera/error.rb +++ b/lib/chimera/error.rb @@ -1,12 +1,14 @@ module Chimera class Error < RuntimeError class MissingConfig < Chimera::Error; end class UniqueConstraintViolation < Chimera::Error; end class SaveWithoutId < Chimera::Error; end class MissingId < Chimera::Error; end class ValidationErrors < Chimera::Error; end class AttemptToModifyId < Chimera::Error; end class AssociationClassMismatch < Chimera::Error; end + class UnhandledRiakResponseCode < Chimera::Error; end + class CannotSaveWithConflicts < Chimera::Error; end end end diff --git a/lib/chimera/finders.rb b/lib/chimera/finders.rb index 5e18fee..4be3a02 100644 --- a/lib/chimera/finders.rb +++ b/lib/chimera/finders.rb @@ -1,49 +1,61 @@ module Chimera module Finders def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def each self.find_with_index(:all) { |obj| yield(obj) } end - def find(key) - find_many(key)[0] + def find(key,opts={}) + find_many([[key,opts]])[0] end - def find_many(keys) - keys = Array(keys) + def find_many(key_opts_arr) found = [] threads = [] - keys.each do |key| + key_opts_arr = Array(key_opts_arr).collect { |e| Array(e) } + key_opts_arr.each do |key,opts| + opts ||= {} threads << Thread.new do if key - resp = self.connection(:riak_raw).fetch(self.to_s, key) - if resp.code == 200 + resp = self.connection(:riak_raw).fetch(self.to_s, key, opts) + case resp.code + when 300 then + # siblings + obj = self.new({},key,false) + obj.riak_response = resp + obj.load_sibling_attributes + found << obj + when 200 then if resp.body and yaml_hash = YAML.load(resp.body) hash = {} yaml_hash.each { |k,v| hash[k.to_sym] = v } obj = self.new(hash,key,false) obj.riak_response = resp found << obj else obj = self.new({},key,false) obj.riak_response = resp found << obj end - end + when 404 then + nil + else + raise(Chimera::Error::UnhandledRiakResponseCode.new(resp.code.to_s)) + end # case end end # Thread.new end # keys.each threads.each { |th| th.join } found end # find_many end # ClassMethods module InstanceMethods end # InstanceMethods end end \ No newline at end of file diff --git a/lib/chimera/persistence.rb b/lib/chimera/persistence.rb index fdb495f..9d1065f 100644 --- a/lib/chimera/persistence.rb +++ b/lib/chimera/persistence.rb @@ -1,70 +1,122 @@ module Chimera module Persistence def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods + # allows for multiple conflicting values from riak + def allow_multi=(val) + props = self.bucket + props["props"]["allow_mult"] = val + self.connection(:riak_raw).set_bucket_properties(self.to_s,props) + end end # ClassMethods module InstanceMethods def new? @new == true end + + def in_conflict? + !self.sibling_attributes.nil? + end + + def load_sibling_attributes + return nil unless self.riak_response.body =~ /^Sibling/ + vtags = self.riak_response.body.split("\n")[1..-1] + if vtags.empty? + self.sibling_attributes = nil + else + self.sibling_attributes = {} + vtags.each do |vtag| + if resp = self.class.connection(:riak_raw).fetch(self.class.to_s, self.id, {"vtag" => vtag}) + self.sibling_attributes[vtag] = YAML.load(resp.body) + else + self.sibling_attributes[vtag] = {} + end + end + end + end # load_sibling_attributes + + def resolve_and_save + if valid? + self.sibling_attributes = nil + save + end + end def save - raise(Chimera::Error::SaveWithoutId) unless self.id - raise(Chimera::Error::ValidationErrors) unless self.valid? + verify_can_save! check_index_constraints if new? _run_create_callbacks do _run_save_callbacks do save_without_callbacks create_indexes end end else _run_save_callbacks do destroy_indexes save_without_callbacks create_indexes end end true end alias :create :save def vector_clock if @riak_response and @riak_response.headers_hash return @riak_response.headers_hash["X-Riak-Vclock"] end; nil end def save_without_callbacks + verify_can_save! + @riak_response = self.class.connection(:riak_raw).store( self.class.bucket_key, self.id, YAML.dump(@attributes), self.vector_clock) - + + case @riak_response.code + when 300 then + self.load_sibling_attributes + when 200 then + # all good + else + raise(Chimera::Error::UnhandledRiakResponseCode.new(@riak_response.code)) + end + @orig_attributes = @attributes.clone @new = false end def destroy _run_destroy_callbacks do @riak_response = self.class.connection(:riak_raw).delete(self.class.bucket_key, self.id) destroy_indexes association_memberships.destroy destroy_associations destroy_redis_objects freeze end end + + protected + + def verify_can_save! + raise(Chimera::Error::SaveWithoutId) unless self.id + raise(Chimera::Error::ValidationErrors) unless self.valid? + raise(Chimera::Error::CannotSaveWithConflicts) if self.in_conflict? + end end # InstanceMethods end end \ No newline at end of file diff --git a/lib/riak_raw.rb b/lib/riak_raw.rb index 0786db3..db64aa5 100644 --- a/lib/riak_raw.rb +++ b/lib/riak_raw.rb @@ -1,100 +1,109 @@ # gem "typhoeus", "= 0.1.18" # gem "uuidtools", "= 2.1.1" # gem "brianmario-yajl-ruby", "= 0.6.3" # require "typhoeus" # require "uuidtools" # require "uri" # require "yajl" # A Ruby interface for the Riak (http://riak.basho.com/) key-value store. # # Example Usage: # # > client = RiakRaw::Client.new('127.0.0.1', 8098, 'raw') # > client.delete('raw_example', 'doctestkey') # > obj = client.store('raw_example', 'doctestkey', {'foo':2}) # > client.fetch('raw_example', 'doctestkey') module RiakRaw VERSION = '0.0.1' class Client attr_accessor :host, :port, :prefix, :client_id def initialize(host="127.0.0.1", port=8098, prefix='riak', client_id=SecureRandom.base64) @host = host @port = port @prefix = prefix @client_id = client_id end def bucket(bucket_name,keys=false) #request(:get, build_path(bucket_name)) response = request(:get, build_path(bucket_name), nil, nil, {"returnbody" => "true", "keys" => keys}) if response.code == 200 if json = response.body return Yajl::Parser.parse(json) end end; nil end + def set_bucket_properties(name,props) + response = request(:put, + build_path(name), + Yajl::Encoder.encode(props), { 'Content-Type' => 'application/json' }) + end + def store(bucket_name, key, content, vclock=nil, links=[], content_type='application/json', w=2, dw=2, r=2) headers = { 'Content-Type' => content_type, 'X-Riak-ClientId' => self.client_id } if vclock headers['X-Riak-Vclock'] = vclock end response = request(:put, build_path(bucket_name,key), content, headers, {"returnbody" => "false", "w" => w, "dw" => dw}) # returnbody=true could cause issues. instead we'll do a # separate fetch. see: https://issues.basho.com/show_bug.cgi?id=52 if response.code == 204 - response = fetch(bucket_name, key, r) + response = fetch(bucket_name, key, {:r => r}) end response end - def fetch(bucket_name, key, r=2) + def fetch(bucket_name, key, _params={}) + params = {} + _params.each { |k,v| params[k.to_s] = v } + params["r"] ||= 2 response = request(:get, build_path(bucket_name, key), - nil, {}, {"r" => r}) + nil, {}, params) end # there could be concurrency issues if we don't force a short sleep # after delete. see: https://issues.basho.com/show_bug.cgi?id=52 def delete(bucket_name, key, dw=2) response = request(:delete, build_path(bucket_name, key), nil, {}, {"dw" => dw}) end private def build_path(bucket_name, key='') "http://#{self.host}:#{self.port}/#{self.prefix}/#{URI.escape(bucket_name)}/#{URI.escape(key)}" end def request(method, uri, body="", headers={}, params={}) hydra = Typhoeus::Hydra.new case method when :get then req = Typhoeus::Request.new(uri, :method => :get, :body => body, :headers => headers, :params => params) when :post then req = Typhoeus::Request.new(uri, :method => :post, :body => body, :headers => headers, :params => params) when :put then req = Typhoeus::Request.new(uri, :method => :put, :body => body, :headers => headers, :params => params) when :delete then req = Typhoeus::Request.new(uri, :method => :delete, :body => body, :headers => headers, :params => params) end hydra.queue(req); hydra.run req.handled_response end end # Client end \ No newline at end of file diff --git a/test/test_chimera.rb b/test/test_chimera.rb index 828e3cf..fce66bc 100644 --- a/test/test_chimera.rb +++ b/test/test_chimera.rb @@ -1,238 +1,330 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestChimera < Test::Unit::TestCase def setup Car.each { |c| c.destroy } Car.connection(:redis).flush_all + Car.allow_multi = true end def test_geo_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.id = Car.new_uuid c.curr_location = [37.12122, 121.43392] assert c.save c2 = Car.new c2.make = "Toyota" c2.model = "Hilux" c2.year = 2010 c2.sku = 1001 c2.curr_location = [37.12222, 121.43792] c2.id = Car.new_uuid assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c,c2].sort, found.sort c2.curr_location = [38.0, 122.0] assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c].sort, found.sort found = Car.find_with_index(:curr_location, {:coordinate => [38.0-0.05, 122.0+0.05], :steps => 5}) assert_equal [c2].sort, found.sort end def test_search_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.comments = "cat dog chicken dolphin whale panther" c.id = Car.new_uuid assert c.save c2 = Car.new c2.make = "Porsche" c2.model = "911" c2.year = 2010 c2.sku = 1001 c2.comments = "cat dog chicken" c2.id = Car.new_uuid assert c2.save - + c3 = Car.new c3.make = "Porsche" c3.model = "911" c3.year = 2010 c3.sku = 1002 c3.comments = "dog chicken dolphin whale" c3.id = Car.new_uuid assert c3.save assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, "dog").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort - + assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :union}).sort assert_equal [c,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :intersect}).sort end def test_indexes c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert !c.new? assert_equal [c], Car.find_with_index(:comments, "fast") assert_equal [c], Car.find_with_index(:comments, "purple") assert_equal [], Car.find_with_index(:comments, "blue") assert_equal [c], Car.find_with_index(:year, 2010) assert_equal [c], Car.find_with_index(:sku, 1001) c2 = Car.new c2.make = "Honda" c2.model = "Accord" c2.year = 2010 c2.sku = 1001 c2.id = Car.new_uuid assert_raise(Chimera::Error::UniqueConstraintViolation) { c2.save } c2.sku = 1002 assert c2.save c3 = Car.new c3.make = "Honda" c3.model = "Civic" c3.year = 2010 c3.sku = 1003 c3.id = Car.new_uuid assert c3.save assert_equal 3, Car.find_with_index(:year, 2010).size assert Car.find_with_index(:year, 2010).include?(c) assert Car.find_with_index(:year, 2010).include?(c2) assert Car.find_with_index(:year, 2010).include?(c3) count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 3, count count = 0 Car.each { |car| count += 1 } assert_equal 3, count c2.destroy count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 2, count count = 0 Car.each { |car| count += 1 } assert_equal 2, count end def test_associations u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_equal 0, u.friends.size chris = User.new chris.id = User.new_uuid chris.name = "Chris" assert chris.save assert_equal 0, u.friends.size u.friends << chris assert_equal 1, u.friends.size chris.destroy assert_equal 0, u.friends.size c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert_equal 0, u.cars.size u.cars << c assert_equal 1, u.cars.size assert_equal [c], u.cars.all assert_equal 1, c.association_memberships.all_associations.size u.cars.remove(c) assert_equal 0, c.association_memberships.all_associations.size end def test_model_attribute u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_nil u.favorite_car c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save u.favorite_car = c assert u.save assert_equal c, u.favorite_car u = User.find(u.id) assert_equal c, u.favorite_car u.favorite_car = nil assert u.save assert_nil u.favorite_car u.favorite_car = c assert u.save assert_equal c, u.favorite_car c.destroy assert_equal c, u.favorite_car u = User.find(u.id) assert_nil u.favorite_car end def test_redis_objects u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_equal false, User.connection(:redis).exists(u.num_logins.key) assert_equal 0, u.num_logins.count u.num_logins.incr assert_equal 1, u.num_logins.count assert_equal true, User.connection(:redis).exists(u.num_logins.key) u.num_logins.incr_by 10 assert_equal 11, u.num_logins.count u.destroy assert_equal false, User.connection(:redis).exists(u.num_logins.key) end def test_rich_attributes u = User.new u.id = User.new_uuid u.updated_at = Time.now.utc assert u.updated_at.is_a?(Time) u.name = "ben" assert u.save u = User.find(u.id) assert u.updated_at.is_a?(Time) end + + def test_conflicts + Car.connection(:riak_raw).client_id = "Client1" + c = Car.new + c.id = Car.new_uuid + c.make = "Nissan" + c.model = "Versa" + c.year = 2009 + assert c.save + + c2 = c.clone + Car.connection(:riak_raw).client_id = "Client2" + c2.year = 2008 + assert c2.save + + assert !c2.in_conflict? + + Car.connection(:riak_raw).client_id = "Client3" + c.year = 2007 + assert c.save + + assert c.in_conflict? + assert_raise(Chimera::Error::CannotSaveWithConflicts) { c.save } + + c2 = Car.find(c.id) + #puts c2.attributes.inspect + #puts c2.sibling_attributes.inspect + + c.attributes = c.sibling_attributes.first[1].dup + c.year = 2006 + assert c.resolve_and_save + + assert !c.in_conflict? + + c = Car.find(c.id) + assert !c.in_conflict? + assert_equal 2006, c.year + end + + # test based on http://blog.basho.com/2010/01/29/why-vector-clocks-are-easy/ + def test_riak_siblings + Chimera::Base.connection(:riak_raw).delete("plans","dinner") + props = Chimera::Base.connection(:riak_raw).bucket("plans") + props["props"]["allow_mult"] = true + Chimera::Base.connection(:riak_raw).set_bucket_properties("plans",props) + props = Chimera::Base.connection(:riak_raw).bucket("plans") + + alice_client = Chimera::Base.new_connection(:riak_raw) + alice_client.client_id = "Alice" + + ben_client = Chimera::Base.new_connection(:riak_raw) + ben_client.client_id = "Ben" + + kathy_client = Chimera::Base.new_connection(:riak_raw) + kathy_client.client_id = "Kathy" + + dave_client = Chimera::Base.new_connection(:riak_raw) + dave_client.client_id = "Dave" + + alice_resp = alice_client.store("plans","dinner","Wednesday") + + # When Ben, Kathy, and Dave each GET Alice's plans, they'll get the same vector clock + ben_resp = ben_client.fetch("plans","dinner") + kathy_resp = kathy_client.fetch("plans","dinner") + dave_resp = dave_client.fetch("plans","dinner") + + # Now when Ben sends his change to Dave, he includes both the vector clock he pulled down + # (in the X-Riak-Vclock header), and his own X-Riak-Client-Id: + ben_resp = ben_client.store("plans","dinner","Tuesday",ben_resp.headers_hash['X-Riak-Vclock']) + # Dave pulls down a fresh copy, and then confirms Tuesday: + dave_resp = dave_client.fetch("plans","dinner") + dave_resp = dave_client.store("plans","dinner","Tuesday",dave_resp.headers_hash['X-Riak-Vclock']) + # Kathy, on the other hand, hasn't pulled down a new version, and instead merely updated + # the plans with her suggestion of Thursday: + kathy_client.store("plans","dinner","Thursday",kathy_resp.headers_hash['X-Riak-Vclock']) + + # Now, when Dave goes to grab this new copy (after Cathy tells him she has posted it), he'll + # see one of two things. If the "plans" Riak bucket has the allow_mult property set to false, + # he'll see just Cathy's update. If allow_mult is true for the "plans" bucket, he'll see both + # his last update and Cathy's. I'm going to show the allow_mult=true version below, because I + # think it illustrates the flow better. + dave_resp = dave_client.fetch("plans","dinner") + + assert dave_resp.body =~ /^Siblings/ + siblings = dave_resp.body.split("\n")[1..-1] + # puts siblings.inspect + # puts dave_resp.code + + sib1 = dave_client.fetch("plans","dinner",:vtag => siblings[0]) + # puts sib1.body + end end
benmyles/chimera
3a35b3aa37156fc7c5309726affeb147b5030221
formatting
diff --git a/README.rdoc b/README.rdoc index 72ee8bd..c5672d2 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,127 +1,126 @@ = chimera * http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). !! Chimera is alpha. It's not production tested and needs a better test suite. !! !! It's also only tested in Ruby 1.9. !! == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. * Uses Typhoeus for communicating with Riak. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Only tested with Ruby 1.9. Why not upgrade? * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :union) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * Ruby 1.9 * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == USEFUL LINKS: -* http://groups.google.com/group/chimera-lib - -Email: ben dot myles at gmail dot com -Twitter: benmyles +* Discussion: http://groups.google.com/group/chimera-lib +* Email: ben dot myles at gmail dot com +* Twitter: benmyles == LICENSE: (The MIT License) Copyright (c) 2010 Ben Myles 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. \ No newline at end of file
benmyles/chimera
1d89f8f21938486514e3809f37ff261636021630
add my name in the license, email and twitter
diff --git a/README.rdoc b/README.rdoc index fa49601..72ee8bd 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,124 +1,127 @@ = chimera * http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). !! Chimera is alpha. It's not production tested and needs a better test suite. !! !! It's also only tested in Ruby 1.9. !! == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. * Uses Typhoeus for communicating with Riak. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Only tested with Ruby 1.9. Why not upgrade? * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :union) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * Ruby 1.9 * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == USEFUL LINKS: * http://groups.google.com/group/chimera-lib +Email: ben dot myles at gmail dot com +Twitter: benmyles + == LICENSE: (The MIT License) -Copyright (c) 2010 FIXME full name +Copyright (c) 2010 Ben Myles 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. \ No newline at end of file
benmyles/chimera
8cb75e63cc619301999e91d57030ac0ac3971679
add ruby 1.9 as a requirement
diff --git a/README.rdoc b/README.rdoc index f1a2fa2..fa49601 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,122 +1,124 @@ = chimera * http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). !! Chimera is alpha. It's not production tested and needs a better test suite. !! !! It's also only tested in Ruby 1.9. !! == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. * Uses Typhoeus for communicating with Riak. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Only tested with Ruby 1.9. Why not upgrade? * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :union) => [c] Car.find_with_index(:description, :q => "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server +* Ruby 1.9 + * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == USEFUL LINKS: * http://groups.google.com/group/chimera-lib == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file
benmyles/chimera
3adc091ff756534dc0d87a3260c5993f08238d7b
add a note about being alpha
diff --git a/README.rdoc b/README.rdoc index 96e9793..bc6826e 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,117 +1,119 @@ = chimera * http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). +!! Chimera is alpha. It's not production tested and needs a better test suite. !! + == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, "rigid boat", :type => :union) => [c] Car.find_with_index(:description, "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == USEFUL LINKS: * http://groups.google.com/group/chimera-lib == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file diff --git a/pkg/chimera-0.0.2.gem b/pkg/chimera-0.0.2.gem new file mode 100644 index 0000000..fbb5e36 Binary files /dev/null and b/pkg/chimera-0.0.2.gem differ diff --git a/pkg/chimera-0.0.3.gem b/pkg/chimera-0.0.3.gem new file mode 100644 index 0000000..79f8324 Binary files /dev/null and b/pkg/chimera-0.0.3.gem differ
benmyles/chimera
9f4fb189ab2ad7783ee98b99c63240f50c153611
bump version again for readme
diff --git a/README.rdoc b/README.rdoc index edd5584..96e9793 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,118 +1,117 @@ = chimera * http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" - gem "chimera", "0.0.2" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, "rigid boat", :type => :union) => [c] Car.find_with_index(:description, "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == USEFUL LINKS: * http://groups.google.com/group/chimera-lib == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file diff --git a/lib/chimera.rb b/lib/chimera.rb index c3ce9e2..18b7405 100644 --- a/lib/chimera.rb +++ b/lib/chimera.rb @@ -1,33 +1,33 @@ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) gem 'uuidtools','= 2.1.1' gem 'activemodel','= 3.0.0.beta' gem "yajl-ruby", "= 0.7.4" gem "fast-stemmer", "= 1.0.0" require 'fast_stemmer' require 'digest/sha1' require 'uuidtools' require 'yajl' require 'yaml' require 'active_model' require 'redis' require 'typhoeus' require 'riak_raw' require "chimera/error" require "chimera/attributes" require "chimera/indexes" require "chimera/geo_indexes" require "chimera/associations" require "chimera/redis_objects" require "chimera/finders" require "chimera/persistence" require "chimera/base" module Chimera - VERSION = '0.0.2' + VERSION = '0.0.3' end \ No newline at end of file
benmyles/chimera
4b825e9b9d9372c2e5295366b64f07d637dd24ae
added link to google group
diff --git a/README.rdoc b/README.rdoc index 55412d4..edd5584 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,114 +1,118 @@ = chimera * http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" gem "chimera", "0.0.2" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, "rigid boat", :type => :union) => [c] Car.find_with_index(:description, "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera + +== USEFUL LINKS: + +* http://groups.google.com/group/chimera-lib == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file
benmyles/chimera
42275196cecf1a5e106f42c61d657a5274aaa48a
fix homepage
diff --git a/README.rdoc b/README.rdoc index 336f422..55412d4 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,114 +1,114 @@ = chimera -* http://github.com/#{github_username}/#{project_name} +* http://github.com/benmyles/chimera == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" gem "chimera", "0.0.2" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, "rigid boat", :type => :union) => [c] Car.find_with_index(:description, "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file
benmyles/chimera
188292d3bfa6290a6c7f9f8ae116bfc5ca3c255c
new version
diff --git a/README.rdoc b/README.rdoc index 9202abf..336f422 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,114 +1,114 @@ = chimera * http://github.com/#{github_username}/#{project_name} == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" - gem "chimera", "0.0.1" + gem "chimera", "0.0.2" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, "rigid boat", :type => :union) => [c] Car.find_with_index(:description, "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file diff --git a/lib/chimera.rb b/lib/chimera.rb index c1087ff..c3ce9e2 100644 --- a/lib/chimera.rb +++ b/lib/chimera.rb @@ -1,33 +1,33 @@ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) gem 'uuidtools','= 2.1.1' gem 'activemodel','= 3.0.0.beta' gem "yajl-ruby", "= 0.7.4" gem "fast-stemmer", "= 1.0.0" require 'fast_stemmer' require 'digest/sha1' require 'uuidtools' require 'yajl' require 'yaml' require 'active_model' require 'redis' require 'typhoeus' require 'riak_raw' require "chimera/error" require "chimera/attributes" require "chimera/indexes" require "chimera/geo_indexes" require "chimera/associations" require "chimera/redis_objects" require "chimera/finders" require "chimera/persistence" require "chimera/base" module Chimera - VERSION = '0.0.1' + VERSION = '0.0.2' end \ No newline at end of file
benmyles/chimera
84eb06c10b4791cfe2a974b2983556b26cfbe658
repackaged gem
diff --git a/pkg/chimera-0.0.1.gem b/pkg/chimera-0.0.1.gem index 6652c64..4c44505 100644 Binary files a/pkg/chimera-0.0.1.gem and b/pkg/chimera-0.0.1.gem differ
benmyles/chimera
276517a11a3ec83dc3ab47d52d8d4c1c47ed83f4
use yajl ruby
diff --git a/README.rdoc b/README.rdoc index a1e99e4..9202abf 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,114 +1,114 @@ = chimera * http://github.com/#{github_username}/#{project_name} == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" gem "chimera", "0.0.1" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, "rigid boat", :type => :union) => [c] Car.find_with_index(:description, "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 -* brianmario-yajl-ruby 0.6.3 +* yajl-ruby 0.7.4 * fast-stemmer 1.0.0 == INSTALL: $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre $ gem install chimera == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file diff --git a/Rakefile b/Rakefile index 583f4cb..e227c10 100644 --- a/Rakefile +++ b/Rakefile @@ -1,30 +1,30 @@ require 'rubygems' gem 'hoe', '>= 2.1.0' require 'hoe' require 'fileutils' require './lib/chimera' Hoe.plugin :newgem # Hoe.plugin :website # Hoe.plugin :cucumberfeatures # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) $hoe = Hoe.spec 'chimera' do self.developer 'Ben Myles', '[email protected]' self.post_install_message = 'PostInstall.txt' # TODO remove if post-install message not required self.rubyforge_name = self.name # TODO this is default value # self.extra_deps = [['activesupport','>= 2.0.2']] self.extra_deps = [["activesupport","= 3.0.0.beta"], ["uuidtools","= 2.1.1"], ["activemodel",'= 3.0.0.beta'], - ["brianmario-yajl-ruby","= 0.6.3"], + ["yajl-ruby","= 0.7.4"], ["fast-stemmer", "= 1.0.0"]] end require 'newgem/tasks' Dir['tasks/**/*.rake'].each { |t| load t } # TODO - want other tests/tasks run by default? Add them to the list # remove_task :default # task :default => [:spec, :features] diff --git a/lib/chimera.rb b/lib/chimera.rb index e4d3900..c1087ff 100644 --- a/lib/chimera.rb +++ b/lib/chimera.rb @@ -1,33 +1,33 @@ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) gem 'uuidtools','= 2.1.1' gem 'activemodel','= 3.0.0.beta' -gem "brianmario-yajl-ruby", "= 0.6.3" +gem "yajl-ruby", "= 0.7.4" gem "fast-stemmer", "= 1.0.0" require 'fast_stemmer' require 'digest/sha1' require 'uuidtools' require 'yajl' require 'yaml' require 'active_model' require 'redis' require 'typhoeus' require 'riak_raw' require "chimera/error" require "chimera/attributes" require "chimera/indexes" require "chimera/geo_indexes" require "chimera/associations" require "chimera/redis_objects" require "chimera/finders" require "chimera/persistence" require "chimera/base" module Chimera VERSION = '0.0.1' end \ No newline at end of file diff --git a/pkg/chimera-0.0.1.gem b/pkg/chimera-0.0.1.gem index 0873775..6652c64 100644 Binary files a/pkg/chimera-0.0.1.gem and b/pkg/chimera-0.0.1.gem differ
benmyles/chimera
a3a7482aa21d4b003ff2911d5898438ae3f5a4dc
more indentaiton
diff --git a/README.rdoc b/README.rdoc index b7237b6..a1e99e4 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,114 +1,114 @@ = chimera * http://github.com/#{github_username}/#{project_name} == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: - require "rubygems" - gem "chimera", "0.0.1" - require "chimera" + require "rubygems" + gem "chimera", "0.0.1" + require "chimera" - Chimera.config_path = "path/to/your/config.yml" + Chimera.config_path = "path/to/your/config.yml" - class Car < Chimera::Base - attribute :vin - attribute :make - attribute :model - attribute :year - attribute :description + class Car < Chimera::Base + attribute :vin + attribute :make + attribute :model + attribute :year + attribute :description - index :year, :type => :find - index :description, :type => :search - index :vin, :type => :unique + index :year, :type => :find + index :description, :type => :search + index :vin, :type => :unique - validates_presence_of :vin, :make, :model, :year - end + validates_presence_of :vin, :make, :model, :year + end - c = Car.new - c.id = Car.new_uuid - c.vin = 12345 - c.make = "Pagani" - c.model = "Zonda Cinque Roadster" - c.year = 2010 - c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." - c.save + c = Car.new + c.id = Car.new_uuid + c.vin = 12345 + c.make = "Pagani" + c.model = "Zonda Cinque Roadster" + c.year = 2010 + c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." + c.save - Car.find_with_index(:year, 2010) - => [c] + Car.find_with_index(:year, 2010) + => [c] - Car.find_with_index(:description, "rigid boat", :type => :union) - => [c] + Car.find_with_index(:description, "rigid boat", :type => :union) + => [c] - Car.find_with_index(:description, "rigid boat", :type => :intersect) - => [] + Car.find_with_index(:description, "rigid boat", :type => :intersect) + => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta * uuidtools 2.1.1 * brianmario-yajl-ruby 0.6.3 * fast-stemmer 1.0.0 == INSTALL: - $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n - $ gem install rails --pre + $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n + $ gem install rails --pre $ gem install chimera == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file
benmyles/chimera
51883fe014fef7eefbae3a1bba9bf3e720c2737d
more indentaiton
diff --git a/README.rdoc b/README.rdoc index e9693b9..b7237b6 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,114 +1,114 @@ = chimera * http://github.com/#{github_username}/#{project_name} == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" gem "chimera", "0.0.1" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, "rigid boat", :type => :union) => [c] Car.find_with_index(:description, "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta - $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n - $ gem install rails --pre * uuidtools 2.1.1 * brianmario-yajl-ruby 0.6.3 * fast-stemmer 1.0.0 == INSTALL: + $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n + $ gem install rails --pre $ gem install chimera == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file
benmyles/chimera
c9b298382b39ac1c55a225a8e34e034b77cbb0de
more indentaiton
diff --git a/README.rdoc b/README.rdoc index f430265..e9693b9 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,114 +1,114 @@ = chimera * http://github.com/#{github_username}/#{project_name} == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: require "rubygems" gem "chimera", "0.0.1" require "chimera" Chimera.config_path = "path/to/your/config.yml" class Car < Chimera::Base attribute :vin attribute :make attribute :model attribute :year attribute :description index :year, :type => :find index :description, :type => :search index :vin, :type => :unique validates_presence_of :vin, :make, :model, :year end c = Car.new c.id = Car.new_uuid c.vin = 12345 c.make = "Pagani" c.model = "Zonda Cinque Roadster" c.year = 2010 c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." c.save Car.find_with_index(:year, 2010) => [c] Car.find_with_index(:description, "rigid boat", :type => :union) => [c] Car.find_with_index(:description, "rigid boat", :type => :intersect) => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta -$ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n -$ gem install rails --pre + $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n + $ gem install rails --pre * uuidtools 2.1.1 * brianmario-yajl-ruby 0.6.3 * fast-stemmer 1.0.0 == INSTALL: -* gem install chimera + $ gem install chimera == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file
benmyles/chimera
18dd979eb3e71c0fb730c91731e28939f7aaf9d6
indentation
diff --git a/README.rdoc b/README.rdoc index 3a50233..f430265 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,114 +1,114 @@ = chimera * http://github.com/#{github_username}/#{project_name} == DESCRIPTION: Chimera is an object mapper for Riak and Redis. The idea is to mix the advantages of Riak (scalability, massive data storage) with Redis (atomicity, performance, data structures). You should store the bulk of your data in Riak, and then use Redis data structures where appropriate (for example, a counter or set of keys). Internally, Chimera uses Redis for any indexes you define as well as some default indexes that are automatically created. There's no built in sharding for Redis, but since it's only being used for key storage and basic data elements you should be able to go a long way with one Redis server (especially if you use the new Redis VM). == FEATURES: * Uses Riak (http://riak.basho.com/) for your primary storage. * Uses Redis for indexes and also allows you to define Redis objects on a model. * Supports unique and non-unique indexes, as well as basic search indexes (words are stemmed, uses set intersection so you can get an AND/OR search). * Supports a geospatial index type for simple storage and lookup of coordinates. == ISSUES/NOTES: * Experimental. Not yet tested in production environment, use at your own risk. * Test coverage needs to be improved. * Documentation is lacking. At the moment reading the tests and sample test/models.rb file are your best bet. == SYNOPSIS: -require "rubygems" -gem "chimera", "0.0.1" -require "chimera" - -Chimera.config_path = "path/to/your/config.yml" - -class Car < Chimera::Base - attribute :vin - attribute :make - attribute :model - attribute :year - attribute :description - - index :year, :type => :find - index :description, :type => :search - index :vin, :type => :unique - - validates_presence_of :vin, :make, :model, :year -end - -c = Car.new -c.id = Car.new_uuid -c.vin = 12345 -c.make = "Pagani" -c.model = "Zonda Cinque Roadster" -c.year = 2010 -c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." -c.save - -Car.find_with_index(:year, 2010) -=> [c] - -Car.find_with_index(:description, "rigid boat", :type => :union) -=> [c] - -Car.find_with_index(:description, "rigid boat", :type => :intersect) -=> [] + require "rubygems" + gem "chimera", "0.0.1" + require "chimera" + + Chimera.config_path = "path/to/your/config.yml" + + class Car < Chimera::Base + attribute :vin + attribute :make + attribute :model + attribute :year + attribute :description + + index :year, :type => :find + index :description, :type => :search + index :vin, :type => :unique + + validates_presence_of :vin, :make, :model, :year + end + + c = Car.new + c.id = Car.new_uuid + c.vin = 12345 + c.make = "Pagani" + c.model = "Zonda Cinque Roadster" + c.year = 2010 + c.description = "The Roadster will have specs as the Cinque Coupé, and will likely maintain the same rigidity or more, as it was for the Roadster F and F Coupé." + c.save + + Car.find_with_index(:year, 2010) + => [c] + + Car.find_with_index(:description, "rigid boat", :type => :union) + => [c] + + Car.find_with_index(:description, "rigid boat", :type => :intersect) + => [] * See tests for more usage examples == REQUIREMENTS: * Riak Server * Redis Server * ActiveSupport+ActiveModel 3.0.0.beta $ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n $ gem install rails --pre * uuidtools 2.1.1 * brianmario-yajl-ruby 0.6.3 * fast-stemmer 1.0.0 == INSTALL: * gem install chimera == LICENSE: (The MIT License) Copyright (c) 2010 FIXME full name 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. \ No newline at end of file
benmyles/chimera
3b8e98d01bc107ebbef12243c3e9767a631f34ef
added pkg files
diff --git a/pkg/chimera-0.0.1.gem b/pkg/chimera-0.0.1.gem new file mode 100644 index 0000000..0873775 Binary files /dev/null and b/pkg/chimera-0.0.1.gem differ
benmyles/chimera
fbc29af55350c76e38af2215e4c08547b796bf1f
now everything is encoded with yaml
diff --git a/Manifest.txt b/Manifest.txt index 81e06cf..4212f2b 100644 --- a/Manifest.txt +++ b/Manifest.txt @@ -1,11 +1,57 @@ +doc/examples/config.yml +doc/NOTES +doc/redis6379.conf History.txt +lib/chimera/associations.rb +lib/chimera/attributes.rb +lib/chimera/base.rb +lib/chimera/config.rb +lib/chimera/error.rb +lib/chimera/finders.rb +lib/chimera/geo_indexes.rb +lib/chimera/indexes.rb +lib/chimera/persistence.rb +lib/chimera/redis_objects.rb +lib/chimera.rb +lib/redis/counter.rb +lib/redis/dist_redis.rb +lib/redis/hash_ring.rb +lib/redis/helpers +lib/redis/helpers/core_commands.rb +lib/redis/helpers/serialize.rb +lib/redis/list.rb +lib/redis/lock.rb +lib/redis/objects +lib/redis/objects/counters.rb +lib/redis/objects/lists.rb +lib/redis/objects/locks.rb +lib/redis/objects/sets.rb +lib/redis/objects/values.rb +lib/redis/objects.rb +lib/redis/pipeline.rb +lib/redis/set.rb +lib/redis/value.rb +lib/redis.rb +lib/riak_raw.rb +lib/typhoeus/.gitignore +lib/typhoeus/easy.rb +lib/typhoeus/filter.rb +lib/typhoeus/hydra.rb +lib/typhoeus/multi.rb +lib/typhoeus/remote.rb +lib/typhoeus/remote_method.rb +lib/typhoeus/remote_proxy_object.rb +lib/typhoeus/request.rb +lib/typhoeus/response.rb +lib/typhoeus/service.rb +lib/typhoeus.rb Manifest.txt PostInstall.txt -README.rdoc Rakefile -lib/chimera.rb +README.rdoc script/console script/destroy script/generate -test/test_helper.rb +test/models.rb test/test_chimera.rb +test/test_helper.rb diff --git a/Rakefile b/Rakefile index 7ee7ba6..583f4cb 100644 --- a/Rakefile +++ b/Rakefile @@ -1,29 +1,30 @@ require 'rubygems' gem 'hoe', '>= 2.1.0' require 'hoe' require 'fileutils' require './lib/chimera' Hoe.plugin :newgem # Hoe.plugin :website # Hoe.plugin :cucumberfeatures # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) $hoe = Hoe.spec 'chimera' do - self.developer 'FIXME full name', 'FIXME email' + self.developer 'Ben Myles', '[email protected]' self.post_install_message = 'PostInstall.txt' # TODO remove if post-install message not required self.rubyforge_name = self.name # TODO this is default value # self.extra_deps = [['activesupport','>= 2.0.2']] self.extra_deps = [["activesupport","= 3.0.0.beta"], ["uuidtools","= 2.1.1"], ["activemodel",'= 3.0.0.beta'], - ["brianmario-yajl-ruby","= 0.6.3"]] + ["brianmario-yajl-ruby","= 0.6.3"], + ["fast-stemmer", "= 1.0.0"]] end require 'newgem/tasks' Dir['tasks/**/*.rake'].each { |t| load t } # TODO - want other tests/tasks run by default? Add them to the list # remove_task :default # task :default => [:spec, :features] diff --git a/lib/chimera.rb b/lib/chimera.rb index 2e645d6..e4d3900 100644 --- a/lib/chimera.rb +++ b/lib/chimera.rb @@ -1,32 +1,33 @@ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) gem 'uuidtools','= 2.1.1' gem 'activemodel','= 3.0.0.beta' gem "brianmario-yajl-ruby", "= 0.6.3" gem "fast-stemmer", "= 1.0.0" require 'fast_stemmer' require 'digest/sha1' require 'uuidtools' require 'yajl' +require 'yaml' require 'active_model' require 'redis' require 'typhoeus' require 'riak_raw' require "chimera/error" require "chimera/attributes" require "chimera/indexes" require "chimera/geo_indexes" require "chimera/associations" require "chimera/redis_objects" require "chimera/finders" require "chimera/persistence" require "chimera/base" module Chimera VERSION = '0.0.1' end \ No newline at end of file diff --git a/lib/chimera/attributes.rb b/lib/chimera/attributes.rb index 992f29b..032aab4 100644 --- a/lib/chimera/attributes.rb +++ b/lib/chimera/attributes.rb @@ -1,53 +1,52 @@ module Chimera module Attributes def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def defined_attributes @defined_attributes || {} end - # available types include: - # string, integer, yaml, json, coordinate - def attribute(name, type = :string, extra_opts={}) + # available types include: model + def attribute(name, type = nil, extra_opts={}) @defined_attributes ||= {} @defined_attributes[name.to_sym] = [type, extra_opts] define_method("#{name}") do return nil unless @attributes if type == :model @cached_attributes ||= {} @cached_attributes[name.to_sym] ||= begin model_id = @attributes[name.to_sym] klass = extra_opts[:class] if model_id && klass eval(klass.to_s.camelize).find(model_id) end end else @attributes[name.to_sym] end end define_method("#{name}=") do |val| return nil unless @attributes if type == :model @cached_attributes ||= {} @cached_attributes.delete(name.to_sym) if val.respond_to?(:id) @attributes[name.to_sym] = val.id else @attributes.delete(name.to_sym) end else @attributes @attributes[name.to_sym] = val end end end end # ClassMethods module InstanceMethods end # InstanceMethods end end \ No newline at end of file diff --git a/lib/chimera/finders.rb b/lib/chimera/finders.rb index 756b9e4..5e18fee 100644 --- a/lib/chimera/finders.rb +++ b/lib/chimera/finders.rb @@ -1,49 +1,49 @@ module Chimera module Finders def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def each self.find_with_index(:all) { |obj| yield(obj) } end def find(key) find_many(key)[0] end def find_many(keys) keys = Array(keys) found = [] threads = [] keys.each do |key| threads << Thread.new do if key resp = self.connection(:riak_raw).fetch(self.to_s, key) if resp.code == 200 - if resp.body and json_hash = Yajl::Parser.parse(resp.body) + if resp.body and yaml_hash = YAML.load(resp.body) hash = {} - json_hash.each { |k,v| hash[k.to_sym] = v } + yaml_hash.each { |k,v| hash[k.to_sym] = v } obj = self.new(hash,key,false) obj.riak_response = resp found << obj else obj = self.new({},key,false) obj.riak_response = resp found << obj end end end end # Thread.new end # keys.each threads.each { |th| th.join } found end # find_many end # ClassMethods module InstanceMethods end # InstanceMethods end end \ No newline at end of file diff --git a/lib/chimera/persistence.rb b/lib/chimera/persistence.rb index 911f18e..fdb495f 100644 --- a/lib/chimera/persistence.rb +++ b/lib/chimera/persistence.rb @@ -1,70 +1,70 @@ module Chimera module Persistence def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods end # ClassMethods module InstanceMethods def new? @new == true end def save raise(Chimera::Error::SaveWithoutId) unless self.id raise(Chimera::Error::ValidationErrors) unless self.valid? check_index_constraints if new? _run_create_callbacks do _run_save_callbacks do save_without_callbacks create_indexes end end else _run_save_callbacks do destroy_indexes save_without_callbacks create_indexes end end true end alias :create :save def vector_clock if @riak_response and @riak_response.headers_hash return @riak_response.headers_hash["X-Riak-Vclock"] end; nil end def save_without_callbacks @riak_response = self.class.connection(:riak_raw).store( self.class.bucket_key, self.id, - Yajl::Encoder.encode(@attributes), + YAML.dump(@attributes), self.vector_clock) @orig_attributes = @attributes.clone @new = false end def destroy _run_destroy_callbacks do @riak_response = self.class.connection(:riak_raw).delete(self.class.bucket_key, self.id) destroy_indexes association_memberships.destroy destroy_associations destroy_redis_objects freeze end end end # InstanceMethods end end \ No newline at end of file diff --git a/lib/chimera/redis_objects.rb b/lib/chimera/redis_objects.rb index 5d3c83a..e5c1907 100644 --- a/lib/chimera/redis_objects.rb +++ b/lib/chimera/redis_objects.rb @@ -1,335 +1,345 @@ module Chimera module RedisObjects def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def defined_redis_objects @defined_redis_objects || {} end # available types include: # string, set, zset, list, counter def redis_object(name, type = :string, extra_opts={}) @defined_redis_objects ||= {} @defined_redis_objects[name.to_sym] = [type, extra_opts] define_method("#{name}") do @redis_objects ||= {} case type when :string then @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::String.new(self, name, extra_opts) when :set then @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::Set.new(self, name, extra_opts) when :zset then @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::ZSet.new(self, name, extra_opts) when :list then @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::List.new(self, name, extra_opts) when :counter then @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::Counter.new(self, name, extra_opts) end end end end # ClassMethods module InstanceMethods def destroy_redis_objects (@redis_objects || {}).each do |name, redis_obj| redis_obj.destroy end end end # InstanceMethods end module RedisObjectProxy class Base attr_accessor :owner, :name, :extra_opts def initialize(owner, name, extra_opts) unless owner and owner.id raise(Chimera::Errors::MissingId) end @owner = owner @name = name @extra_opts = extra_opts end def connection self.owner.class.connection(:redis) end def key "#{self.class.to_s}::RedisObjects::#{name}::#{self.owner.id}" end def destroy connection.del(self.key) end + + def encode(val) + YAML.dump(val) + end + + def decode(val) + return nil if val.nil? + return "" if val == "" + YAML.load(val) + end end class Collection < Base def sort(opts={}) cmd = [self.key] cmd << "BY #{opts[:by_pattern]}" if opts[:by_pattern] if opts[:limit] start, count = opts[:limit] cmd << "LIMIT #{start} #{count}" if start && count end cmd << "GET #{opts[:get_pattern]}" if opts[:get_pattern] cmd << opts[:order] if opts[:order] cmd << "ALPHA" if opts[:alpha] == true cmd << "STORE #{opts[:dest_key]}" if opts[:dest_key] connection.sort(self.key, cmd.join(" ")) end end class String < Base def set(val) - connection.set(self.key, val) + connection.set(self.key, encode(val)) end def get - connection.get(self.key) + decode(connection.get(self.key)) end end class Set < Collection def add(val) - connection.sadd(self.key, val) + connection.sadd(self.key, encode(val)) end def <<(val) add(val) end def rem(val) - connection.srem(self.key, val) + connection.srem(self.key, encode(val)) end def pop - connection.spop(self.key) + decode connection.spop(self.key) end def move(val, dest_set_key) - connection.smove(self.key, dest_set_key, val) + connection.smove(self.key, dest_set_key, encode(val)) end def card connection.scard(self.key) end alias :size :card alias :count :card def ismember(val) - connection.sismember(self.key, val) + connection.sismember(self.key, encode(val)) end alias :is_member? :ismember alias :include? :ismember alias :includes? :ismember alias :contains? :ismember def inter(*set_keys) - connection.sinter(set_keys.join(" ")) + (connection.sinter(set_keys.join(" ")) || []).collect { |val| decode(val) } end alias :intersect :inter def interstore(dest_key, *set_keys) connection.sinterstore(dest_key, set_keys.join(" ")) end alias :intersect_and_store :interstore def union(*set_keys) - connection.sunion(set_keys.join(" ")) + (connection.sunion(set_keys.join(" ")) || []).collect { |val| decode(val) } end def unionstore(dest_key, *set_keys) connection.sunionstore(dest_key, set_keys.join(" ")) end alias :union_and_store :unionstore def diff(*set_keys) - connection.sdiff(set_keys.join(" ")) + (connection.sdiff(set_keys.join(" ")) || []).collect { |val| decode(val) } end def diffstore(dest_key, *set_keys) connection.sdiffstore(dest_key, set_keys.join(" ")) end alias :diff_and_store :diffstore def members - connection.smembers(self.key) + (connection.smembers(self.key) || []).collect { |val| decode(val) } end alias :all :members def randmember - connection.srandmember(self.key) + decode connection.srandmember(self.key) end alias :rand_member :randmember end class ZSet < Collection def add(val,score=0) - connection.zadd(self.key, score, val) + connection.zadd(self.key, score, encode(val)) end def rem(val) - connection.zrem(self.key, val) + connection.zrem(self.key, encode(val)) end def incrby(val, incr) - connection.zincrby(self.key, incr, val) + connection.zincrby(self.key, incr.to_f, encode(val)) end alias :incr_by :incrby def range(start_index, end_index, extra_opts={}) - opts = [self.key, start_index, end_index] + opts = [self.key, start_index.to_i, end_index.to_i] opts << "WITHSCORES" if extra_opts[:with_scores] == true - connection.zrange(opts) + (connection.zrange(opts) || []).collect { |val| decode(val) } end def revrange(start_index, end_index, extra_opts={}) - opts = [self.key, start_index, end_index] + opts = [self.key, start_index.to_i, end_index.to_i] opts << "WITHSCORES" if extra_opts[:with_scores] == true - connection.zrevrange(opts) + (connection.zrevrange(opts) || []).collect { |val| decode(val) } end alias :rev_range :revrange def rangebyscore(min, max, extra_opts={}) - opts = [self.key, min, max] + opts = [self.key, min.to_f, max.to_f] offset, count = extra_opts[:limit] if offset and count opts << "LIMIT #{offset} #{count}" end opts << "WITHSCORES" if extra_opts[:with_scores] == true - connection.zrangebyscore(opts) + (connection.zrangebyscore(opts) || []).collect { |val| decode(val) } end alias :range_by_score :rangebyscore def remrangebyscore(min,max) - connection.zremrangebyscore(self.key,min,max) + connection.zremrangebyscore(self.key,min.to_f,max.to_f) end alias :rem_range_by_score :remrangebyscore alias :remove_range_by_score :remrangebyscore def card - connection.zcard(self.key) + connection.zcard(self.key).to_i end alias :size :card alias :count :card def score(val) - connection.zscore(self.key, val) + connection.zscore(self.key, val).to_f end end class List < Collection def rpush(val) - connection.rpush(self.key, val) + connection.rpush(self.key, encode(val)) end alias :right_push :rpush def <<(val) rpush(val) end def lpush(val) - connection.lpush(self.key, val) + connection.lpush(self.key, encode(val)) end alias :left_push :lpush def len - connection.len(self.key) + connection.len(self.key).to_i end alias :size :len alias :count :len def range(start_index, end_index) - connection.lrange(self.key, start_index, end_index) + (connection.lrange(self.key, start_index.to_i, end_index.to_i) || []).collect { |val| decode(val) } end def trim(start_index, end_index) - connection.ltrim(self.key, start_index, end_index) + connection.ltrim(self.key, start_index.to_i, end_index.to_i) end def index(index) - connection.lindex(self.key, index) + decode connection.lindex(self.key, index.to_i) end def [](index) self.index(index) end def set(index, val) - connection.lset(self.key, index, val) + connection.lset(self.key, index.to_i, encode(val)) end def rem(val, count=0) - connection.lrem(self.key, count, val) + connection.lrem(self.key, count.to_i, encode(val)) end def lpop - connection.lpop(self.key) + decode connection.lpop(self.key) end alias :left_pop :lpop alias :pop :lpop def rpop - connection.rpop(self.key) + decode connection.rpop(self.key) end alias :right_pop :rpop def rpoplpush(dest_key) - connection.rpoplpush(self.key, dest_key) + decode connection.rpoplpush(self.key, dest_key) end alias :right_pop_left_push :rpoplpush end class Counter < Base def incr - connection.incr(self.key) + connection.incr(self.key).to_i end def incrby(val) - connection.incrby(self.key,val) + connection.incrby(self.key,val.to_i).to_i end alias :incr_by :incrby def decr - connection.decr(self.key) + connection.decr(self.key).to_i end def decrby(val) - connection.decrby(self.key, val) + connection.decrby(self.key, val.to_i).to_i end def val connection.get(self.key).to_i end alias :count :val alias :decr_by :decrby end end end \ No newline at end of file diff --git a/test/models.rb b/test/models.rb index 57e12b3..087ec34 100644 --- a/test/models.rb +++ b/test/models.rb @@ -1,48 +1,49 @@ class User < Chimera::Base use_config :default # this is implied even if not here - attribute :name, :string - attribute :age, :integer - attribute :occupation, :string - attribute :interests, :json - attribute :home_coordinate, :coordinate # [37.2,122.1] - attribute :ssn, :string + attribute :name + attribute :age + attribute :occupation + attribute :interests + attribute :home_coordinate # [37.2,122.1] + attribute :ssn + attribute :updated_at attribute :favorite_car, :model, :class => :car # User.find_with_index(:home_coordinate, {:coordinate => [37.2,122.1], :steps => 5}) index :home_coordinate, :type => :geo, :step_size => 0.05 # User.find_with_index(:occupation, { :q => "developer", :type => :intersect } ) # fuzzy search. :intersect or :union index :occupation, :type => :search # User.find_with_index(:ssn, "12345") # exact search, enforces unique constraint index :ssn, :type => :unique # User.find_with_index(:name, "Ben") # like :search but exact index :name, :type => :find association :friends, :user association :cars, :car redis_object :num_logins, :counter validates_presence_of :name end class Car < Chimera::Base attribute :color attribute :make attribute :model - attribute :year, :integer - attribute :mileage, :integer + attribute :year + attribute :mileage attribute :comments attribute :sku - attribute :curr_location, :coordinate + attribute :curr_location index :year, :type => :find index :comments, :type => :search index :sku, :type => :unique index :curr_location, :type => :geo, :step_size => 0.05 validates_presence_of :make, :model, :year end \ No newline at end of file diff --git a/test/test_chimera.rb b/test/test_chimera.rb index e776a01..828e3cf 100644 --- a/test/test_chimera.rb +++ b/test/test_chimera.rb @@ -1,227 +1,238 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestChimera < Test::Unit::TestCase def setup Car.each { |c| c.destroy } Car.connection(:redis).flush_all end def test_geo_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.id = Car.new_uuid c.curr_location = [37.12122, 121.43392] assert c.save c2 = Car.new c2.make = "Toyota" c2.model = "Hilux" c2.year = 2010 c2.sku = 1001 c2.curr_location = [37.12222, 121.43792] c2.id = Car.new_uuid assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c,c2].sort, found.sort c2.curr_location = [38.0, 122.0] assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c].sort, found.sort found = Car.find_with_index(:curr_location, {:coordinate => [38.0-0.05, 122.0+0.05], :steps => 5}) assert_equal [c2].sort, found.sort end def test_search_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.comments = "cat dog chicken dolphin whale panther" c.id = Car.new_uuid assert c.save c2 = Car.new c2.make = "Porsche" c2.model = "911" c2.year = 2010 c2.sku = 1001 c2.comments = "cat dog chicken" c2.id = Car.new_uuid assert c2.save c3 = Car.new c3.make = "Porsche" c3.model = "911" c3.year = 2010 c3.sku = 1002 c3.comments = "dog chicken dolphin whale" c3.id = Car.new_uuid assert c3.save assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, "dog").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :union}).sort assert_equal [c,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :intersect}).sort end def test_indexes c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert !c.new? assert_equal [c], Car.find_with_index(:comments, "fast") assert_equal [c], Car.find_with_index(:comments, "purple") assert_equal [], Car.find_with_index(:comments, "blue") assert_equal [c], Car.find_with_index(:year, 2010) assert_equal [c], Car.find_with_index(:sku, 1001) c2 = Car.new c2.make = "Honda" c2.model = "Accord" c2.year = 2010 c2.sku = 1001 c2.id = Car.new_uuid assert_raise(Chimera::Error::UniqueConstraintViolation) { c2.save } c2.sku = 1002 assert c2.save c3 = Car.new c3.make = "Honda" c3.model = "Civic" c3.year = 2010 c3.sku = 1003 c3.id = Car.new_uuid assert c3.save assert_equal 3, Car.find_with_index(:year, 2010).size assert Car.find_with_index(:year, 2010).include?(c) assert Car.find_with_index(:year, 2010).include?(c2) assert Car.find_with_index(:year, 2010).include?(c3) count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 3, count count = 0 Car.each { |car| count += 1 } assert_equal 3, count c2.destroy count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 2, count count = 0 Car.each { |car| count += 1 } assert_equal 2, count end def test_associations u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_equal 0, u.friends.size chris = User.new chris.id = User.new_uuid chris.name = "Chris" assert chris.save assert_equal 0, u.friends.size u.friends << chris assert_equal 1, u.friends.size chris.destroy assert_equal 0, u.friends.size c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert_equal 0, u.cars.size u.cars << c assert_equal 1, u.cars.size assert_equal [c], u.cars.all assert_equal 1, c.association_memberships.all_associations.size u.cars.remove(c) assert_equal 0, c.association_memberships.all_associations.size end def test_model_attribute u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_nil u.favorite_car c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save u.favorite_car = c assert u.save assert_equal c, u.favorite_car u = User.find(u.id) assert_equal c, u.favorite_car u.favorite_car = nil assert u.save assert_nil u.favorite_car u.favorite_car = c assert u.save assert_equal c, u.favorite_car c.destroy assert_equal c, u.favorite_car u = User.find(u.id) assert_nil u.favorite_car end def test_redis_objects u = User.new u.id = User.new_uuid u.name = "Ben" assert u.save assert_equal false, User.connection(:redis).exists(u.num_logins.key) assert_equal 0, u.num_logins.count u.num_logins.incr assert_equal 1, u.num_logins.count assert_equal true, User.connection(:redis).exists(u.num_logins.key) u.num_logins.incr_by 10 assert_equal 11, u.num_logins.count u.destroy assert_equal false, User.connection(:redis).exists(u.num_logins.key) end + + def test_rich_attributes + u = User.new + u.id = User.new_uuid + u.updated_at = Time.now.utc + assert u.updated_at.is_a?(Time) + u.name = "ben" + assert u.save + u = User.find(u.id) + assert u.updated_at.is_a?(Time) + end end
benmyles/chimera
a2930c67959d60727f1c906da8aa25b5d406f038
added redis objects
diff --git a/lib/chimera.rb b/lib/chimera.rb index f12978c..2e645d6 100644 --- a/lib/chimera.rb +++ b/lib/chimera.rb @@ -1,30 +1,32 @@ $:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) gem 'uuidtools','= 2.1.1' gem 'activemodel','= 3.0.0.beta' gem "brianmario-yajl-ruby", "= 0.6.3" gem "fast-stemmer", "= 1.0.0" require 'fast_stemmer' require 'digest/sha1' require 'uuidtools' require 'yajl' require 'active_model' require 'redis' require 'typhoeus' require 'riak_raw' require "chimera/error" require "chimera/attributes" require "chimera/indexes" require "chimera/geo_indexes" +require "chimera/associations" +require "chimera/redis_objects" require "chimera/finders" require "chimera/persistence" require "chimera/base" module Chimera VERSION = '0.0.1' end \ No newline at end of file diff --git a/lib/chimera/associations.rb b/lib/chimera/associations.rb new file mode 100644 index 0000000..cce33c0 --- /dev/null +++ b/lib/chimera/associations.rb @@ -0,0 +1,146 @@ +module Chimera + module Associations + def self.included(base) + base.send :extend, ClassMethods + base.send :include, InstanceMethods + end + + module ClassMethods + def defined_associations + @defined_associations || {} + end + + # association :friends, User + def association(name, class_sym) + @defined_associations ||= {} + @defined_associations[name.to_sym] = class_sym + define_method("#{name}") do + @associations ||= {} + @associations[name] ||= Chimera::AssociationProxies::Association.new(self,name,class_sym) + end + end + end # ClassMethods + + module InstanceMethods + def destroy_associations + (@associations || {}).each do |name, association| + association.destroy + end + end + + def association_memberships + @association_memberships ||= Chimera::AssociationProxies::AssociationMemberships.new(self) + end + end # InstanceMethods + end + + module AssociationProxies + class AssociationMemberships + attr_accessor :model + + def initialize(_model) + @model = _model + end + + def key + "#{model.class.to_s}::AssociationProxies::AssociationMemberships::#{model.id}" + end + + def add(assoc_key) + self.model.class.connection(:redis).lpush(self.key, assoc_key) + end + + def remove(assoc_key) + self.model.class.connection(:redis).lrem(self.key, 0, assoc_key) + end + + def destroy + remove_from_all_associations + self.model.class.connection(:redis).del(self.key) + end + + def remove_from_all_associations + self.each_association { |assoc| assoc.remove(self.model) } + end + + def each_association + llen = self.model.class.connection(:redis).llen(self.key) + 0.upto(llen-1) do |i| + assoc_key = self.model.class.connection(:redis).lindex(self.key, i) + yield Chimera::AssociationProxies::Association.find(assoc_key) + end + true + end + + def all_associations + all = []; self.each_association { |ass| all << ass }; all + end + end + + class Association + attr_accessor :model, :name, :klass + + def self.find(assoc_key) + parts = assoc_key.split("::") + model_klass = parts[0] + name = parts[3] + assoc_klass = parts[4] + model_id = parts[5] + self.new(eval(model_klass).find(model_id), name, assoc_klass.to_sym) + end + + def initialize(_model, _name, class_sym) + @model = _model + @name = _name + @klass = eval(class_sym.to_s.camelize) + raise(Chimera::Error::MissingId) unless model.id + end + + def key + "#{model.class.to_s}::AssociationProxies::Association::#{name}::#{klass.to_s}::#{model.id}" + end + + def <<(obj) + raise(Chimera::Error::AssociationClassMismatch) unless obj.class.to_s == self.klass.to_s + self.model.class.connection(:redis).lpush(self.key, obj.id) + obj.association_memberships.add(self.key) + true + end + + def remove(obj) + raise(Chimera::Error::AssociationClassMismatch) unless obj.class.to_s == self.klass.to_s + self.model.class.connection(:redis).lrem(self.key, 0, obj.id) + obj.association_memberships.remove(self.key) + true + end + + def size + self.model.class.connection(:redis).llen(self.key) + end + + def each + llen = self.model.class.connection(:redis).llen(self.key) + curr = 0 + while(curr < llen) + keys = self.model.class.connection(:redis).lrange(self.key, curr, curr+9).compact + self.klass.find_many(keys).each { |obj| yield(obj) } + curr += 10 + end + true + end + + def all + found = []; self.each { |o| found << o }; found + end + + def destroy(delete_associated=true) + if delete_associated == true + self.each { |obj| obj.destroy } + else + self.each { |obj| obj.association_memberships.remove(self.key) } + end + self.model.class.connection(:redis).del(self.key) + end + end # Association + end # AssociationProxies +end \ No newline at end of file diff --git a/lib/chimera/attributes.rb b/lib/chimera/attributes.rb index 9db5e87..992f29b 100644 --- a/lib/chimera/attributes.rb +++ b/lib/chimera/attributes.rb @@ -1,34 +1,53 @@ module Chimera module Attributes def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods def defined_attributes @defined_attributes || {} end # available types include: # string, integer, yaml, json, coordinate - def attribute(name, type = :string) + def attribute(name, type = :string, extra_opts={}) @defined_attributes ||= {} - @defined_attributes[name.to_sym] = type + @defined_attributes[name.to_sym] = [type, extra_opts] define_method("#{name}") do - if @attributes + return nil unless @attributes + if type == :model + @cached_attributes ||= {} + @cached_attributes[name.to_sym] ||= begin + model_id = @attributes[name.to_sym] + klass = extra_opts[:class] + if model_id && klass + eval(klass.to_s.camelize).find(model_id) + end + end + else @attributes[name.to_sym] end end define_method("#{name}=") do |val| - if @attributes + return nil unless @attributes + if type == :model + @cached_attributes ||= {} + @cached_attributes.delete(name.to_sym) + if val.respond_to?(:id) + @attributes[name.to_sym] = val.id + else + @attributes.delete(name.to_sym) + end + else @attributes @attributes[name.to_sym] = val end end end end # ClassMethods module InstanceMethods end # InstanceMethods end end \ No newline at end of file diff --git a/lib/chimera/base.rb b/lib/chimera/base.rb index 43371f8..f9b663a 100644 --- a/lib/chimera/base.rb +++ b/lib/chimera/base.rb @@ -1,85 +1,95 @@ module Chimera def self.config_path=(path) @config_path = path @config = YAML.load_file(@config_path) end def self.config @config || raise(Chimera::Error::MissingConfig) end class Base include Chimera::Attributes include Chimera::Indexes include Chimera::GeoIndexes + include Chimera::Associations + include Chimera::RedisObjects include Chimera::Finders include Chimera::Persistence include ActiveModel::Validations extend ActiveModel::Naming extend ActiveModel::Callbacks define_model_callbacks :create, :save, :destroy - attr_accessor :id, :attributes, :orig_attributes, :riak_response + attr_accessor :id, :attributes, :orig_attributes, :riak_response, :associations def self.use_config(key) @config = (Chimera.config[key.to_sym] || raise(Chimera::Error::MissingConfig,":#{key}")) end def self.config @config ||= (Chimera.config[:default] || raise(Chimera::Error::MissingConfig,":default")) end def self.connection(server) Thread.current["Chimera::#{self.to_s}::#{server}::connection"] ||= begin case server.to_sym when :redis Redis.new(self.config[:redis]) when :riak_raw RiakRaw::Client.new(self.config[:riak_raw][:host], self.config[:riak_raw][:port]) else nil end end end def self.bucket_key self.to_s end def self.bucket(keys=false) self.connection(:riak_raw).bucket(self.bucket_key,keys) end def self.new_uuid UUIDTools::UUID.random_create.to_s end def inspect "#<#{self.to_s}: @id=#{self.id}, @new=#{@new}>" end def ==(obj) obj.class.to_s == self.class.to_s && !obj.new? && !self.new? && obj.id == self.id end def <=>(obj) self.id.to_s <=> obj.id.to_s end def initialize(attributes={},id=nil,is_new=true) @attributes = attributes @orig_attributes = @attributes.clone @id = id @new = is_new end + def id=(val) + if self.new? + @id = val + else + raise(Chimera::Error::AttemptToModifyId) + end + end + protected def read_attribute_for_validation(key) @attributes[key.to_sym] end end # Base end # Chimera \ No newline at end of file diff --git a/lib/chimera/error.rb b/lib/chimera/error.rb index ca30cfc..70b744e 100644 --- a/lib/chimera/error.rb +++ b/lib/chimera/error.rb @@ -1,9 +1,12 @@ module Chimera class Error < RuntimeError class MissingConfig < Chimera::Error; end class UniqueConstraintViolation < Chimera::Error; end class SaveWithoutId < Chimera::Error; end + class MissingId < Chimera::Error; end class ValidationErrors < Chimera::Error; end + class AttemptToModifyId < Chimera::Error; end + class AssociationClassMismatch < Chimera::Error; end end end diff --git a/lib/chimera/persistence.rb b/lib/chimera/persistence.rb index dff047f..911f18e 100644 --- a/lib/chimera/persistence.rb +++ b/lib/chimera/persistence.rb @@ -1,67 +1,70 @@ module Chimera module Persistence def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end module ClassMethods end # ClassMethods module InstanceMethods def new? @new == true end def save raise(Chimera::Error::SaveWithoutId) unless self.id raise(Chimera::Error::ValidationErrors) unless self.valid? check_index_constraints if new? _run_create_callbacks do _run_save_callbacks do save_without_callbacks create_indexes end end else _run_save_callbacks do destroy_indexes save_without_callbacks create_indexes end end true end alias :create :save def vector_clock if @riak_response and @riak_response.headers_hash return @riak_response.headers_hash["X-Riak-Vclock"] end; nil end def save_without_callbacks @riak_response = self.class.connection(:riak_raw).store( self.class.bucket_key, self.id, Yajl::Encoder.encode(@attributes), self.vector_clock) @orig_attributes = @attributes.clone @new = false end def destroy _run_destroy_callbacks do @riak_response = self.class.connection(:riak_raw).delete(self.class.bucket_key, self.id) destroy_indexes + association_memberships.destroy + destroy_associations + destroy_redis_objects freeze end end end # InstanceMethods end end \ No newline at end of file diff --git a/lib/chimera/redis_objects.rb b/lib/chimera/redis_objects.rb new file mode 100644 index 0000000..5d3c83a --- /dev/null +++ b/lib/chimera/redis_objects.rb @@ -0,0 +1,335 @@ +module Chimera + module RedisObjects + def self.included(base) + base.send :extend, ClassMethods + base.send :include, InstanceMethods + end + + module ClassMethods + def defined_redis_objects + @defined_redis_objects || {} + end + + # available types include: + # string, set, zset, list, counter + def redis_object(name, type = :string, extra_opts={}) + @defined_redis_objects ||= {} + @defined_redis_objects[name.to_sym] = [type, extra_opts] + define_method("#{name}") do + @redis_objects ||= {} + case type + when :string then + @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::String.new(self, name, extra_opts) + when :set then + @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::Set.new(self, name, extra_opts) + when :zset then + @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::ZSet.new(self, name, extra_opts) + when :list then + @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::List.new(self, name, extra_opts) + when :counter then + @redis_objects[name.to_sym] = Chimera::RedisObjectProxy::Counter.new(self, name, extra_opts) + end + end + end + end # ClassMethods + + module InstanceMethods + def destroy_redis_objects + (@redis_objects || {}).each do |name, redis_obj| + redis_obj.destroy + end + end + end # InstanceMethods + end + + module RedisObjectProxy + class Base + attr_accessor :owner, :name, :extra_opts + def initialize(owner, name, extra_opts) + unless owner and owner.id + raise(Chimera::Errors::MissingId) + end + + @owner = owner + @name = name + @extra_opts = extra_opts + end + + def connection + self.owner.class.connection(:redis) + end + + def key + "#{self.class.to_s}::RedisObjects::#{name}::#{self.owner.id}" + end + + def destroy + connection.del(self.key) + end + end + + class Collection < Base + def sort(opts={}) + cmd = [self.key] + cmd << "BY #{opts[:by_pattern]}" if opts[:by_pattern] + if opts[:limit] + start, count = opts[:limit] + cmd << "LIMIT #{start} #{count}" if start && count + end + cmd << "GET #{opts[:get_pattern]}" if opts[:get_pattern] + cmd << opts[:order] if opts[:order] + cmd << "ALPHA" if opts[:alpha] == true + cmd << "STORE #{opts[:dest_key]}" if opts[:dest_key] + connection.sort(self.key, cmd.join(" ")) + end + end + + class String < Base + def set(val) + connection.set(self.key, val) + end + + def get + connection.get(self.key) + end + end + + class Set < Collection + def add(val) + connection.sadd(self.key, val) + end + + def <<(val) + add(val) + end + + def rem(val) + connection.srem(self.key, val) + end + + def pop + connection.spop(self.key) + end + + def move(val, dest_set_key) + connection.smove(self.key, dest_set_key, val) + end + + def card + connection.scard(self.key) + end + + alias :size :card + alias :count :card + + def ismember(val) + connection.sismember(self.key, val) + end + + alias :is_member? :ismember + alias :include? :ismember + alias :includes? :ismember + alias :contains? :ismember + + def inter(*set_keys) + connection.sinter(set_keys.join(" ")) + end + + alias :intersect :inter + + def interstore(dest_key, *set_keys) + connection.sinterstore(dest_key, set_keys.join(" ")) + end + + alias :intersect_and_store :interstore + + def union(*set_keys) + connection.sunion(set_keys.join(" ")) + end + + def unionstore(dest_key, *set_keys) + connection.sunionstore(dest_key, set_keys.join(" ")) + end + + alias :union_and_store :unionstore + + def diff(*set_keys) + connection.sdiff(set_keys.join(" ")) + end + + def diffstore(dest_key, *set_keys) + connection.sdiffstore(dest_key, set_keys.join(" ")) + end + + alias :diff_and_store :diffstore + + def members + connection.smembers(self.key) + end + + alias :all :members + + def randmember + connection.srandmember(self.key) + end + + alias :rand_member :randmember + end + + class ZSet < Collection + def add(val,score=0) + connection.zadd(self.key, score, val) + end + + def rem(val) + connection.zrem(self.key, val) + end + + def incrby(val, incr) + connection.zincrby(self.key, incr, val) + end + + alias :incr_by :incrby + + def range(start_index, end_index, extra_opts={}) + opts = [self.key, start_index, end_index] + opts << "WITHSCORES" if extra_opts[:with_scores] == true + connection.zrange(opts) + end + + def revrange(start_index, end_index, extra_opts={}) + opts = [self.key, start_index, end_index] + opts << "WITHSCORES" if extra_opts[:with_scores] == true + connection.zrevrange(opts) + end + + alias :rev_range :revrange + + def rangebyscore(min, max, extra_opts={}) + opts = [self.key, min, max] + offset, count = extra_opts[:limit] + if offset and count + opts << "LIMIT #{offset} #{count}" + end + opts << "WITHSCORES" if extra_opts[:with_scores] == true + connection.zrangebyscore(opts) + end + + alias :range_by_score :rangebyscore + + def remrangebyscore(min,max) + connection.zremrangebyscore(self.key,min,max) + end + + alias :rem_range_by_score :remrangebyscore + alias :remove_range_by_score :remrangebyscore + + def card + connection.zcard(self.key) + end + + alias :size :card + alias :count :card + + def score(val) + connection.zscore(self.key, val) + end + end + + class List < Collection + def rpush(val) + connection.rpush(self.key, val) + end + + alias :right_push :rpush + + def <<(val) + rpush(val) + end + + def lpush(val) + connection.lpush(self.key, val) + end + + alias :left_push :lpush + + def len + connection.len(self.key) + end + + alias :size :len + alias :count :len + + def range(start_index, end_index) + connection.lrange(self.key, start_index, end_index) + end + + def trim(start_index, end_index) + connection.ltrim(self.key, start_index, end_index) + end + + def index(index) + connection.lindex(self.key, index) + end + + def [](index) + self.index(index) + end + + def set(index, val) + connection.lset(self.key, index, val) + end + + def rem(val, count=0) + connection.lrem(self.key, count, val) + end + + def lpop + connection.lpop(self.key) + end + + alias :left_pop :lpop + alias :pop :lpop + + def rpop + connection.rpop(self.key) + end + + alias :right_pop :rpop + + def rpoplpush(dest_key) + connection.rpoplpush(self.key, dest_key) + end + + alias :right_pop_left_push :rpoplpush + end + + class Counter < Base + def incr + connection.incr(self.key) + end + + def incrby(val) + connection.incrby(self.key,val) + end + + alias :incr_by :incrby + + def decr + connection.decr(self.key) + end + + def decrby(val) + connection.decrby(self.key, val) + end + + def val + connection.get(self.key).to_i + end + + alias :count :val + + alias :decr_by :decrby + end + end +end \ No newline at end of file diff --git a/lib/riak_raw.rb b/lib/riak_raw.rb index 038e667..0786db3 100644 --- a/lib/riak_raw.rb +++ b/lib/riak_raw.rb @@ -1,106 +1,100 @@ # gem "typhoeus", "= 0.1.18" # gem "uuidtools", "= 2.1.1" # gem "brianmario-yajl-ruby", "= 0.6.3" # require "typhoeus" # require "uuidtools" # require "uri" # require "yajl" # A Ruby interface for the Riak (http://riak.basho.com/) key-value store. # # Example Usage: # # > client = RiakRaw::Client.new('127.0.0.1', 8098, 'raw') # > client.delete('raw_example', 'doctestkey') # > obj = client.store('raw_example', 'doctestkey', {'foo':2}) # > client.fetch('raw_example', 'doctestkey') module RiakRaw VERSION = '0.0.1' class Client attr_accessor :host, :port, :prefix, :client_id - - def self.extract_header(headers, target_header) - headers.split("\r\n").select { |header| header =~ /^#{target_header}/ }[0].split(": ")[1] - rescue => e - nil - end - + def initialize(host="127.0.0.1", port=8098, prefix='riak', client_id=SecureRandom.base64) @host = host @port = port @prefix = prefix @client_id = client_id end def bucket(bucket_name,keys=false) #request(:get, build_path(bucket_name)) response = request(:get, build_path(bucket_name), nil, nil, {"returnbody" => "true", "keys" => keys}) if response.code == 200 if json = response.body return Yajl::Parser.parse(json) end end; nil end def store(bucket_name, key, content, vclock=nil, links=[], content_type='application/json', w=2, dw=2, r=2) headers = { 'Content-Type' => content_type, 'X-Riak-ClientId' => self.client_id } if vclock headers['X-Riak-Vclock'] = vclock end response = request(:put, build_path(bucket_name,key), content, headers, {"returnbody" => "false", "w" => w, "dw" => dw}) # returnbody=true could cause issues. instead we'll do a # separate fetch. see: https://issues.basho.com/show_bug.cgi?id=52 if response.code == 204 response = fetch(bucket_name, key, r) end response end def fetch(bucket_name, key, r=2) response = request(:get, build_path(bucket_name, key), nil, {}, {"r" => r}) end # there could be concurrency issues if we don't force a short sleep # after delete. see: https://issues.basho.com/show_bug.cgi?id=52 def delete(bucket_name, key, dw=2) response = request(:delete, build_path(bucket_name, key), nil, {}, {"dw" => dw}) end private def build_path(bucket_name, key='') "http://#{self.host}:#{self.port}/#{self.prefix}/#{URI.escape(bucket_name)}/#{URI.escape(key)}" end def request(method, uri, body="", headers={}, params={}) hydra = Typhoeus::Hydra.new case method when :get then req = Typhoeus::Request.new(uri, :method => :get, :body => body, :headers => headers, :params => params) when :post then req = Typhoeus::Request.new(uri, :method => :post, :body => body, :headers => headers, :params => params) when :put then req = Typhoeus::Request.new(uri, :method => :put, :body => body, :headers => headers, :params => params) when :delete then req = Typhoeus::Request.new(uri, :method => :delete, :body => body, :headers => headers, :params => params) end hydra.queue(req); hydra.run req.handled_response end end # Client end \ No newline at end of file diff --git a/test/models.rb b/test/models.rb index f1e04d0..57e12b3 100644 --- a/test/models.rb +++ b/test/models.rb @@ -1,42 +1,48 @@ class User < Chimera::Base use_config :default # this is implied even if not here attribute :name, :string attribute :age, :integer attribute :occupation, :string attribute :interests, :json attribute :home_coordinate, :coordinate # [37.2,122.1] attribute :ssn, :string + attribute :favorite_car, :model, :class => :car # User.find_with_index(:home_coordinate, {:coordinate => [37.2,122.1], :steps => 5}) index :home_coordinate, :type => :geo, :step_size => 0.05 # User.find_with_index(:occupation, { :q => "developer", :type => :intersect } ) # fuzzy search. :intersect or :union index :occupation, :type => :search # User.find_with_index(:ssn, "12345") # exact search, enforces unique constraint index :ssn, :type => :unique # User.find_with_index(:name, "Ben") # like :search but exact index :name, :type => :find + association :friends, :user + association :cars, :car + + redis_object :num_logins, :counter + validates_presence_of :name end class Car < Chimera::Base attribute :color attribute :make attribute :model attribute :year, :integer attribute :mileage, :integer attribute :comments attribute :sku attribute :curr_location, :coordinate index :year, :type => :find index :comments, :type => :search index :sku, :type => :unique index :curr_location, :type => :geo, :step_size => 0.05 validates_presence_of :make, :model, :year end \ No newline at end of file diff --git a/test/test_chimera.rb b/test/test_chimera.rb index 472d2db..e776a01 100644 --- a/test/test_chimera.rb +++ b/test/test_chimera.rb @@ -1,137 +1,227 @@ require File.dirname(__FILE__) + '/test_helper.rb' class TestChimera < Test::Unit::TestCase def setup Car.each { |c| c.destroy } Car.connection(:redis).flush_all end def test_geo_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.id = Car.new_uuid c.curr_location = [37.12122, 121.43392] assert c.save c2 = Car.new c2.make = "Toyota" c2.model = "Hilux" c2.year = 2010 c2.sku = 1001 c2.curr_location = [37.12222, 121.43792] c2.id = Car.new_uuid assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c,c2].sort, found.sort c2.curr_location = [38.0, 122.0] assert c2.save found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) assert_equal [c].sort, found.sort found = Car.find_with_index(:curr_location, {:coordinate => [38.0-0.05, 122.0+0.05], :steps => 5}) assert_equal [c2].sort, found.sort end def test_search_indexes c = Car.new c.make = "Porsche" c.model = "911" c.year = 2010 c.sku = 1000 c.comments = "cat dog chicken dolphin whale panther" c.id = Car.new_uuid assert c.save c2 = Car.new c2.make = "Porsche" c2.model = "911" c2.year = 2010 c2.sku = 1001 c2.comments = "cat dog chicken" c2.id = Car.new_uuid assert c2.save c3 = Car.new c3.make = "Porsche" c3.model = "911" c3.year = 2010 c3.sku = 1002 c3.comments = "dog chicken dolphin whale" c3.id = Car.new_uuid assert c3.save assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, "dog").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :union}).sort assert_equal [c,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :intersect}).sort end def test_indexes c = Car.new c.make = "Nissan" c.model = "RX7" c.year = 2010 c.sku = 1001 c.comments = "really fast car. it's purple too!" c.id = Car.new_uuid assert c.save assert !c.new? assert_equal [c], Car.find_with_index(:comments, "fast") assert_equal [c], Car.find_with_index(:comments, "purple") assert_equal [], Car.find_with_index(:comments, "blue") assert_equal [c], Car.find_with_index(:year, 2010) assert_equal [c], Car.find_with_index(:sku, 1001) c2 = Car.new c2.make = "Honda" c2.model = "Accord" c2.year = 2010 c2.sku = 1001 c2.id = Car.new_uuid assert_raise(Chimera::Error::UniqueConstraintViolation) { c2.save } c2.sku = 1002 assert c2.save c3 = Car.new c3.make = "Honda" c3.model = "Civic" c3.year = 2010 c3.sku = 1003 c3.id = Car.new_uuid assert c3.save assert_equal 3, Car.find_with_index(:year, 2010).size assert Car.find_with_index(:year, 2010).include?(c) assert Car.find_with_index(:year, 2010).include?(c2) assert Car.find_with_index(:year, 2010).include?(c3) count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 3, count count = 0 Car.each { |car| count += 1 } assert_equal 3, count c2.destroy count = 0 Car.find_with_index(:all) { |car| count += 1 } assert_equal 2, count count = 0 Car.each { |car| count += 1 } assert_equal 2, count end + + def test_associations + u = User.new + u.id = User.new_uuid + u.name = "Ben" + assert u.save + + assert_equal 0, u.friends.size + + chris = User.new + chris.id = User.new_uuid + chris.name = "Chris" + assert chris.save + + assert_equal 0, u.friends.size + u.friends << chris + assert_equal 1, u.friends.size + chris.destroy + assert_equal 0, u.friends.size + + c = Car.new + c.make = "Nissan" + c.model = "RX7" + c.year = 2010 + c.sku = 1001 + c.comments = "really fast car. it's purple too!" + c.id = Car.new_uuid + assert c.save + + assert_equal 0, u.cars.size + u.cars << c + assert_equal 1, u.cars.size + assert_equal [c], u.cars.all + assert_equal 1, c.association_memberships.all_associations.size + u.cars.remove(c) + assert_equal 0, c.association_memberships.all_associations.size + end + + def test_model_attribute + u = User.new + u.id = User.new_uuid + u.name = "Ben" + assert u.save + assert_nil u.favorite_car + + c = Car.new + c.make = "Nissan" + c.model = "RX7" + c.year = 2010 + c.sku = 1001 + c.comments = "really fast car. it's purple too!" + c.id = Car.new_uuid + assert c.save + + u.favorite_car = c + assert u.save + assert_equal c, u.favorite_car + u = User.find(u.id) + assert_equal c, u.favorite_car + u.favorite_car = nil + assert u.save + assert_nil u.favorite_car + + u.favorite_car = c + assert u.save + assert_equal c, u.favorite_car + c.destroy + assert_equal c, u.favorite_car + u = User.find(u.id) + assert_nil u.favorite_car + end + + def test_redis_objects + u = User.new + u.id = User.new_uuid + u.name = "Ben" + assert u.save + + assert_equal false, User.connection(:redis).exists(u.num_logins.key) + assert_equal 0, u.num_logins.count + u.num_logins.incr + assert_equal 1, u.num_logins.count + assert_equal true, User.connection(:redis).exists(u.num_logins.key) + u.num_logins.incr_by 10 + assert_equal 11, u.num_logins.count + + u.destroy + + assert_equal false, User.connection(:redis).exists(u.num_logins.key) + end end
benmyles/chimera
519a0a5d1acd7a204d09493c06f7c6fd8c2b5f90
just missing associations now
diff --git a/History.txt b/History.txt new file mode 100644 index 0000000..5846f89 --- /dev/null +++ b/History.txt @@ -0,0 +1,4 @@ +=== 0.0.1 2010-03-01 + +* 1 major enhancement: + * Initial release diff --git a/Manifest.txt b/Manifest.txt new file mode 100644 index 0000000..81e06cf --- /dev/null +++ b/Manifest.txt @@ -0,0 +1,11 @@ +History.txt +Manifest.txt +PostInstall.txt +README.rdoc +Rakefile +lib/chimera.rb +script/console +script/destroy +script/generate +test/test_helper.rb +test/test_chimera.rb diff --git a/PostInstall.txt b/PostInstall.txt new file mode 100644 index 0000000..b94a9f3 --- /dev/null +++ b/PostInstall.txt @@ -0,0 +1,7 @@ + +For more information on chimera, see http://chimera.rubyforge.org + +NOTE: Change this information in PostInstall.txt +You can also delete it if you don't want it. + + diff --git a/README.rdoc b/README.rdoc new file mode 100644 index 0000000..e262727 --- /dev/null +++ b/README.rdoc @@ -0,0 +1,50 @@ += chimera + +* http://github.com/#{github_username}/#{project_name} + +== DESCRIPTION: + +FIX (describe your package) + +== FEATURES/PROBLEMS: + +* FIX (list of features or problems) + +== SYNOPSIS: + + FIX (code sample of usage) + +== REQUIREMENTS: + +* Riak +* Redis +* Xapian + +== INSTALL: + +* FIX (sudo gem install, anything else) + +== LICENSE: + +(The MIT License) + +Copyright (c) 2010 FIXME full name + +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. \ No newline at end of file diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..7ee7ba6 --- /dev/null +++ b/Rakefile @@ -0,0 +1,29 @@ +require 'rubygems' +gem 'hoe', '>= 2.1.0' +require 'hoe' +require 'fileutils' +require './lib/chimera' + +Hoe.plugin :newgem +# Hoe.plugin :website +# Hoe.plugin :cucumberfeatures + +# Generate all the Rake tasks +# Run 'rake -T' to see list of generated tasks (from gem root directory) +$hoe = Hoe.spec 'chimera' do + self.developer 'FIXME full name', 'FIXME email' + self.post_install_message = 'PostInstall.txt' # TODO remove if post-install message not required + self.rubyforge_name = self.name # TODO this is default value + # self.extra_deps = [['activesupport','>= 2.0.2']] + self.extra_deps = [["activesupport","= 3.0.0.beta"], + ["uuidtools","= 2.1.1"], + ["activemodel",'= 3.0.0.beta'], + ["brianmario-yajl-ruby","= 0.6.3"]] +end + +require 'newgem/tasks' +Dir['tasks/**/*.rake'].each { |t| load t } + +# TODO - want other tests/tasks run by default? Add them to the list +# remove_task :default +# task :default => [:spec, :features] diff --git a/doc/NOTES b/doc/NOTES new file mode 100644 index 0000000..076290e --- /dev/null +++ b/doc/NOTES @@ -0,0 +1,11 @@ +require 'lib/chimera' +Chimera.config_path = "doc/examples/config.yml" +require 'test/models' +c = Car.new +c.make = "Nissan" +c.model = "RX7" +c.year = 2010 +c.sku = 1001 +c.comments = "really fast car. it's purple too!" +c.id = Car.new_uuid +c.save \ No newline at end of file diff --git a/doc/examples/config.yml b/doc/examples/config.yml new file mode 100644 index 0000000..ea1bfb7 --- /dev/null +++ b/doc/examples/config.yml @@ -0,0 +1,16 @@ +:default: + :redis: + :host: 127.0.0.1 + :port: 6379 + :db: 0 + :riak_raw: + :host: 127.0.0.1 + :port: 8098 +:user: + :redis: + :host: 127.0.0.1 + :port: 5379 + :db: 0 + :riak_raw: + :host: 127.0.0.1 + :port: 7098 diff --git a/doc/redis6379.conf b/doc/redis6379.conf new file mode 100644 index 0000000..b506895 --- /dev/null +++ b/doc/redis6379.conf @@ -0,0 +1,132 @@ +# Redis configuration file example + +# By default Redis does not run as a daemon. Use 'yes' if you need it. +# Note that Redis will write a pid file in /var/run/redis.pid when daemonized. +daemonize no + +# When run as a daemon, Redis write a pid file in /var/run/redis.pid by default. +# You can specify a custom pid file location here. +pidfile /tmp/redis6379.pid + +# Accept connections on the specified port, default is 6379 +port 6379 + +# If you want you can bind a single interface, if the bind option is not +# specified all the interfaces will listen for connections. +# +# bind 127.0.0.1 + +# Close the connection after a client is idle for N seconds (0 to disable) +timeout 300 + +# Save the DB on disk: +# +# save <seconds> <changes> +# +# Will save the DB if both the given number of seconds and the given +# number of write operations against the DB occurred. +# +# In the example below the behaviour will be to save: +# after 900 sec (15 min) if at least 1 key changed +# after 300 sec (5 min) if at least 10 keys changed +# after 60 sec if at least 10000 keys changed +save 900 1 +save 300 10 +save 60 10000 + +# The filename where to dump the DB +dbfilename /tmp/redis6379.rdb + +# For default save/load DB in/from the working directory +# Note that you must specify a directory not a file name. +dir ./ + +# Set server verbosity to 'debug' +# it can be one of: +# debug (a lot of information, useful for development/testing) +# notice (moderately verbose, what you want in production probably) +# warning (only very important / critical messages are logged) +loglevel debug + +# Specify the log file name. Also 'stdout' can be used to force +# the demon to log on the standard output. Note that if you use standard +# output for logging but daemonize, logs will be sent to /dev/null +logfile stdout + +# Set the number of databases. The default database is DB 0, you can select +# a different one on a per-connection basis using SELECT <dbid> where +# dbid is a number between 0 and 'databases'-1 +databases 256 + +################################# REPLICATION ################################# + +# Master-Slave replication. Use slaveof to make a Redis instance a copy of +# another Redis server. Note that the configuration is local to the slave +# so for example it is possible to configure the slave to save the DB with a +# different interval, or to listen to another port, and so on. + +# slaveof <masterip> <masterport> + +################################## SECURITY ################################### + +# Require clients to issue AUTH <PASSWORD> before processing any other +# commands. This might be useful in environments in which you do not trust +# others with access to the host running redis-server. +# +# This should stay commented out for backward compatibility and because most +# people do not need auth (e.g. they run their own servers). + +# requirepass foobared + +################################### LIMITS #################################### + +# Set the max number of connected clients at the same time. By default there +# is no limit, and it's up to the number of file descriptors the Redis process +# is able to open. The special value '0' means no limts. +# Once the limit is reached Redis will close all the new connections sending +# an error 'max number of clients reached'. + +# maxclients 128 + +# Don't use more memory than the specified amount of bytes. +# When the memory limit is reached Redis will try to remove keys with an +# EXPIRE set. It will try to start freeing keys that are going to expire +# in little time and preserve keys with a longer time to live. +# Redis will also try to remove objects from free lists if possible. +# +# If all this fails, Redis will start to reply with errors to commands +# that will use more memory, like SET, LPUSH, and so on, and will continue +# to reply to most read-only commands like GET. +# +# WARNING: maxmemory can be a good idea mainly if you want to use Redis as a +# 'state' server or cache, not as a real DB. When Redis is used as a real +# database the memory usage will grow over the weeks, it will be obvious if +# it is going to use too much memory in the long run, and you'll have the time +# to upgrade. With maxmemory after the limit is reached you'll start to get +# errors for write operations, and this may even lead to DB inconsistency. + +# maxmemory <bytes> + +############################### ADVANCED CONFIG ############################### + +# Glue small output buffers together in order to send small replies in a +# single TCP packet. Uses a bit more CPU but most of the times it is a win +# in terms of number of queries per second. Use 'yes' if unsure. +glueoutputbuf yes + +# Use object sharing. Can save a lot of memory if you have many common +# string in your dataset, but performs lookups against the shared objects +# pool so it uses more CPU and can be a bit slower. Usually it's a good +# idea. +# +# When object sharing is enabled (shareobjects yes) you can use +# shareobjectspoolsize to control the size of the pool used in order to try +# object sharing. A bigger pool size will lead to better sharing capabilities. +# In general you want this value to be at least the double of the number of +# very common strings you have in your dataset. +# +# WARNING: object sharing is experimental, don't enable this feature +# in production before of Redis 1.0-stable. Still please try this feature in +# your development environment so that we can test it better. +shareobjects no +shareobjectspoolsize 1024 \ No newline at end of file diff --git a/lib/chimera.rb b/lib/chimera.rb new file mode 100644 index 0000000..f12978c --- /dev/null +++ b/lib/chimera.rb @@ -0,0 +1,30 @@ +$:.unshift(File.dirname(__FILE__)) unless + $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) + +gem 'uuidtools','= 2.1.1' +gem 'activemodel','= 3.0.0.beta' +gem "brianmario-yajl-ruby", "= 0.6.3" +gem "fast-stemmer", "= 1.0.0" + +require 'fast_stemmer' + +require 'digest/sha1' +require 'uuidtools' +require 'yajl' +require 'active_model' + +require 'redis' +require 'typhoeus' +require 'riak_raw' + +require "chimera/error" +require "chimera/attributes" +require "chimera/indexes" +require "chimera/geo_indexes" +require "chimera/finders" +require "chimera/persistence" +require "chimera/base" + +module Chimera + VERSION = '0.0.1' +end \ No newline at end of file diff --git a/lib/chimera/attributes.rb b/lib/chimera/attributes.rb new file mode 100644 index 0000000..9db5e87 --- /dev/null +++ b/lib/chimera/attributes.rb @@ -0,0 +1,34 @@ +module Chimera + module Attributes + def self.included(base) + base.send :extend, ClassMethods + base.send :include, InstanceMethods + end + + module ClassMethods + def defined_attributes + @defined_attributes || {} + end + + # available types include: + # string, integer, yaml, json, coordinate + def attribute(name, type = :string) + @defined_attributes ||= {} + @defined_attributes[name.to_sym] = type + define_method("#{name}") do + if @attributes + @attributes[name.to_sym] + end + end + define_method("#{name}=") do |val| + if @attributes + @attributes[name.to_sym] = val + end + end + end + end # ClassMethods + + module InstanceMethods + end # InstanceMethods + end +end \ No newline at end of file diff --git a/lib/chimera/base.rb b/lib/chimera/base.rb new file mode 100644 index 0000000..43371f8 --- /dev/null +++ b/lib/chimera/base.rb @@ -0,0 +1,85 @@ +module Chimera + def self.config_path=(path) + @config_path = path + @config = YAML.load_file(@config_path) + end + + def self.config + @config || raise(Chimera::Error::MissingConfig) + end + + class Base + include Chimera::Attributes + include Chimera::Indexes + include Chimera::GeoIndexes + include Chimera::Finders + include Chimera::Persistence + include ActiveModel::Validations + + extend ActiveModel::Naming + extend ActiveModel::Callbacks + define_model_callbacks :create, :save, :destroy + + attr_accessor :id, :attributes, :orig_attributes, :riak_response + + def self.use_config(key) + @config = (Chimera.config[key.to_sym] || raise(Chimera::Error::MissingConfig,":#{key}")) + end + + def self.config + @config ||= (Chimera.config[:default] || raise(Chimera::Error::MissingConfig,":default")) + end + + def self.connection(server) + Thread.current["Chimera::#{self.to_s}::#{server}::connection"] ||= begin + case server.to_sym + when :redis + Redis.new(self.config[:redis]) + when :riak_raw + RiakRaw::Client.new(self.config[:riak_raw][:host], self.config[:riak_raw][:port]) + else + nil + end + end + end + + def self.bucket_key + self.to_s + end + + def self.bucket(keys=false) + self.connection(:riak_raw).bucket(self.bucket_key,keys) + end + + def self.new_uuid + UUIDTools::UUID.random_create.to_s + end + + def inspect + "#<#{self.to_s}: @id=#{self.id}, @new=#{@new}>" + end + + def ==(obj) + obj.class.to_s == self.class.to_s && + !obj.new? && !self.new? && + obj.id == self.id + end + + def <=>(obj) + self.id.to_s <=> obj.id.to_s + end + + def initialize(attributes={},id=nil,is_new=true) + @attributes = attributes + @orig_attributes = @attributes.clone + @id = id + @new = is_new + end + + protected + + def read_attribute_for_validation(key) + @attributes[key.to_sym] + end + end # Base +end # Chimera \ No newline at end of file diff --git a/lib/chimera/config.rb b/lib/chimera/config.rb new file mode 100644 index 0000000..5d8747a --- /dev/null +++ b/lib/chimera/config.rb @@ -0,0 +1,9 @@ +module Chimera + module Config + module ClassMethods + end + + module InstanceMethods + end + end +end \ No newline at end of file diff --git a/lib/chimera/error.rb b/lib/chimera/error.rb new file mode 100644 index 0000000..ca30cfc --- /dev/null +++ b/lib/chimera/error.rb @@ -0,0 +1,9 @@ +module Chimera + class Error < RuntimeError + class MissingConfig < Chimera::Error; end + class UniqueConstraintViolation < Chimera::Error; end + class SaveWithoutId < Chimera::Error; end + class ValidationErrors < Chimera::Error; end + end +end + diff --git a/lib/chimera/finders.rb b/lib/chimera/finders.rb new file mode 100644 index 0000000..756b9e4 --- /dev/null +++ b/lib/chimera/finders.rb @@ -0,0 +1,49 @@ +module Chimera + module Finders + def self.included(base) + base.send :extend, ClassMethods + base.send :include, InstanceMethods + end + + module ClassMethods + def each + self.find_with_index(:all) { |obj| yield(obj) } + end + + def find(key) + find_many(key)[0] + end + + def find_many(keys) + keys = Array(keys) + found = [] + threads = [] + keys.each do |key| + threads << Thread.new do + if key + resp = self.connection(:riak_raw).fetch(self.to_s, key) + if resp.code == 200 + if resp.body and json_hash = Yajl::Parser.parse(resp.body) + hash = {} + json_hash.each { |k,v| hash[k.to_sym] = v } + obj = self.new(hash,key,false) + obj.riak_response = resp + found << obj + else + obj = self.new({},key,false) + obj.riak_response = resp + found << obj + end + end + end + end # Thread.new + end # keys.each + threads.each { |th| th.join } + found + end # find_many + end # ClassMethods + + module InstanceMethods + end # InstanceMethods + end +end \ No newline at end of file diff --git a/lib/chimera/geo_indexes.rb b/lib/chimera/geo_indexes.rb new file mode 100644 index 0000000..4bb6954 --- /dev/null +++ b/lib/chimera/geo_indexes.rb @@ -0,0 +1,76 @@ +module Chimera + module GeoIndexes + def self.included(base) + base.send :extend, ClassMethods + base.send :include, InstanceMethods + end + + module ClassMethods + def key_for_geo_index(type, name, lat, lon, step_size=0.05) + step_size ||= 0.05 + case type.to_sym + when :geo then + lat = geo_square_coord(lat) + lon = geo_square_coord(lon) + "#{self.to_s}::Indexes::#{type}::#{name}::#{step_size}::#{lat}::#{lon}" + end + end + + def find_with_geo_index(name, opts_or_query) + if props = self.defined_indexes[name.to_sym] + case props[:type] + when :geo then + step_size = props[:step_size] + num_steps = opts_or_query[:steps] || 5 + steps = [50,num_steps].min * step_size + lat, lon = opts_or_query[:coordinate] + union_keys = [] + curr_lat = lat - steps + while curr_lat < lat+steps + curr_lon = lon - steps + while curr_lon < lon+steps + union_keys << key_for_geo_index(:geo,name,curr_lat,curr_lon,step_size) + curr_lon += step_size + end + curr_lat += step_size + end + keys = self.connection(:redis).sunion(union_keys.join(" ")) + find_many(keys) + end # case + end # if props = + end + + def geo_square_coord(lat_or_lon, step=0.05) + i = (lat_or_lon*1000000).floor + i += (step/2)*1000000 + (i - (i % (step * 1000000)))/1000000 + end + end + + module InstanceMethods + def destroy_geo_indexes + self.class.defined_indexes.each do |name, props| + case props[:type] + when :geo then + if val = @orig_attributes[name.to_sym] and val.is_a?(Array) + index_key = self.class.key_for_geo_index(:geo, name, val[0], val[1], props[:step_size]) + self.class.connection(:redis).srem(index_key, self.id) + end + end # case props[:type] + end # self.class.defined_indexes + end # destroy_geo_indexes + + def create_geo_indexes + self.class.defined_indexes.each do |name, props| + case props[:type] + when :geo then + if val = @attributes[name.to_sym] and val.is_a?(Array) + index_key = self.class.key_for_geo_index(:geo, name, val[0], val[1], props[:step_size]) + self.class.connection(:redis).sadd(index_key, self.id) + end + end # case props[:type] + end # self.class.defined_indexes + end # create_geo_indexes + end + end +end \ No newline at end of file diff --git a/lib/chimera/indexes.rb b/lib/chimera/indexes.rb new file mode 100644 index 0000000..c739911 --- /dev/null +++ b/lib/chimera/indexes.rb @@ -0,0 +1,177 @@ +module Chimera + module Indexes + SEARCH_EXCLUDE_LIST = %w(a an and as at but by for in into of on onto to the) + + def self.included(base) + base.send :extend, ClassMethods + base.send :include, InstanceMethods + end + + module ClassMethods + def defined_indexes + @defined_indexes || {} + end + + # available types include: + # find, unique, search, geo + def index(name, type = :find) + @defined_indexes ||= {} + @defined_indexes[name.to_sym] = type + end + + def find_with_index(name, opts_or_query=nil) + if opts_or_query.is_a?(Hash) + q = opts_or_query[:q].to_s + else + q = opts_or_query.to_s + end + if name.to_sym == :all + llen = self.connection(:redis).llen(self.key_for_all_index) + curr = 0 + while(curr < llen) + keys = self.connection(:redis).lrange(self.key_for_all_index, curr, curr+9).compact + find_many(keys).each { |obj| yield(obj) } + curr += 10 + end + elsif props = self.defined_indexes[name.to_sym] + case props[:type] + when :find then + if q and !q.blank? + index_key = self.key_for_index(:find, name, q) + self.find_many(self.connection(:redis).smembers(index_key)) + end + when :unique then + if q and !q.blank? + index_key = self.key_for_index(:unique, name, q) + Array(self.find(self.connection(:redis).get(index_key))) + end + when :search then + keys = [] + q.split(" ").each do |word| + word = word.downcase.stem + next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) + keys << self.key_for_index(:search, name, word) + end + if keys.size > 0 + if opts_or_query.is_a?(Hash) and opts_or_query[:type] == :union + self.find_many(self.connection(:redis).sunion(keys.join(" "))) + else + self.find_many(self.connection(:redis).sinter(keys.join(" "))) + end + end + when :geo then + find_with_geo_index(name, opts_or_query) + end # case + end # if props + end + + def key_for_index(type, name, val) + case type.to_sym + when :find, :unique, :search then + "#{self.to_s}::Indexes::#{type}::#{name}::#{digest(val)}" + end + end + + def key_for_all_index + "#{self.to_s}::Indexes::All" + end + + def digest(val) + Digest::SHA1.hexdigest(val) + end + end # ClassMethods + + module InstanceMethods + def destroy_indexes + remove_from_all_index + self.class.defined_indexes.each do |name, props| + case props[:type] + when :find then + if val = @orig_attributes[name.to_sym] and !val.blank? + index_key = self.class.key_for_index(:find, name,val.to_s) + self.class.connection(:redis).srem(index_key, self.id) + end + when :unique then + if val = @orig_attributes[name.to_sym] and !val.blank? + index_key = self.class.key_for_index(:unique, name,val.to_s) + self.class.connection(:redis).del(index_key) + end + when :search then + if val = @orig_attributes[name.to_sym] and !val.blank? + val.to_s.split(" ").each do |word| + word = word.downcase.stem + next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) + index_key = self.class.key_for_index(:search, name, word) + self.class.connection(:redis).srem(index_key, self.id) + end + end + end + end + destroy_geo_indexes + end + + def check_index_constraints + self.class.defined_indexes.each do |name, props| + case props[:type] + when :unique then + if val = @attributes[name.to_sym] and !val.blank? + index_key = self.class.key_for_index(:unique, name,val.to_s) + if k = self.class.connection(:redis).get(index_key) + if k.to_s != self.id.to_s + raise(Chimera::Error::UniqueConstraintViolation, val) + end + end + end # if val + end # case + end + end + + def create_indexes + add_to_all_index + self.class.defined_indexes.each do |name, props| + case props[:type] + when :find then + if val = @attributes[name.to_sym] and !val.blank? + index_key = self.class.key_for_index(:find, name, val.to_s) + self.class.connection(:redis).sadd(index_key, self.id) + end + when :unique then + if val = @attributes[name.to_sym] and !val.blank? + index_key = self.class.key_for_index(:unique, name,val.to_s) + if self.class.connection(:redis).exists(index_key) + raise(Chimera::Error::UniqueConstraintViolation, val) + else + self.class.connection(:redis).set(index_key, self.id) + end + end + when :search then + if val = @attributes[name.to_sym] and !val.blank? + val.to_s.split(" ").each do |word| + word = word.downcase.stem + next if Chimera::Indexes::SEARCH_EXCLUDE_LIST.include?(word) + index_key = self.class.key_for_index(:search, name, word) + self.class.connection(:redis).sadd(index_key, self.id) + end + end + end + end + create_geo_indexes + end + + def update_indexes + destroy_indexes + destroy_geo_indexes + create_indexes + create_geo_indexes + end + + def remove_from_all_index + self.class.connection(:redis).lrem(self.class.key_for_all_index, 0, self.id) + end + + def add_to_all_index + self.class.connection(:redis).lpush(self.class.key_for_all_index, self.id) + end + end # InstanceMethods + end +end \ No newline at end of file diff --git a/lib/chimera/persistence.rb b/lib/chimera/persistence.rb new file mode 100644 index 0000000..dff047f --- /dev/null +++ b/lib/chimera/persistence.rb @@ -0,0 +1,67 @@ +module Chimera + module Persistence + def self.included(base) + base.send :extend, ClassMethods + base.send :include, InstanceMethods + end + + module ClassMethods + end # ClassMethods + + module InstanceMethods + def new? + @new == true + end + + def save + raise(Chimera::Error::SaveWithoutId) unless self.id + raise(Chimera::Error::ValidationErrors) unless self.valid? + check_index_constraints + + if new? + _run_create_callbacks do + _run_save_callbacks do + save_without_callbacks + create_indexes + end + end + else + _run_save_callbacks do + destroy_indexes + save_without_callbacks + create_indexes + end + end + + true + end + + alias :create :save + + def vector_clock + if @riak_response and @riak_response.headers_hash + return @riak_response.headers_hash["X-Riak-Vclock"] + end; nil + end + + def save_without_callbacks + @riak_response = self.class.connection(:riak_raw).store( + self.class.bucket_key, + self.id, + Yajl::Encoder.encode(@attributes), + self.vector_clock) + + @orig_attributes = @attributes.clone + @new = false + end + + def destroy + _run_destroy_callbacks do + @riak_response = self.class.connection(:riak_raw).delete(self.class.bucket_key, self.id) + destroy_indexes + freeze + end + end + end # InstanceMethods + end +end \ No newline at end of file diff --git a/lib/redis.rb b/lib/redis.rb new file mode 100755 index 0000000..9941e00 --- /dev/null +++ b/lib/redis.rb @@ -0,0 +1,373 @@ +require 'socket' +require File.join(File.dirname(__FILE__),'redis/pipeline') + +begin + if RUBY_VERSION >= '1.9' + require 'timeout' + RedisTimer = Timeout + else + require 'system_timer' + RedisTimer = SystemTimer + end +rescue LoadError + RedisTimer = nil +end + +class Redis + OK = "OK".freeze + MINUS = "-".freeze + PLUS = "+".freeze + COLON = ":".freeze + DOLLAR = "$".freeze + ASTERISK = "*".freeze + + BULK_COMMANDS = { + "set" => true, + "setnx" => true, + "rpush" => true, + "lpush" => true, + "lset" => true, + "lrem" => true, + "sadd" => true, + "srem" => true, + "sismember" => true, + "echo" => true, + "getset" => true, + "smove" => true, + "zadd" => true, + "zincrby" => true, + "zrem" => true, + "zscore" => true + } + + MULTI_BULK_COMMANDS = { + "mset" => true, + "msetnx" => true + } + + BOOLEAN_PROCESSOR = lambda{|r| r == 1 } + + REPLY_PROCESSOR = { + "exists" => BOOLEAN_PROCESSOR, + "sismember" => BOOLEAN_PROCESSOR, + "sadd" => BOOLEAN_PROCESSOR, + "srem" => BOOLEAN_PROCESSOR, + "smove" => BOOLEAN_PROCESSOR, + "zadd" => BOOLEAN_PROCESSOR, + "zrem" => BOOLEAN_PROCESSOR, + "move" => BOOLEAN_PROCESSOR, + "setnx" => BOOLEAN_PROCESSOR, + "del" => BOOLEAN_PROCESSOR, + "renamenx" => BOOLEAN_PROCESSOR, + "expire" => BOOLEAN_PROCESSOR, + "keys" => lambda{|r| r.split(" ")}, + "info" => lambda{|r| + info = {} + r.each_line {|kv| + k,v = kv.split(":",2).map{|x| x.chomp} + info[k.to_sym] = v + } + info + } + } + + ALIASES = { + "flush_db" => "flushdb", + "flush_all" => "flushall", + "last_save" => "lastsave", + "key?" => "exists", + "delete" => "del", + "randkey" => "randomkey", + "list_length" => "llen", + "push_tail" => "rpush", + "push_head" => "lpush", + "pop_tail" => "rpop", + "pop_head" => "lpop", + "list_set" => "lset", + "list_range" => "lrange", + "list_trim" => "ltrim", + "list_index" => "lindex", + "list_rm" => "lrem", + "set_add" => "sadd", + "set_delete" => "srem", + "set_count" => "scard", + "set_member?" => "sismember", + "set_members" => "smembers", + "set_intersect" => "sinter", + "set_intersect_store" => "sinterstore", + "set_inter_store" => "sinterstore", + "set_union" => "sunion", + "set_union_store" => "sunionstore", + "set_diff" => "sdiff", + "set_diff_store" => "sdiffstore", + "set_move" => "smove", + "set_unless_exists" => "setnx", + "rename_unless_exists" => "renamenx", + "type?" => "type", + "zset_add" => "zadd", + "zset_count" => "zcard", + "zset_range_by_score" => "zrangebyscore", + "zset_reverse_range" => "zrevrange", + "zset_range" => "zrange", + "zset_delete" => "zrem", + "zset_score" => "zscore", + "zset_incr_by" => "zincrby", + "zset_increment_by" => "zincrby" + } + + DISABLED_COMMANDS = { + "monitor" => true, + "sync" => true + } + + def initialize(options = {}) + @host = options[:host] || '127.0.0.1' + @port = (options[:port] || 6379).to_i + @db = (options[:db] || 0).to_i + @timeout = (options[:timeout] || 5).to_i + @password = options[:password] + @logger = options[:logger] + @thread_safe = options[:thread_safe] + @mutex = Mutex.new if @thread_safe + @sock = nil + + @logger.info { self.to_s } if @logger + end + + def to_s + "Redis Client connected to #{server} against DB #{@db}" + end + + def server + "#{@host}:#{@port}" + end + + def connect_to_server + @sock = connect_to(@host, @port, @timeout == 0 ? nil : @timeout) + call_command(["auth",@password]) if @password + call_command(["select",@db]) unless @db == 0 + end + + def connect_to(host, port, timeout=nil) + # We support connect() timeout only if system_timer is availabe + # or if we are running against Ruby >= 1.9 + # Timeout reading from the socket instead will be supported anyway. + if @timeout != 0 and RedisTimer + begin + sock = TCPSocket.new(host, port) + rescue Timeout::Error + @sock = nil + raise Timeout::Error, "Timeout connecting to the server" + end + else + sock = TCPSocket.new(host, port) + end + sock.setsockopt Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1 + + # If the timeout is set we set the low level socket options in order + # to make sure a blocking read will return after the specified number + # of seconds. This hack is from memcached ruby client. + if timeout + secs = Integer(timeout) + usecs = Integer((timeout - secs) * 1_000_000) + optval = [secs, usecs].pack("l_2") + begin + sock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval + sock.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval + rescue Exception => ex + # Solaris, for one, does not like/support socket timeouts. + @logger.info "Unable to use raw socket timeouts: #{ex.class.name}: #{ex.message}" if @logger + end + end + sock + end + + def method_missing(*argv) + call_command(argv) + end + + def call_command(argv) + @logger.debug { argv.inspect } if @logger + + # this wrapper to raw_call_command handle reconnection on socket + # error. We try to reconnect just one time, otherwise let the error + # araise. + connect_to_server if !@sock + + begin + raw_call_command(argv.dup) + rescue Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED + @sock.close rescue nil + @sock = nil + connect_to_server + raw_call_command(argv.dup) + end + end + + def raw_call_command(argvp) + pipeline = argvp[0].is_a?(Array) + + unless pipeline + argvv = [argvp] + else + argvv = argvp + end + + if MULTI_BULK_COMMANDS[argvv.flatten[0].to_s] + # TODO improve this code + argvp = argvv.flatten + values = argvp.pop.to_a.flatten + argvp = values.unshift(argvp[0]) + command = ["*#{argvp.size}"] + argvp.each do |v| + v = v.to_s + command << "$#{get_size(v)}" + command << v + end + command = command.map {|cmd| "#{cmd}\r\n"}.join + else + command = "" + argvv.each do |argv| + bulk = nil + argv[0] = argv[0].to_s.downcase + argv[0] = ALIASES[argv[0]] if ALIASES[argv[0]] + raise "#{argv[0]} command is disabled" if DISABLED_COMMANDS[argv[0]] + if BULK_COMMANDS[argv[0]] and argv.length > 1 + bulk = argv[-1].to_s + argv[-1] = get_size(bulk) + end + command << "#{argv.join(' ')}\r\n" + command << "#{bulk}\r\n" if bulk + end + end + results = maybe_lock { process_command(command, argvv) } + + return pipeline ? results : results[0] + end + + def process_command(command, argvv) + @sock.write(command) + argvv.map do |argv| + processor = REPLY_PROCESSOR[argv[0]] + processor ? processor.call(read_reply) : read_reply + end + end + + def maybe_lock(&block) + if @thread_safe + @mutex.synchronize(&block) + else + block.call + end + end + + def select(*args) + raise "SELECT not allowed, use the :db option when creating the object" + end + + def [](key) + self.get(key) + end + + def []=(key,value) + set(key,value) + end + + def set(key, value, expiry=nil) + s = call_command([:set, key, value]) == OK + expire(key, expiry) if s && expiry + s + end + + def sort(key, options = {}) + cmd = ["SORT"] + cmd << key + cmd << "BY #{options[:by]}" if options[:by] + cmd << "GET #{[options[:get]].flatten * ' GET '}" if options[:get] + cmd << "#{options[:order]}" if options[:order] + cmd << "LIMIT #{options[:limit].join(' ')}" if options[:limit] + call_command(cmd) + end + + def incr(key, increment = nil) + call_command(increment ? ["incrby",key,increment] : ["incr",key]) + end + + def decr(key,decrement = nil) + call_command(decrement ? ["decrby",key,decrement] : ["decr",key]) + end + + # Similar to memcache.rb's #get_multi, returns a hash mapping + # keys to values. + def mapped_mget(*keys) + result = {} + mget(*keys).each do |value| + key = keys.shift + result.merge!(key => value) unless value.nil? + end + result + end + + # Ruby defines a now deprecated type method so we need to override it here + # since it will never hit method_missing + def type(key) + call_command(['type', key]) + end + + def quit + call_command(['quit']) + rescue Errno::ECONNRESET + end + + def pipelined(&block) + pipeline = Pipeline.new self + yield pipeline + pipeline.execute + end + + def read_reply + # We read the first byte using read() mainly because gets() is + # immune to raw socket timeouts. + begin + rtype = @sock.read(1) + rescue Errno::EAGAIN + # We want to make sure it reconnects on the next command after the + # timeout. Otherwise the server may reply in the meantime leaving + # the protocol in a desync status. + @sock = nil + raise Errno::EAGAIN, "Timeout reading from the socket" + end + + raise Errno::ECONNRESET,"Connection lost" if !rtype + line = @sock.gets + case rtype + when MINUS + raise MINUS + line.strip + when PLUS + line.strip + when COLON + line.to_i + when DOLLAR + bulklen = line.to_i + return nil if bulklen == -1 + data = @sock.read(bulklen) + @sock.read(2) # CRLF + data + when ASTERISK + objects = line.to_i + return nil if bulklen == -1 + res = [] + objects.times { + res << read_reply + } + res + else + raise "Protocol error, got '#{rtype}' as initial reply byte" + end + end + + private + def get_size(string) + string.respond_to?(:bytesize) ? string.bytesize : string.size + end +end diff --git a/lib/redis/counter.rb b/lib/redis/counter.rb new file mode 100644 index 0000000..d7523d5 --- /dev/null +++ b/lib/redis/counter.rb @@ -0,0 +1,94 @@ +class Redis + # + # Class representing a Redis counter. This functions like a proxy class, in + # that you can say @object.counter_name to get the value and then + # @object.counter_name.increment to operate on it. You can use this + # directly, or you can use the counter :foo class method in your + # class to define a counter. + # + class Counter + require 'redis/helpers/core_commands' + include Redis::Helpers::CoreCommands + + attr_reader :key, :options, :redis + def initialize(key, redis=$redis, options={}) + @key = key + @redis = redis + @options = options + @options[:start] ||= 0 + @redis.setnx(key, @options[:start]) unless @options[:start] == 0 || @options[:init] === false + end + + # Reset the counter to its starting value. Not atomic, so use with care. + # Normally only useful if you're discarding all sub-records associated + # with a parent and starting over (for example, restarting a game and + # disconnecting all players). + def reset(to=options[:start]) + redis.set key, to.to_i + end + + # Returns the current value of the counter. Normally just calling the + # counter will lazily fetch the value, and only update it if increment + # or decrement is called. This forces a network call to redis-server + # to get the current value. + def value + redis.get(key).to_i + end + alias_method :get, :value + + # Increment the counter atomically and return the new value. If passed + # a block, that block will be evaluated with the new value of the counter + # as an argument. If the block returns nil or throws an exception, the + # counter will automatically be decremented to its previous value. This + # method is aliased as incr() for brevity. + def increment(by=1, &block) + val = redis.incr(key, by).to_i + block_given? ? rewindable_block(:decrement, val, &block) : val + end + alias_method :incr, :increment + + # Decrement the counter atomically and return the new value. If passed + # a block, that block will be evaluated with the new value of the counter + # as an argument. If the block returns nil or throws an exception, the + # counter will automatically be incremented to its previous value. This + # method is aliased as incr() for brevity. + def decrement(by=1, &block) + val = redis.decr(key, by).to_i + block_given? ? rewindable_block(:increment, val, &block) : val + end + alias_method :decr, :decrement + + ## + # Proxy methods to help make @object.counter == 10 work + def to_s; value.to_s; end + alias_method :to_str, :to_s + alias_method :to_i, :value + def nil?; value.nil? end + + # Math ops + %w(== < > <= >=).each do |m| + class_eval <<-EndOverload + def #{m}(x) + value #{m} x + end + EndOverload + end + + private + + # Implements atomic increment/decrement blocks + def rewindable_block(rewind, value, &block) + raise ArgumentError, "Missing block to rewindable_block somehow" unless block_given? + ret = nil + begin + ret = yield value + rescue + send(rewind) + raise + end + send(rewind) if ret.nil? + ret + end + end +end + diff --git a/lib/redis/dist_redis.rb b/lib/redis/dist_redis.rb new file mode 100644 index 0000000..6740129 --- /dev/null +++ b/lib/redis/dist_redis.rb @@ -0,0 +1,149 @@ +require 'redis' +require 'hash_ring' +class DistRedis + attr_reader :ring + def initialize(opts={}) + hosts = [] + + db = opts[:db] || nil + timeout = opts[:timeout] || nil + + raise Error, "No hosts given" unless opts[:hosts] + + opts[:hosts].each do |h| + host, port = h.split(':') + hosts << Redis.new(:host => host, :port => port, :db => db, :timeout => timeout) + end + + @ring = HashRing.new hosts + end + + def node_for_key(key) + key = $1 if key =~ /\{(.*)?\}/ + @ring.get_node(key) + end + + def add_server(server) + server, port = server.split(':') + @ring.add_node Redis.new(:host => server, :port => port) + end + + def method_missing(sym, *args, &blk) + if redis = node_for_key(args.first.to_s) + redis.send sym, *args, &blk + else + super + end + end + + def keys(glob) + @ring.nodes.map do |red| + red.keys(glob) + end + end + + def save + on_each_node :save + end + + def bgsave + on_each_node :bgsave + end + + def quit + on_each_node :quit + end + + def flush_all + on_each_node :flush_all + end + alias_method :flushall, :flush_all + + def flush_db + on_each_node :flush_db + end + alias_method :flushdb, :flush_db + + def delete_cloud! + @ring.nodes.each do |red| + red.keys("*").each do |key| + red.delete key + end + end + end + + def on_each_node(command, *args) + @ring.nodes.each do |red| + red.send(command, *args) + end + end + + def mset() + + end + + def mget(*keyz) + results = {} + kbn = keys_by_node(keyz) + kbn.each do |node, node_keyz| + node.mapped_mget(*node_keyz).each do |k, v| + results[k] = v + end + end + keyz.flatten.map { |k| results[k] } + end + + def keys_by_node(*keyz) + keyz.flatten.inject({}) do |kbn, k| + node = node_for_key(k) + next if kbn[node] && kbn[node].include?(k) + kbn[node] ||= [] + kbn[node] << k + kbn + end + end + +end + + +if __FILE__ == $0 + +r = DistRedis.new 'localhost:6379', 'localhost:6380', 'localhost:6381', 'localhost:6382' + r['urmom'] = 'urmom' + r['urdad'] = 'urdad' + r['urmom1'] = 'urmom1' + r['urdad1'] = 'urdad1' + r['urmom2'] = 'urmom2' + r['urdad2'] = 'urdad2' + r['urmom3'] = 'urmom3' + r['urdad3'] = 'urdad3' + p r['urmom'] + p r['urdad'] + p r['urmom1'] + p r['urdad1'] + p r['urmom2'] + p r['urdad2'] + p r['urmom3'] + p r['urdad3'] + + r.push_tail 'listor', 'foo1' + r.push_tail 'listor', 'foo2' + r.push_tail 'listor', 'foo3' + r.push_tail 'listor', 'foo4' + r.push_tail 'listor', 'foo5' + + p r.pop_tail('listor') + p r.pop_tail('listor') + p r.pop_tail('listor') + p r.pop_tail('listor') + p r.pop_tail('listor') + + puts "key distribution:" + + r.ring.nodes.each do |red| + p [red.port, red.keys("*")] + end + r.delete_cloud! + p r.keys('*') + +end diff --git a/lib/redis/hash_ring.rb b/lib/redis/hash_ring.rb new file mode 100644 index 0000000..c912129 --- /dev/null +++ b/lib/redis/hash_ring.rb @@ -0,0 +1,135 @@ +require 'zlib' + +class HashRing + + POINTS_PER_SERVER = 160 # this is the default in libmemcached + + attr_reader :ring, :sorted_keys, :replicas, :nodes + + # nodes is a list of objects that have a proper to_s representation. + # replicas indicates how many virtual points should be used pr. node, + # replicas are required to improve the distribution. + def initialize(nodes=[], replicas=POINTS_PER_SERVER) + @replicas = replicas + @ring = {} + @nodes = [] + @sorted_keys = [] + nodes.each do |node| + add_node(node) + end + end + + # Adds a `node` to the hash ring (including a number of replicas). + def add_node(node) + @nodes << node + @replicas.times do |i| + key = Zlib.crc32("#{node}:#{i}") + @ring[key] = node + @sorted_keys << key + end + @sorted_keys.sort! + end + + def remove_node(node) + @nodes.reject!{|n| n.to_s == node.to_s} + @replicas.times do |i| + key = Zlib.crc32("#{node}:#{i}") + @ring.delete(key) + @sorted_keys.reject! {|k| k == key} + end + end + + # get the node in the hash ring for this key + def get_node(key) + get_node_pos(key)[0] + end + + def get_node_pos(key) + return [nil,nil] if @ring.size == 0 + crc = Zlib.crc32(key) + idx = HashRing.binary_search(@sorted_keys, crc) + return [@ring[@sorted_keys[idx]], idx] + end + + def iter_nodes(key) + return [nil,nil] if @ring.size == 0 + node, pos = get_node_pos(key) + @sorted_keys[pos..-1].each do |k| + yield @ring[k] + end + end + + class << self + + # gem install RubyInline to use this code + # Native extension to perform the binary search within the hashring. + # There's a pure ruby version below so this is purely optional + # for performance. In testing 20k gets and sets, the native + # binary search shaved about 12% off the runtime (9sec -> 8sec). + begin + require 'inline' + inline do |builder| + builder.c <<-EOM + int binary_search(VALUE ary, unsigned int r) { + int upper = RARRAY_LEN(ary) - 1; + int lower = 0; + int idx = 0; + + while (lower <= upper) { + idx = (lower + upper) / 2; + + VALUE continuumValue = RARRAY_PTR(ary)[idx]; + unsigned int l = NUM2UINT(continuumValue); + if (l == r) { + return idx; + } + else if (l > r) { + upper = idx - 1; + } + else { + lower = idx + 1; + } + } + if (upper < 0) { + upper = RARRAY_LEN(ary) - 1; + } + return upper; + } + EOM + end + rescue Exception => e + # Find the closest index in HashRing with value <= the given value + def binary_search(ary, value, &block) + upper = ary.size - 1 + lower = 0 + idx = 0 + + while(lower <= upper) do + idx = (lower + upper) / 2 + comp = ary[idx] <=> value + + if comp == 0 + return idx + elsif comp > 0 + upper = idx - 1 + else + lower = idx + 1 + end + end + + if upper < 0 + upper = ary.size - 1 + end + return upper + end + + end + end + +end + +# ring = HashRing.new ['server1', 'server2', 'server3'] +# p ring +# # +# p ring.get_node "kjhjkjlkjlkkh" +# \ No newline at end of file diff --git a/lib/redis/helpers/core_commands.rb b/lib/redis/helpers/core_commands.rb new file mode 100644 index 0000000..bdd4214 --- /dev/null +++ b/lib/redis/helpers/core_commands.rb @@ -0,0 +1,46 @@ +class Redis + module Helpers + # These are core commands that all types share (rename, etc) + module CoreCommands + def exists? + redis.exists key + end + + def delete + redis.del key + end + alias_method :del, :delete + alias_method :clear, :delete + + def type + redis.type key + end + + def rename(name, setkey=true) + dest = name.is_a?(self.class) ? name.key : name + ret = redis.rename key, dest + @key = dest if ret && setkey + ret + end + + def renamenx(name, setkey=true) + dest = name.is_a?(self.class) ? name.key : name + ret = redis.renamenx key, dest + @key = dest if ret && setkey + ret + end + + def expire(seconds) + redis.expire key, seconds + end + + def expireat(unixtime) + redis.expire key, unixtime + end + + def move(dbindex) + redis.move key, dbindex + end + end + end +end diff --git a/lib/redis/helpers/serialize.rb b/lib/redis/helpers/serialize.rb new file mode 100644 index 0000000..7be4a81 --- /dev/null +++ b/lib/redis/helpers/serialize.rb @@ -0,0 +1,25 @@ +class Redis + module Helpers + module Serialize + include Marshal + + def to_redis(value) + case value + when String, Fixnum, Bignum, Float + value + else + dump(value) + end + end + + def from_redis(value) + case value + when Array + value.collect{|v| from_redis(v)} + else + restore(value) rescue value + end + end + end + end +end \ No newline at end of file diff --git a/lib/redis/list.rb b/lib/redis/list.rb new file mode 100644 index 0000000..26bb467 --- /dev/null +++ b/lib/redis/list.rb @@ -0,0 +1,122 @@ +class Redis + # + # Class representing a Redis list. Instances of Redis::List are designed to + # behave as much like Ruby arrays as possible. + # + class List + require 'enumerator' + include Enumerable + require 'redis/helpers/core_commands' + include Redis::Helpers::CoreCommands + require 'redis/helpers/serialize' + include Redis::Helpers::Serialize + + attr_reader :key, :options, :redis + + def initialize(key, redis=$redis, options={}) + @key = key + @redis = redis + @options = options + end + + # Works like push. Can chain together: list << 'a' << 'b' + def <<(value) + push(value) + self # for << 'a' << 'b' + end + + # Add a member to the end of the list. Redis: RPUSH + def push(value) + redis.rpush(key, to_redis(value)) + end + + # Remove a member from the end of the list. Redis: RPOP + def pop + from_redis redis.rpop(key) + end + + # Add a member to the start of the list. Redis: LPUSH + def unshift(value) + redis.lpush(key, to_redis(value)) + end + + # Remove a member from the start of the list. Redis: LPOP + def shift + from_redis redis.lpop(key) + end + + # Return all values in the list. Redis: LRANGE(0,-1) + def values + from_redis range(0, -1) + end + alias_method :get, :values + + # Same functionality as Ruby arrays. If a single number is given, return + # just the element at that index using Redis: LINDEX. Otherwise, return + # a range of values using Redis: LRANGE. + def [](index, length=nil) + if index.is_a? Range + range(index.first, index.last) + elsif length + range(index, length) + else + at(index) + end + end + + # Delete the element(s) from the list that match name. If count is specified, + # only the first-N (if positive) or last-N (if negative) will be removed. + # Use .del to completely delete the entire key. + # Redis: LREM + def delete(name, count=0) + redis.lrem(key, count, name) # weird api + end + + # Iterate through each member of the set. Redis::Objects mixes in Enumerable, + # so you can also use familiar methods like +collect+, +detect+, and so forth. + def each(&block) + values.each(&block) + end + + # Return a range of values from +start_index+ to +end_index+. Can also use + # the familiar list[start,end] Ruby syntax. Redis: LRANGE + def range(start_index, end_index) + from_redis redis.lrange(key, start_index, end_index) + end + + # Return the value at the given index. Can also use familiar list[index] syntax. + # Redis: LINDEX + def at(index) + from_redis redis.lindex(key, index) + end + + # Return the first element in the list. Redis: LINDEX(0) + def first + at(0) + end + + # Return the last element in the list. Redis: LINDEX(-1) + def last + at(-1) + end + + # Return the length of the list. Aliased as size. Redis: LLEN + def length + redis.llen(key) + end + alias_method :size, :length + + # Returns true if there are no elements in the list. Redis: LLEN == 0 + def empty? + length == 0 + end + + def ==(x) + values == x + end + + def to_s + values.join(', ') + end + end +end \ No newline at end of file diff --git a/lib/redis/lock.rb b/lib/redis/lock.rb new file mode 100644 index 0000000..2405b3e --- /dev/null +++ b/lib/redis/lock.rb @@ -0,0 +1,83 @@ +class Redis + # + # Class representing a lock. This functions like a proxy class, in + # that you can say @object.lock_name { block } to use the lock and also + # @object.counter_name.clear to reset on it. You can use this + # directly, but it is better to use the lock :foo class method in your + # class to define a lock. + # + class Lock + class LockTimeout < StandardError; end #:nodoc: + + attr_reader :key, :options, :redis + def initialize(key, redis=$redis, options={}) + @key = key + @redis = redis + @options = options + @options[:timeout] ||= 5 + @redis.setnx(key, @options[:start]) unless @options[:start] == 0 || @options[:init] === false + end + + # Clear the lock. Should only be needed if there's a server crash + # or some other event that gets locks in a stuck state. + def clear + redis.del(key) + end + alias_method :delete, :clear + + # Get the lock and execute the code block. Any other code that needs the lock + # (on any server) will spin waiting for the lock up to the :timeout + # that was specified when the lock was defined. + def lock(&block) + start = Time.now + gotit = false + expiration = nil + while Time.now - start < @options[:timeout] + expiration = generate_expiration + # Use the expiration as the value of the lock. + gotit = redis.setnx(key, expiration) + break if gotit + + # Lock is being held. Now check to see if it's expired (if we're using + # lock expiration). + # See "Handling Deadlocks" section on http://code.google.com/p/redis/wiki/SetnxCommand + if !@options[:expiration].nil? + old_expiration = redis.get(key).to_f + + if old_expiration < Time.now.to_f + # If it's expired, use GETSET to update it. + expiration = generate_expiration + old_expiration = redis.getset(key, expiration).to_f + + # Since GETSET returns the old value of the lock, if the old expiration + # is still in the past, we know no one else has expired the locked + # and we now have it. + if old_expiration < Time.now.to_f + gotit = true + break + end + end + end + + sleep 0.1 + end + raise LockTimeout, "Timeout on lock #{key} exceeded #{@options[:timeout]} sec" unless gotit + begin + yield + ensure + # We need to be careful when cleaning up the lock key. If we took a really long + # time for some reason, and the lock expired, someone else may have it, and + # it's not safe for us to remove it. Check how much time has passed since we + # wrote the lock key and only delete it if it hasn't expired (or we're not using + # lock expiration) + if @options[:expiration].nil? || expiration > Time.now.to_f + redis.del(key) + end + end + end + + def generate_expiration + @options[:expiration].nil? ? 1 : (Time.now + @options[:expiration].to_f + 1).to_f + end + end +end \ No newline at end of file diff --git a/lib/redis/objects.rb b/lib/redis/objects.rb new file mode 100644 index 0000000..0885c2a --- /dev/null +++ b/lib/redis/objects.rb @@ -0,0 +1,100 @@ +# Redis::Objects - Lightweight object layer around redis-rb +# See README.rdoc for usage and approach. + +class Redis + # + # Redis::Objects enables high-performance atomic operations in your app + # by leveraging the atomic features of the Redis server. To use Redis::Objects, + # first include it in any class you want. (This example uses an ActiveRecord + # subclass, but that is *not* required.) Then, use +counter+ and +lock+ + # to define your primitives: + # + # class Game < ActiveRecord::Base + # include Redis::Objects + # + # counter :joined_players + # counter :active_players + # set :player_ids + # lock :archive_game + # end + # + # The, you can use these counters both for bookeeping and as atomic actions: + # + # @game = Game.find(id) + # @game_user = @game.joined_players.increment do |val| + # break if val > @game.max_players + # gu = @game.game_users.create!(:user_id => @user.id) + # @game.active_players.increment + # gu + # end + # if @game_user.nil? + # # game is full - error screen + # else + # # success + # end + # + # + # + module Objects + dir = File.expand_path(__FILE__.sub(/\.rb$/,'')) + + autoload :Counters, File.join(dir, 'counters') + autoload :Values, File.join(dir, 'values') + autoload :Lists, File.join(dir, 'lists') + autoload :Sets, File.join(dir, 'sets') + autoload :Locks, File.join(dir, 'locks') + + class NotConnected < StandardError; end + + class << self + # def redis=(conn) @redis = conn end + # def redis + # @redis ||= $redis || raise(NotConnected, "Redis::Objects.redis not set to a Redis.new connection") + # end + + def included(klass) + # Core (this file) + #klass.instance_variable_set('@redis', @redis) + klass.instance_variable_set('@redis_objects', {}) + klass.send :include, InstanceMethods + klass.extend ClassMethods + + # Pull in each object type + klass.send :include, Redis::Objects::Counters + klass.send :include, Redis::Objects::Values + klass.send :include, Redis::Objects::Lists + klass.send :include, Redis::Objects::Sets + klass.send :include, Redis::Objects::Locks + end + end + + # Class methods that appear in your class when you include Redis::Objects. + module ClassMethods + #attr_accessor :redis, :redis_objects + attr_accessor :redis_objects + + # Set the Redis prefix to use. Defaults to model_name + def prefix=(prefix) @prefix = prefix end + def prefix #:nodoc: + @prefix ||= self.name.to_s. + sub(%r{(.*::)}, ''). + gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). + gsub(/([a-z\d])([A-Z])/,'\1_\2'). + downcase + end + + def field_key(name, id) #:nodoc: + "#{prefix}:#{id}:#{name}" + end + + end + + # Instance methods that appear in your class when you include Redis::Objects. + module InstanceMethods + def redis() self.class.connection end + def field_key(name) #:nodoc: + self.class.field_key(name, id) + end + end + end +end diff --git a/lib/redis/objects/counters.rb b/lib/redis/objects/counters.rb new file mode 100644 index 0000000..82e1421 --- /dev/null +++ b/lib/redis/objects/counters.rb @@ -0,0 +1,132 @@ +# This is the class loader, for use as "include Redis::Objects::Counters" +# For the object itself, see "Redis::Counter" +require 'redis/counter' +class Redis + module Objects + class UndefinedCounter < StandardError; end #:nodoc: + class MissingID < StandardError; end #:nodoc: + + module Counters + def self.included(klass) + klass.instance_variable_set('@initialized_counters', {}) + klass.send :include, InstanceMethods + klass.extend ClassMethods + end + + # Class methods that appear in your class when you include Redis::Objects. + module ClassMethods + attr_reader :initialized_counters + + # Define a new counter. It will function like a regular instance + # method, so it can be used alongside ActiveRecord, DataMapper, etc. + def counter(name, options={}) + options[:start] ||= 0 + options[:type] ||= options[:start] == 0 ? :increment : :decrement + @redis_objects[name] = options.merge(:type => :counter) + if options[:global] + instance_eval <<-EndMethods + def #{name} + @#{name} ||= Redis::Counter.new(field_key(:#{name}, ''), redis, @redis_objects[:#{name}]) + end + EndMethods + class_eval <<-EndMethods + def #{name} + self.class.#{name} + end + EndMethods + else + class_eval <<-EndMethods + def #{name} + @#{name} ||= Redis::Counter.new(field_key(:#{name}), redis, self.class.redis_objects[:#{name}]) + end + EndMethods + end + end + + # Get the current value of the counter. It is more efficient + # to use the instance method if possible. + def get_counter(name, id=nil) + verify_counter_defined!(name, id) + initialize_counter!(name, id) + redis.get(field_key(name, id)).to_i + end + + # Increment a counter with the specified name and id. Accepts a block + # like the instance method. See Redis::Objects::Counter for details. + def increment_counter(name, id=nil, by=1, &block) + verify_counter_defined!(name, id) + initialize_counter!(name, id) + value = redis.incr(field_key(name, id), by).to_i + block_given? ? rewindable_block(:decrement_counter, name, id, value, &block) : value + end + + # Decrement a counter with the specified name and id. Accepts a block + # like the instance method. See Redis::Objects::Counter for details. + def decrement_counter(name, id=nil, by=1, &block) + verify_counter_defined!(name, id) + initialize_counter!(name, id) + value = redis.decr(field_key(name, id), by).to_i + block_given? ? rewindable_block(:increment_counter, name, id, value, &block) : value + end + + # Reset a counter to its starting value. + def reset_counter(name, id=nil, to=nil) + verify_counter_defined!(name, id) + to = @redis_objects[name][:start] if to.nil? + redis.set(field_key(name, id), to) + end + + private + + def verify_counter_defined!(name, id) #:nodoc: + raise Redis::Objects::UndefinedCounter, "Undefined counter :#{name} for class #{self.name}" unless @redis_objects.has_key?(name) + if id.nil? and !@redis_objects[name][:global] + raise Redis::Objects::MissingID, "Missing ID for non-global counter #{self.name}##{name}" + end + end + + def initialize_counter!(name, id) #:nodoc: + key = field_key(name, id) + unless @initialized_counters[key] + redis.setnx(key, @redis_objects[name][:start]) + end + @initialized_counters[key] = true + end + + # Implements increment/decrement blocks on a class level + def rewindable_block(rewind, name, id, value, &block) #:nodoc: + # Unfortunately this is almost exactly duplicated from Redis::Counter + raise ArgumentError, "Missing block to rewindable_block somehow" unless block_given? + ret = nil + begin + ret = yield value + rescue + send(rewind, name, id) + raise + end + send(rewind, name, id) if ret.nil? + ret + end + end + + # Instance methods that appear in your class when you include Redis::Objects. + module InstanceMethods + # Increment a counter. + # It is more efficient to use increment_[counter_name] directly. + # This is mainly just for completeness to override ActiveRecord. + def increment(name, by=1) + raise(ActiveRedis::Errors::NotSavedError) if self.new? + send(name).increment(by) + end + + # Decrement a counter. + # It is more efficient to use increment_[counter_name] directly. + # This is mainly just for completeness to override ActiveRecord. + def decrement(name, by=1) + raise(ActiveRedis::Errors::NotSavedError) if self.new? + send(name).decrement(by) + end + end + end + end +end \ No newline at end of file diff --git a/lib/redis/objects/lists.rb b/lib/redis/objects/lists.rb new file mode 100644 index 0000000..444bdc2 --- /dev/null +++ b/lib/redis/objects/lists.rb @@ -0,0 +1,45 @@ +# This is the class loader, for use as "include Redis::Objects::Lists" +# For the object itself, see "Redis::List" +require 'redis/list' +class Redis + module Objects + module Lists + def self.included(klass) + klass.send :include, InstanceMethods + klass.extend ClassMethods + end + + # Class methods that appear in your class when you include Redis::Objects. + module ClassMethods + # Define a new list. It will function like a regular instance + # method, so it can be used alongside ActiveRecord, DataMapper, etc. + def list(name, options={}) + @redis_objects[name] = options.merge(:type => :list) + if options[:global] + instance_eval <<-EndMethods + def #{name} + @#{name} ||= Redis::List.new(field_key(:#{name}, ''), redis, @redis_objects[:#{name}]) + end + EndMethods + class_eval <<-EndMethods + def #{name} + self.class.#{name} + end + EndMethods + else + class_eval <<-EndMethods + def #{name} + raise(ActiveRedis::Errors::NotSavedError) if self.new? + @#{name} ||= Redis::List.new(field_key(:#{name}), redis, self.class.redis_objects[:#{name}]) + end + EndMethods + end + end + end + + # Instance methods that appear in your class when you include Redis::Objects. + module InstanceMethods + end + end + end +end \ No newline at end of file diff --git a/lib/redis/objects/locks.rb b/lib/redis/objects/locks.rb new file mode 100644 index 0000000..c3f9522 --- /dev/null +++ b/lib/redis/objects/locks.rb @@ -0,0 +1,71 @@ +# This is the class loader, for use as "include Redis::Objects::Locks" +# For the object itself, see "Redis::Lock" +require 'redis/lock' +class Redis + module Objects + class UndefinedLock < StandardError; end #:nodoc: + module Locks + def self.included(klass) + klass.send :include, InstanceMethods + klass.extend ClassMethods + end + + # Class methods that appear in your class when you include Redis::Objects. + module ClassMethods + # Define a new lock. It will function like a model attribute, + # so it can be used alongside ActiveRecord/DataMapper, etc. + def lock(name, options={}) + options[:timeout] ||= 5 # seconds + options[:init] = false if options[:init].nil? # default :init to false + @redis_objects[name] = options.merge(:type => :lock) + if options[:global] + instance_eval <<-EndMethods + def #{name}_lock(&block) + @#{name} ||= Redis::Lock.new(field_key(:#{name}_lock, ''), redis, @redis_objects[:#{name}]) + end + EndMethods + class_eval <<-EndMethods + def #{name}_lock(&block) + self.class.#{name}(block) + end + EndMethods + else + class_eval <<-EndMethods + def #{name}_lock(&block) + raise(ActiveRedis::Errors::NotSavedError) if self.new? + @#{name} ||= Redis::Lock.new(field_key(:#{name}_lock), redis, self.class.redis_objects[:#{name}]) + end + EndMethods + end + + + + end + + # Obtain a lock, and execute the block synchronously. Any other code + # (on any server) will spin waiting for the lock up to the :timeout + # that was specified when the lock was defined. + def obtain_lock(name, id, &block) + verify_lock_defined!(name) + raise ArgumentError, "Missing block to #{self.name}.obtain_lock" unless block_given? + lock_name = field_key("#{name}_lock", id) + Redis::Lock.new(lock_name, redis, self.redis_objects[name]).lock(&block) + end + + # Clear the lock. Use with care - usually only in an Admin page to clear + # stale locks (a stale lock should only happen if a server crashes.) + def clear_lock(name, id) + verify_lock_defined!(name) + lock_name = field_key("#{name}_lock", id) + redis.del(lock_name) + end + + private + + def verify_lock_defined!(name) + raise Redis::Objects::UndefinedLock, "Undefined lock :#{name} for class #{self.name}" unless @redis_objects.has_key?(name) + end + end + end + end +end diff --git a/lib/redis/objects/sets.rb b/lib/redis/objects/sets.rb new file mode 100644 index 0000000..1c2760e --- /dev/null +++ b/lib/redis/objects/sets.rb @@ -0,0 +1,46 @@ +# This is the class loader, for use as "include Redis::Objects::Sets" +# For the object itself, see "Redis::Set" +require 'redis/set' +class Redis + module Objects + module Sets + def self.included(klass) + klass.send :include, InstanceMethods + klass.extend ClassMethods + end + + # Class methods that appear in your class when you include Redis::Objects. + module ClassMethods + # Define a new list. It will function like a regular instance + # method, so it can be used alongside ActiveRecord, DataMapper, etc. + def set(name, options={}) + @redis_objects[name] = options.merge(:type => :set) + if options[:global] + instance_eval <<-EndMethods + def #{name} + @#{name} ||= Redis::Set.new(field_key(:#{name}, ''), redis, @redis_objects[:#{name}]) + end + EndMethods + class_eval <<-EndMethods + def #{name} + self.class.#{name} + end + EndMethods + else + class_eval <<-EndMethods + def #{name} + raise(ActiveRedis::Errors::NotSavedError) if self.new? + @#{name} ||= Redis::Set.new(field_key(:#{name}), redis, self.class.redis_objects[:#{name}]) + end + EndMethods + end + + end + end + + # Instance methods that appear in your class when you include Redis::Objects. + module InstanceMethods + end + end + end +end \ No newline at end of file diff --git a/lib/redis/objects/values.rb b/lib/redis/objects/values.rb new file mode 100644 index 0000000..ec3bb67 --- /dev/null +++ b/lib/redis/objects/values.rb @@ -0,0 +1,56 @@ +# This is the class loader, for use as "include Redis::Objects::Values" +# For the object itself, see "Redis::Value" +require 'redis/value' +class Redis + module Objects + module Values + def self.included(klass) + klass.send :include, InstanceMethods + klass.extend ClassMethods + end + + # Class methods that appear in your class when you include Redis::Objects. + module ClassMethods + # Define a new simple value. It will function like a regular instance + # method, so it can be used alongside ActiveRecord, DataMapper, etc. + def value(name, options={}) + @redis_objects[name] = options.merge(:type => :value) + if options[:global] + instance_eval <<-EndMethods + def #{name} + @#{name} ||= Redis::Value.new(field_key(:#{name}, ''), redis, @redis_objects[:#{name}]) + end + def #{name}=(value) + #{name}.value = value + end + EndMethods + class_eval <<-EndMethods + def #{name} + self.class.#{name} + end + def #{name}=(value) + self.class.#{name} = value + end + EndMethods + else + class_eval <<-EndMethods + def #{name} + raise(ActiveRedis::Errors::NotSavedError) if self.new? + @#{name} ||= Redis::Value.new(field_key(:#{name}), redis, self.class.redis_objects[:#{name}]) + end + def #{name}=(value) + raise(ActiveRedis::Errors::NotSavedError) if self.new? + #{name}.value = value + end + EndMethods + end + + end + end + + # Instance methods that appear in your class when you include Redis::Objects. + module InstanceMethods + end + end + end +end \ No newline at end of file diff --git a/lib/redis/pipeline.rb b/lib/redis/pipeline.rb new file mode 100644 index 0000000..92364d4 --- /dev/null +++ b/lib/redis/pipeline.rb @@ -0,0 +1,21 @@ +class Redis + class Pipeline < Redis + BUFFER_SIZE = 50_000 + + def initialize(redis) + @redis = redis + @commands = [] + end + + def call_command(command) + @commands << command + end + + def execute + return if @commands.empty? + @redis.call_command(@commands) + @commands.clear + end + + end +end diff --git a/lib/redis/set.rb b/lib/redis/set.rb new file mode 100644 index 0000000..10fecfb --- /dev/null +++ b/lib/redis/set.rb @@ -0,0 +1,156 @@ +class Redis + # + # Class representing a set. + # + class Set + require 'enumerator' + include Enumerable + require 'redis/helpers/core_commands' + include Redis::Helpers::CoreCommands + require 'redis/helpers/serialize' + include Redis::Helpers::Serialize + + attr_reader :key, :options, :redis + + # Create a new Set. + def initialize(key, redis=$redis, options={}) + @key = key + @redis = redis + @options = options + end + + # Works like add. Can chain together: list << 'a' << 'b' + def <<(value) + add(value) + self # for << 'a' << 'b' + end + + # Add the specified value to the set only if it does not exist already. + # Redis: SADD + def add(value) + redis.sadd(key, to_redis(value)) + end + + # Return all members in the set. Redis: SMEMBERS + def members + from_redis redis.smembers(key) + end + alias_method :get, :members + + # Returns true if the specified value is in the set. Redis: SISMEMBER + def member?(value) + redis.sismember(key, to_redis(value)) + end + alias_method :include?, :member? + + # Delete the value from the set. Redis: SREM + def delete(value) + redis.srem(key, value) + end + + # Iterate through each member of the set. Redis::Objects mixes in Enumerable, + # so you can also use familiar methods like +collect+, +detect+, and so forth. + def each(&block) + members.each(&block) + end + + # Return the intersection with another set. Can pass it either another set + # object or set name. Also available as & which is a bit cleaner: + # + # members_in_both = set1 & set2 + # + # If you want to specify multiple sets, you must use +intersection+: + # + # members_in_all = set1.intersection(set2, set3, set4) + # members_in_all = set1.inter(set2, set3, set4) # alias + # + # Redis: SINTER + def intersection(*sets) + from_redis redis.sinter(key, *keys_from_objects(sets)) + end + alias_method :intersect, :intersection + alias_method :inter, :intersection + alias_method :&, :intersection + + # Calculate the intersection and store it in Redis as +name+. Returns the number + # of elements in the stored intersection. Redis: SUNIONSTORE + def interstore(name, *sets) + redis.sinterstore(name, key, *keys_from_objects(sets)) + end + + # Return the union with another set. Can pass it either another set + # object or set name. Also available as | and + which are a bit cleaner: + # + # members_in_either = set1 | set2 + # members_in_either = set1 + set2 + # + # If you want to specify multiple sets, you must use +union+: + # + # members_in_all = set1.union(set2, set3, set4) + # + # Redis: SUNION + def union(*sets) + from_redis redis.sunion(key, *keys_from_objects(sets)) + end + alias_method :|, :union + alias_method :+, :union + + # Calculate the union and store it in Redis as +name+. Returns the number + # of elements in the stored union. Redis: SUNIONSTORE + def unionstore(name, *sets) + redis.sunionstore(name, key, *keys_from_objects(sets)) + end + + # Return the difference vs another set. Can pass it either another set + # object or set name. Also available as ^ or - which is a bit cleaner: + # + # members_difference = set1 ^ set2 + # members_difference = set1 - set2 + # + # If you want to specify multiple sets, you must use +difference+: + # + # members_difference = set1.difference(set2, set3, set4) + # members_difference = set1.diff(set2, set3, set4) + # + # Redis: SDIFF + def difference(*sets) + from_redis redis.sdiff(key, *keys_from_objects(sets)) + end + alias_method :diff, :difference + alias_method :^, :difference + alias_method :-, :difference + + # Calculate the diff and store it in Redis as +name+. Returns the number + # of elements in the stored union. Redis: SDIFFSTORE + def diffstore(name, *sets) + redis.sdiffstore(name, key, *keys_from_objects(sets)) + end + + # The number of members in the set. Aliased as size. Redis: SCARD + def length + redis.scard(key) + end + alias_method :size, :length + + # Returns true if the set has no members. Redis: SCARD == 0 + def empty? + length == 0 + end + + def ==(x) + members == x + end + + def to_s + members.join(', ') + end + + private + + def keys_from_objects(sets) + raise ArgumentError, "Must pass in one or more set names" if sets.empty? + sets.collect{|set| set.is_a?(Redis::Set) ? set.key : set} + end + + end +end \ No newline at end of file diff --git a/lib/redis/value.rb b/lib/redis/value.rb new file mode 100644 index 0000000..16327dc --- /dev/null +++ b/lib/redis/value.rb @@ -0,0 +1,35 @@ +class Redis + # + # Class representing a simple value. You can use standard Ruby operations on it. + # + class Value + require 'redis/helpers/core_commands' + include Redis::Helpers::CoreCommands + require 'redis/helpers/serialize' + include Redis::Helpers::Serialize + + attr_reader :key, :options, :redis + def initialize(key, redis=$redis, options={}) + @key = key + @redis = redis + @options = options + @redis.setnx(key, @options[:default]) if @options[:default] + end + + def value=(val) + redis.set key, to_redis(val) + end + alias_method :set, :value= + + def value + from_redis redis.get(key) + end + alias_method :get, :value + + def to_s; value.to_s; end + alias_method :to_str, :to_s + + def ==(x); value == x; end + def nil?; value.nil?; end + end +end \ No newline at end of file diff --git a/lib/riak_raw.rb b/lib/riak_raw.rb new file mode 100644 index 0000000..038e667 --- /dev/null +++ b/lib/riak_raw.rb @@ -0,0 +1,106 @@ +# gem "typhoeus", "= 0.1.18" +# gem "uuidtools", "= 2.1.1" +# gem "brianmario-yajl-ruby", "= 0.6.3" +# require "typhoeus" +# require "uuidtools" +# require "uri" +# require "yajl" + +# A Ruby interface for the Riak (http://riak.basho.com/) key-value store. +# +# Example Usage: +# +# > client = RiakRaw::Client.new('127.0.0.1', 8098, 'raw') +# > client.delete('raw_example', 'doctestkey') +# > obj = client.store('raw_example', 'doctestkey', {'foo':2}) +# > client.fetch('raw_example', 'doctestkey') +module RiakRaw + VERSION = '0.0.1' + + class Client + attr_accessor :host, :port, :prefix, :client_id + + def self.extract_header(headers, target_header) + headers.split("\r\n").select { |header| header =~ /^#{target_header}/ }[0].split(": ")[1] + rescue => e + nil + end + + def initialize(host="127.0.0.1", port=8098, prefix='riak', client_id=SecureRandom.base64) + @host = host + @port = port + @prefix = prefix + @client_id = client_id + end + + def bucket(bucket_name,keys=false) + #request(:get, build_path(bucket_name)) + response = request(:get, + build_path(bucket_name), + nil, nil, + {"returnbody" => "true", "keys" => keys}) + if response.code == 200 + if json = response.body + return Yajl::Parser.parse(json) + end + end; nil + end + + def store(bucket_name, key, content, vclock=nil, links=[], content_type='application/json', w=2, dw=2, r=2) + headers = { 'Content-Type' => content_type, + 'X-Riak-ClientId' => self.client_id } + if vclock + headers['X-Riak-Vclock'] = vclock + end + + response = request(:put, + build_path(bucket_name,key), + content, headers, + {"returnbody" => "false", "w" => w, "dw" => dw}) + + # returnbody=true could cause issues. instead we'll do a + # separate fetch. see: https://issues.basho.com/show_bug.cgi?id=52 + if response.code == 204 + response = fetch(bucket_name, key, r) + end + + response + end + + def fetch(bucket_name, key, r=2) + response = request(:get, + build_path(bucket_name, key), + nil, {}, {"r" => r}) + end + + # there could be concurrency issues if we don't force a short sleep + # after delete. see: https://issues.basho.com/show_bug.cgi?id=52 + def delete(bucket_name, key, dw=2) + response = request(:delete, + build_path(bucket_name, key), + nil, {}, {"dw" => dw}) + end + + private + + def build_path(bucket_name, key='') + "http://#{self.host}:#{self.port}/#{self.prefix}/#{URI.escape(bucket_name)}/#{URI.escape(key)}" + end + + def request(method, uri, body="", headers={}, params={}) + hydra = Typhoeus::Hydra.new + case method + when :get then + req = Typhoeus::Request.new(uri, :method => :get, :body => body, :headers => headers, :params => params) + when :post then + req = Typhoeus::Request.new(uri, :method => :post, :body => body, :headers => headers, :params => params) + when :put then + req = Typhoeus::Request.new(uri, :method => :put, :body => body, :headers => headers, :params => params) + when :delete then + req = Typhoeus::Request.new(uri, :method => :delete, :body => body, :headers => headers, :params => params) + end + hydra.queue(req); hydra.run + req.handled_response + end + end # Client +end \ No newline at end of file diff --git a/lib/typhoeus.rb b/lib/typhoeus.rb new file mode 100644 index 0000000..44cdb77 --- /dev/null +++ b/lib/typhoeus.rb @@ -0,0 +1,55 @@ +$LOAD_PATH.unshift(File.dirname(__FILE__)) unless $LOAD_PATH.include?(File.dirname(__FILE__)) + +require 'rack/utils' +require 'digest/sha2' +require 'typhoeus/easy' +require 'typhoeus/multi' +require 'typhoeus/native' +require 'typhoeus/filter' +require 'typhoeus/remote_method' +require 'typhoeus/remote' +require 'typhoeus/remote_proxy_object' +require 'typhoeus/response' +require 'typhoeus/request' +require 'typhoeus/hydra' + +module Typhoeus + VERSION = "0.1.22" + + def self.easy_object_pool + @easy_objects ||= [] + end + + def self.init_easy_object_pool + 20.times do + easy_object_pool << Typhoeus::Easy.new + end + end + + def self.release_easy_object(easy) + easy.reset + easy_object_pool << easy + end + + def self.get_easy_object + if easy_object_pool.empty? + Typhoeus::Easy.new + else + easy_object_pool.pop + end + end + + def self.add_easy_request(easy_object) + Thread.current[:curl_multi] ||= Typhoeus::Multi.new + Thread.current[:curl_multi].add(easy_object) + end + + def self.perform_easy_requests + multi = Thread.current[:curl_multi] + start_time = Time.now + multi.easy_handles.each do |easy| + easy.start_time = start_time + end + multi.perform + end +end diff --git a/lib/typhoeus/.gitignore b/lib/typhoeus/.gitignore new file mode 100644 index 0000000..08d271f --- /dev/null +++ b/lib/typhoeus/.gitignore @@ -0,0 +1 @@ +native.bundle \ No newline at end of file diff --git a/lib/typhoeus/easy.rb b/lib/typhoeus/easy.rb new file mode 100644 index 0000000..7fbbe54 --- /dev/null +++ b/lib/typhoeus/easy.rb @@ -0,0 +1,253 @@ +module Typhoeus + class Easy + attr_reader :response_body, :response_header, :method, :headers, :url + attr_accessor :start_time + + CURLINFO_STRING = 1048576 + OPTION_VALUES = { + :CURLOPT_URL => 10002, + :CURLOPT_HTTPGET => 80, + :CURLOPT_HTTPPOST => 10024, + :CURLOPT_UPLOAD => 46, + :CURLOPT_CUSTOMREQUEST => 10036, + :CURLOPT_POSTFIELDS => 10015, + :CURLOPT_POSTFIELDSIZE => 60, + :CURLOPT_USERAGENT => 10018, + :CURLOPT_TIMEOUT_MS => 155, + :CURLOPT_NOSIGNAL => 99, + :CURLOPT_HTTPHEADER => 10023, + :CURLOPT_FOLLOWLOCATION => 52, + :CURLOPT_MAXREDIRS => 68, + :CURLOPT_HTTPAUTH => 107, + :CURLOPT_USERPWD => 10000 + 5, + :CURLOPT_VERBOSE => 41, + :CURLOPT_PROXY => 10004, + :CURLOPT_VERIFYPEER => 64, + :CURLOPT_NOBODY => 44 + } + INFO_VALUES = { + :CURLINFO_RESPONSE_CODE => 2097154, + :CURLINFO_TOTAL_TIME => 3145731, + :CURLINFO_HTTPAUTH_AVAIL => 0x200000 + 23 + } + AUTH_TYPES = { + :CURLAUTH_BASIC => 1, + :CURLAUTH_DIGEST => 2, + :CURLAUTH_GSSNEGOTIATE => 4, + :CURLAUTH_NTLM => 8, + :CURLAUTH_DIGEST_IE => 16 + } + + def initialize + @method = :get + @post_dat_set = nil + @headers = {} + end + + def headers=(hash) + @headers = hash + end + + def proxy=(proxy) + set_option(OPTION_VALUES[:CURLOPT_PROXY], proxy) + end + + def auth=(authinfo) + set_option(OPTION_VALUES[:CURLOPT_USERPWD], "#{authinfo[:username]}:#{authinfo[:password]}") + set_option(OPTION_VALUES[:CURLOPT_HTTPAUTH], authinfo[:method]) if authinfo[:method] + end + + def auth_methods + get_info_long(INFO_VALUES[:CURLINFO_HTTPAUTH_AVAIL]) + end + + def verbose=(boolean) + set_option(OPTION_VALUES[:CURLOPT_VERBOSE], !!boolean ? 1 : 0) + end + + def total_time_taken + get_info_double(INFO_VALUES[:CURLINFO_TOTAL_TIME]) + end + + def response_code + get_info_long(INFO_VALUES[:CURLINFO_RESPONSE_CODE]) + end + + def follow_location=(boolean) + if boolean + set_option(OPTION_VALUES[:CURLOPT_FOLLOWLOCATION], 1) + else + set_option(OPTION_VALUES[:CURLOPT_FOLLOWLOCATION], 0) + end + end + + def max_redirects=(redirects) + set_option(OPTION_VALUES[:CURLOPT_MAXREDIRS], redirects) + end + + def timeout=(milliseconds) + @timeout = milliseconds + set_option(OPTION_VALUES[:CURLOPT_NOSIGNAL], 1) + set_option(OPTION_VALUES[:CURLOPT_TIMEOUT_MS], milliseconds) + end + + def timed_out? + @timeout && total_time_taken > @timeout && response_code == 0 + end + + def request_body=(request_body) + @request_body = request_body + if @method == :put + easy_set_request_body(@request_body) + headers["Transfer-Encoding"] = "" + headers["Expect"] = "" + else + self.post_data = request_body + end + end + + def user_agent=(user_agent) + set_option(OPTION_VALUES[:CURLOPT_USERAGENT], user_agent) + end + + def url=(url) + @url = url + set_option(OPTION_VALUES[:CURLOPT_URL], url) + end + + def disable_ssl_peer_verification + set_option(OPTION_VALUES[:CURLOPT_VERIFYPEER], 0) + end + + def method=(method) + @method = method + if method == :get + set_option(OPTION_VALUES[:CURLOPT_HTTPGET], 1) + elsif method == :post + set_option(OPTION_VALUES[:CURLOPT_HTTPPOST], 1) + self.post_data = "" + elsif method == :put + set_option(OPTION_VALUES[:CURLOPT_UPLOAD], 1) + self.request_body = "" unless @request_body + elsif method == :head + set_option(OPTION_VALUES[:CURLOPT_NOBODY], 1) + else + set_option(OPTION_VALUES[:CURLOPT_CUSTOMREQUEST], "DELETE") + end + end + + def post_data=(data) + @post_data_set = true + set_option(OPTION_VALUES[:CURLOPT_POSTFIELDS], data) + set_option(OPTION_VALUES[:CURLOPT_POSTFIELDSIZE], data.length) + end + + def params=(params) + params_string = params.keys.collect do |k| + value = params[k] + if value.is_a? Hash + value.keys.collect {|sk| Rack::Utils.escape("#{k}[#{sk}]") + "=" + Rack::Utils.escape(value[sk].to_s)} + elsif value.is_a? Array + key = Rack::Utils.escape(k.to_s) + value.collect { |v| "#{key}=#{Rack::Utils.escape(v.to_s)}" }.join('&') + else + "#{Rack::Utils.escape(k.to_s)}=#{Rack::Utils.escape(params[k].to_s)}" + end + end.flatten.join("&") + + if method == :post + self.post_data = params_string + else + self.url = "#{url}?#{params_string}" + end + end + + def set_option(option, value) + if value.class == String + easy_setopt_string(option, value) + else + easy_setopt_long(option, value) + end + end + + def perform + set_headers() + easy_perform() + response_code() + end + + def set_headers + headers.each_pair do |key, value| + easy_add_header("#{key}: #{value}") + end + easy_set_headers() unless headers.empty? + end + + # gets called when finished and response code is 200-299 + def success + @success.call(self) if @success + end + + def on_success(&block) + @success = block + end + + def on_success=(block) + @success = block + end + + # gets called when finished and response code is 300-599 + def failure + @failure.call(self) if @failure + end + + def on_failure(&block) + @failure = block + end + + def on_failure=(block) + @failure = block + end + + def retries + @retries ||= 0 + end + + def increment_retries + @retries ||= 0 + @retries += 1 + end + + def max_retries + @max_retries ||= 40 + end + + def max_retries? + retries >= max_retries + end + + def reset + @retries = 0 + @response_code = 0 + @response_header = "" + @response_body = "" + easy_reset() + end + + def get_info_string(option) + easy_getinfo_string(option) + end + + def get_info_long(option) + easy_getinfo_long(option) + end + + def get_info_double(option) + easy_getinfo_double(option) + end + + def curl_version + version + end + end +end diff --git a/lib/typhoeus/filter.rb b/lib/typhoeus/filter.rb new file mode 100644 index 0000000..9f970e9 --- /dev/null +++ b/lib/typhoeus/filter.rb @@ -0,0 +1,28 @@ +module Typhoeus + class Filter + attr_reader :method_name + + def initialize(method_name, options = {}) + @method_name = method_name + @options = options + end + + def apply_filter?(method_name) + if @options[:only] + if @options[:only].instance_of? Symbol + @options[:only] == method_name + else + @options[:only].include?(method_name) + end + elsif @options[:except] + if @options[:except].instance_of? Symbol + @options[:except] != method_name + else + !@options[:except].include?(method_name) + end + else + true + end + end + end +end \ No newline at end of file diff --git a/lib/typhoeus/hydra.rb b/lib/typhoeus/hydra.rb new file mode 100644 index 0000000..1a69138 --- /dev/null +++ b/lib/typhoeus/hydra.rb @@ -0,0 +1,210 @@ +module Typhoeus + class Hydra + def initialize(options = {}) + @memoize_requests = true + @multi = Multi.new + @easy_pool = [] + initial_pool_size = options[:initial_pool_size] || 10 + @max_concurrency = options[:max_concurrency] || 200 + initial_pool_size.times { @easy_pool << Easy.new } + @stubs = [] + @memoized_requests = {} + @retrieved_from_cache = {} + @queued_requests = [] + @running_requests = 0 + end + + def self.hydra + @hydra ||= new + end + + def self.hydra=(val) + @hydra = val + end + + def clear_stubs + @stubs = [] + end + + def fire_and_forget + @queued_requests.each {|r| queue(r, false)} + @multi.fire_and_forget + end + + def queue(request, obey_concurrency_limit = true) + return if assign_to_stub(request) + + if @running_requests >= @max_concurrency && obey_concurrency_limit + @queued_requests << request + else + if request.method == :get + if @memoize_requests && @memoized_requests.has_key?(request.url) + if response = @retrieved_from_cache[request.url] + request.response = response + request.call_handlers + else + @memoized_requests[request.url] << request + end + else + @memoized_requests[request.url] = [] if @memoize_requests + get_from_cache_or_queue(request) + end + else + get_from_cache_or_queue(request) + end + end + end + + def run + @stubs.each do |m| + m.requests.each do |request| + m.response.request = request + handle_request(request, m.response) + end + end + @multi.perform + @memoized_requests = {} + @retrieved_from_cache = {} + end + + def disable_memoization + @memoize_requests = false + end + + def cache_getter(&block) + @cache_getter = block + end + + def cache_setter(&block) + @cache_setter = block + end + + def on_complete(&block) + @on_complete = block + end + + def on_complete=(proc) + @on_complete = proc + end + + def stub(method, url) + @stubs << HydraMock.new(url, method) + @stubs.last + end + + def assign_to_stub(request) + m = @stubs.detect {|stub| stub.matches? request} + m && m.add_request(request) + end + private :assign_to_stub + + def get_from_cache_or_queue(request) + if @cache_getter + val = @cache_getter.call(request) + if val + @retrieved_from_cache[request.url] = val + handle_request(request, val, false) + else + @multi.add(get_easy_object(request)) + end + else + @multi.add(get_easy_object(request)) + end + end + private :get_from_cache_or_queue + + def get_easy_object(request) + @running_requests += 1 + easy = @easy_pool.pop || Easy.new + easy.url = request.url + easy.method = request.method + easy.params = request.params if request.method == :post && !request.params.nil? + easy.headers = request.headers if request.headers + easy.request_body = request.body if request.body + easy.timeout = request.timeout if request.timeout + easy.follow_location = request.follow_location if request.follow_location + easy.max_redirects = request.max_redirects if request.max_redirects + easy.proxy = request.proxy if request.proxy + easy.disable_ssl_peer_verification if request.disable_ssl_peer_verification + + easy.on_success do |easy| + queue_next + handle_request(request, response_from_easy(easy, request)) + release_easy_object(easy) + end + easy.on_failure do |easy| + queue_next + handle_request(request, response_from_easy(easy, request)) + release_easy_object(easy) + end + easy.set_headers + easy + end + private :get_easy_object + + def queue_next + @running_requests -= 1 + queue(@queued_requests.pop) unless @queued_requests.empty? + end + private :queue_next + + def release_easy_object(easy) + easy.reset + @easy_pool.push easy + end + private :release_easy_object + + def handle_request(request, response, live_request = true) + request.response = response + + if live_request && request.cache_timeout && @cache_setter + @cache_setter.call(request) + end + @on_complete.call(response) if @on_complete + + request.call_handlers + if requests = @memoized_requests[request.url] + requests.each do |r| + r.response = response + r.call_handlers + end + end + end + private :handle_request + + def response_from_easy(easy, request) + Response.new(:code => easy.response_code, + :headers => easy.response_header, + :body => easy.response_body, + :time => easy.total_time_taken, + :request => request) + end + private :response_from_easy + end + + class HydraMock + attr_reader :url, :method, :response, :requests + + def initialize(url, method) + @url = url + @method = method + @requests = [] + end + + def add_request(request) + @requests << request + end + + def and_return(val) + @response = val + end + + def matches?(request) + if url.kind_of?(String) + request.method == method && request.url == url + else + request.method == method && url =~ request.url + end + end + end +end diff --git a/lib/typhoeus/multi.rb b/lib/typhoeus/multi.rb new file mode 100644 index 0000000..acf0731 --- /dev/null +++ b/lib/typhoeus/multi.rb @@ -0,0 +1,34 @@ +module Typhoeus + class Multi + attr_reader :easy_handles + + def initialize + reset_easy_handles + end + + def remove(easy) + multi_remove_handle(easy) + end + + def add(easy) + @easy_handles << easy + multi_add_handle(easy) + end + + def perform() + while active_handle_count > 0 do + multi_perform + end + reset_easy_handles + end + + def cleanup() + multi_cleanup + end + + private + def reset_easy_handles + @easy_handles = [] + end + end +end diff --git a/lib/typhoeus/remote.rb b/lib/typhoeus/remote.rb new file mode 100644 index 0000000..d54d061 --- /dev/null +++ b/lib/typhoeus/remote.rb @@ -0,0 +1,306 @@ +module Typhoeus + USER_AGENT = "Typhoeus - http://github.com/pauldix/typhoeus/tree/master" + + def self.included(base) + base.extend ClassMethods + end + + class MockExpectedError < StandardError; end + + module ClassMethods + def allow_net_connect + @allow_net_connect = true if @allow_net_connect.nil? + @allow_net_connect + end + + def allow_net_connect=(value) + @allow_net_connect = value + end + + def mock(method, args = {}) + @remote_mocks ||= {} + @remote_mocks[method] ||= {} + args[:code] ||= 200 + args[:body] ||= "" + args[:headers] ||= "" + args[:time] ||= 0 + url = args.delete(:url) + url ||= :catch_all + params = args.delete(:params) + + key = mock_key_for(url, params) + + @remote_mocks[method][key] = args + end + + # Returns a key for a given URL and passed in + # set of Typhoeus options to be used to store/retrieve + # a corresponding mock. + def mock_key_for(url, params = nil) + if url == :catch_all + url + else + key = url + if params and !params.empty? + key += flatten_and_sort_hash(params).to_s + end + key + end + end + + def flatten_and_sort_hash(params) + params = params.dup + + # Flatten any sub-hashes to a single string. + params.keys.each do |key| + if params[key].is_a?(Hash) + params[key] = params[key].sort_by { |k, v| k.to_s.downcase }.to_s + end + end + + params.sort_by { |k, v| k.to_s.downcase } + end + + def get_mock(method, url, options) + return nil unless @remote_mocks + if @remote_mocks.has_key? method + extra_response_args = { :requested_http_method => method, + :requested_url => url, + :start_time => Time.now } + mock_key = mock_key_for(url, options[:params]) + if @remote_mocks[method].has_key? mock_key + get_mock_and_run_handlers(method, + @remote_mocks[method][mock_key].merge( + extra_response_args), + options) + elsif @remote_mocks[method].has_key? :catch_all + get_mock_and_run_handlers(method, + @remote_mocks[method][:catch_all].merge( + extra_response_args), + options) + else + nil + end + else + nil + end + end + + def enforce_allow_net_connect!(http_verb, url, params = nil) + if !allow_net_connect + message = "Real HTTP connections are disabled. Unregistered request: " << + "#{http_verb.to_s.upcase} #{url}\n" << + " Try: mock(:#{http_verb}, :url => \"#{url}\"" + if params + message << ",\n :params => #{params.inspect}" + end + + message << ")" + + raise MockExpectedError, message + end + end + + def check_expected_headers!(response_args, options) + missing_headers = {} + + response_args[:expected_headers].each do |key, value| + if options[:headers].nil? + missing_headers[key] = [value, nil] + elsif ((options[:headers][key] && value != :anything) && + options[:headers][key] != value) + + missing_headers[key] = [value, options[:headers][key]] + end + end + + unless missing_headers.empty? + raise headers_error_summary(response_args, options, missing_headers, 'expected') + end + end + + def check_unexpected_headers!(response_args, options) + bad_headers = {} + response_args[:unexpected_headers].each do |key, value| + if (options[:headers][key] && value == :anything) || + (options[:headers][key] == value) + bad_headers[key] = [value, options[:headers][key]] + end + end + + unless bad_headers.empty? + raise headers_error_summary(response_args, options, bad_headers, 'did not expect') + end + end + + def headers_error_summary(response_args, options, missing_headers, lead_in) + error = "#{lead_in} the following headers: #{response_args[:expected_headers].inspect}, but received: #{options[:headers].inspect}\n\n" + error << "Differences:\n" + error << "------------\n" + missing_headers.each do |key, values| + error << " - #{key}: #{lead_in} #{values[0].inspect}, got #{values[1].inspect}\n" + end + + error + end + private :headers_error_summary + + def get_mock_and_run_handlers(method, response_args, options) + response = Response.new(response_args) + + if response_args.has_key? :expected_body + raise "#{method} expected body of \"#{response_args[:expected_body]}\" but received #{options[:body]}" if response_args[:expected_body] != options[:body] + end + + if response_args.has_key? :expected_headers + check_expected_headers!(response_args, options) + end + + if response_args.has_key? :unexpected_headers + check_unexpected_headers!(response_args, options) + end + + if response.code >= 200 && response.code < 300 && options.has_key?(:on_success) + response = options[:on_success].call(response) + elsif options.has_key?(:on_failure) + response = options[:on_failure].call(response) + end + + encode_nil_response(response) + end + + [:get, :post, :put, :delete].each do |method| + line = __LINE__ + 2 # get any errors on the correct line num + code = <<-SRC + def #{method.to_s}(url, options = {}) + mock_object = get_mock(:#{method.to_s}, url, options) + unless mock_object.nil? + decode_nil_response(mock_object) + else + enforce_allow_net_connect!(:#{method.to_s}, url, options[:params]) + remote_proxy_object(url, :#{method.to_s}, options) + end + end + SRC + module_eval(code, "./lib/typhoeus/remote.rb", line) + end + + def remote_proxy_object(url, method, options) + easy = Typhoeus.get_easy_object + + easy.url = url + easy.method = method + easy.headers = options[:headers] if options.has_key?(:headers) + easy.headers["User-Agent"] = (options[:user_agent] || Typhoeus::USER_AGENT) + easy.params = options[:params] if options[:params] + easy.request_body = options[:body] if options[:body] + easy.timeout = options[:timeout] if options[:timeout] + easy.set_headers + + proxy = Typhoeus::RemoteProxyObject.new(clear_memoized_proxy_objects, easy, options) + set_memoized_proxy_object(method, url, options, proxy) + end + + def remote_defaults(options) + @remote_defaults ||= {} + @remote_defaults.merge!(options) if options + @remote_defaults + end + + # If we get subclassed, make sure that child inherits the remote defaults + # of the parent class. + def inherited(child) + child.__send__(:remote_defaults, @remote_defaults) + end + + def call_remote_method(method_name, args) + m = @remote_methods[method_name] + + base_uri = args.delete(:base_uri) || m.base_uri || "" + + if args.has_key? :path + path = args.delete(:path) + else + path = m.interpolate_path_with_arguments(args) + end + path ||= "" + + http_method = m.http_method + url = base_uri + path + options = m.merge_options(args) + + # proxy_object = memoized_proxy_object(http_method, url, options) + # return proxy_object unless proxy_object.nil? + # + # if m.cache_responses? + # object = @cache.get(get_memcache_response_key(method_name, args)) + # if object + # set_memoized_proxy_object(http_method, url, options, object) + # return object + # end + # end + + proxy = memoized_proxy_object(http_method, url, options) + unless proxy + if m.cache_responses? + options[:cache] = @cache + options[:cache_key] = get_memcache_response_key(method_name, args) + options[:cache_timeout] = m.cache_ttl + end + proxy = send(http_method, url, options) + end + proxy + end + + def set_memoized_proxy_object(http_method, url, options, object) + @memoized_proxy_objects ||= {} + @memoized_proxy_objects["#{http_method}_#{url}_#{options.to_s}"] = object + end + + def memoized_proxy_object(http_method, url, options) + @memoized_proxy_objects ||= {} + @memoized_proxy_objects["#{http_method}_#{url}_#{options.to_s}"] + end + + def clear_memoized_proxy_objects + lambda { @memoized_proxy_objects = {} } + end + + def get_memcache_response_key(remote_method_name, args) + result = "#{remote_method_name.to_s}-#{args.to_s}" + (Digest::SHA2.new << result).to_s + end + + def cache=(cache) + @cache = cache + end + + def define_remote_method(name, args = {}) + @remote_defaults ||= {} + args[:method] ||= @remote_defaults[:method] + args[:on_success] ||= @remote_defaults[:on_success] + args[:on_failure] ||= @remote_defaults[:on_failure] + args[:base_uri] ||= @remote_defaults[:base_uri] + args[:path] ||= @remote_defaults[:path] + m = RemoteMethod.new(args) + + @remote_methods ||= {} + @remote_methods[name] = m + + class_eval <<-SRC + def self.#{name.to_s}(args = {}) + call_remote_method(:#{name.to_s}, args) + end + SRC + end + + private + def encode_nil_response(response) + response == nil ? :__nil__ : response + end + + def decode_nil_response(response) + response == :__nil__ ? nil : response + end + end # ClassMethods +end diff --git a/lib/typhoeus/remote_method.rb b/lib/typhoeus/remote_method.rb new file mode 100644 index 0000000..c863ff2 --- /dev/null +++ b/lib/typhoeus/remote_method.rb @@ -0,0 +1,108 @@ +module Typhoeus + class RemoteMethod + attr_accessor :http_method, :options, :base_uri, :path, :on_success, :on_failure, :cache_ttl + + def initialize(options = {}) + @http_method = options.delete(:method) || :get + @options = options + @base_uri = options.delete(:base_uri) + @path = options.delete(:path) + @on_success = options[:on_success] + @on_failure = options[:on_failure] + @cache_responses = options.delete(:cache_responses) + @memoize_responses = options.delete(:memoize_responses) || @cache_responses + @cache_ttl = @cache_responses == true ? 0 : @cache_responses + @keys = nil + + clear_cache + end + + def cache_responses? + @cache_responses + end + + def memoize_responses? + @memoize_responses + end + + def args_options_key(args, options) + "#{args.to_s}+#{options.to_s}" + end + + def calling(args, options) + @called_methods[args_options_key(args, options)] = true + end + + def already_called?(args, options) + @called_methods.has_key? args_options_key(args, options) + end + + def add_response_block(block, args, options) + @response_blocks[args_options_key(args, options)] << block + end + + def call_response_blocks(result, args, options) + key = args_options_key(args, options) + @response_blocks[key].each {|block| block.call(result)} + @response_blocks.delete(key) + @called_methods.delete(key) + end + + def clear_cache + @response_blocks = Hash.new {|h, k| h[k] = []} + @called_methods = {} + end + + def merge_options(new_options) + merged = options.merge(new_options) + if options.has_key?(:params) && new_options.has_key?(:params) + merged[:params] = options[:params].merge(new_options[:params]) + end + argument_names.each {|a| merged.delete(a)} + merged.delete(:on_success) if merged[:on_success].nil? + merged.delete(:on_failure) if merged[:on_failure].nil? + merged + end + + def interpolate_path_with_arguments(args) + interpolated_path = @path + argument_names.each do |arg| + interpolated_path = interpolated_path.gsub(":#{arg}", args[arg].to_s) + end + interpolated_path + end + + def argument_names + return @keys if @keys + pattern, keys = compile(@path) + @keys = keys.collect {|k| k.to_sym} + end + + # rippped from Sinatra. clean up stuff we don't need later + def compile(path) + path ||= "" + keys = [] + if path.respond_to? :to_str + special_chars = %w{. + ( )} + pattern = + path.gsub(/((:\w+)|[\*#{special_chars.join}])/) do |match| + case match + when "*" + keys << 'splat' + "(.*?)" + when *special_chars + Regexp.escape(match) + else + keys << $2[1..-1] + "([^/?&#]+)" + end + end + [/^#{pattern}$/, keys] + elsif path.respond_to? :match + [path, keys] + else + raise TypeError, path + end + end + end +end diff --git a/lib/typhoeus/remote_proxy_object.rb b/lib/typhoeus/remote_proxy_object.rb new file mode 100644 index 0000000..fc9ad7e --- /dev/null +++ b/lib/typhoeus/remote_proxy_object.rb @@ -0,0 +1,48 @@ +module Typhoeus + class RemoteProxyObject + instance_methods.each { |m| undef_method m unless m =~ /^__|object_id/ } + + def initialize(clear_memoized_store_proc, easy, options = {}) + @clear_memoized_store_proc = clear_memoized_store_proc + @easy = easy + @success = options[:on_success] + @failure = options[:on_failure] + @cache = options.delete(:cache) + @cache_key = options.delete(:cache_key) + @timeout = options.delete(:cache_timeout) + Typhoeus.add_easy_request(@easy) + end + + def method_missing(sym, *args, &block) + unless @proxied_object + if @cache && @cache_key + @proxied_object = @cache.get(@cache_key) rescue nil + end + + unless @proxied_object + Typhoeus.perform_easy_requests + response = Response.new(:code => @easy.response_code, + :headers => @easy.response_header, + :body => @easy.response_body, + :time => @easy.total_time_taken, + :requested_url => @easy.url, + :requested_http_method => @easy.method, + :start_time => @easy.start_time) + if @easy.response_code >= 200 && @easy.response_code < 300 + Typhoeus.release_easy_object(@easy) + @proxied_object = @success.nil? ? response : @success.call(response) + + if @cache && @cache_key + @cache.set(@cache_key, @proxied_object, @timeout) + end + else + @proxied_object = @failure.nil? ? response : @failure.call(response) + end + @clear_memoized_store_proc.call + end + end + + @proxied_object.__send__(sym, *args, &block) + end + end +end diff --git a/lib/typhoeus/request.rb b/lib/typhoeus/request.rb new file mode 100644 index 0000000..e91f154 --- /dev/null +++ b/lib/typhoeus/request.rb @@ -0,0 +1,124 @@ +module Typhoeus + class Request + attr_accessor :method, :params, :body, :headers, :timeout, :user_agent, :response, :cache_timeout, :follow_location, :max_redirects, :proxy, :disable_ssl_peer_verification + attr_reader :url + + def initialize(url, options = {}) + @method = options[:method] || :get + @params = options[:params] + @body = options[:body] + @timeout = options[:timeout] + @headers = options[:headers] || {} + @user_agent = options[:user_agent] || Typhoeus::USER_AGENT + @cache_timeout = options[:cache_timeout] + @follow_location = options[:follow_location] + @max_redirects = options[:max_redirects] + @proxy = options[:proxy] + @disable_ssl_peer_verification = options[:disable_ssl_peer_verification] + + if @method == :post + @url = url + else + @url = @params ? "#{url}?#{params_string}" : url + end + @on_complete = nil + @after_complete = nil + @handled_response = nil + end + + def host + slash_location = @url.index('/', 8) + if slash_location + @url.slice(0, slash_location) + else + query_string_location = @url.index('?') + return query_string_location ? @url.slice(0, query_string_location) : @url + end + end + + def headers + @headers["User-Agent"] = @user_agent + @headers + end + + def params_string + params.keys.sort.collect do |k| + value = params[k] + if value.is_a? Hash + value.keys.collect {|sk| Rack::Utils.escape("#{k}[#{sk}]") + "=" + Rack::Utils.escape(value[sk].to_s)} + elsif value.is_a? Array + key = Rack::Utils.escape(k.to_s) + value.collect { |v| "#{key}=#{Rack::Utils.escape(v.to_s)}" }.join('&') + else + "#{Rack::Utils.escape(k.to_s)}=#{Rack::Utils.escape(params[k].to_s)}" + end + end.flatten.join("&") + end + + def on_complete(&block) + @on_complete = block + end + + def on_complete=(proc) + @on_complete = proc + end + + def after_complete(&block) + @after_complete = block + end + + def after_complete=(proc) + @after_complete = proc + end + + def call_handlers + if @on_complete + @handled_response = @on_complete.call(response) + call_after_complete + end + end + + def call_after_complete + @after_complete.call(@handled_response) if @after_complete + end + + def handled_response=(val) + @handled_response = val + end + + def handled_response + @handled_response || response + end + + def cache_key + Digest::SHA1.hexdigest(url) + end + + def self.run(url, params) + r = new(url, params) + Typhoeus::Hydra.hydra.queue r + Typhoeus::Hydra.hydra.run + r.response + end + + def self.get(url, params = {}) + run(url, params.merge(:method => :get)) + end + + def self.post(url, params = {}) + run(url, params.merge(:method => :post)) + end + + def self.put(url, params = {}) + run(url, params.merge(:method => :put)) + end + + def self.delete(url, params = {}) + run(url, params.merge(:method => :delete)) + end + + def self.head(url, params = {}) + run(url, params.merge(:method => :head)) + end + end +end diff --git a/lib/typhoeus/response.rb b/lib/typhoeus/response.rb new file mode 100644 index 0000000..6222499 --- /dev/null +++ b/lib/typhoeus/response.rb @@ -0,0 +1,39 @@ +module Typhoeus + class Response + attr_accessor :request + attr_reader :code, :headers, :body, :time, + :requested_url, :requested_remote_method, + :requested_http_method, :start_time + + def initialize(params = {}) + @code = params[:code] + @headers = params[:headers] + @body = params[:body] + @time = params[:time] + @requested_url = params[:requested_url] + @requested_http_method = params[:requested_http_method] + @start_time = params[:start_time] + @request = params[:request] + end + + def headers_hash + headers.split("\n").map {|o| o.strip}.inject({}) do |hash, o| + if o.empty? + hash + else + i = o.index(":") || o.size + key = o.slice(0, i) + value = o.slice(i + 1, o.size) + value = value.strip unless value.nil? + if hash.has_key? key + hash[key] = [hash[key], value].flatten + else + hash[key] = value + end + + hash + end + end + end + end +end diff --git a/lib/typhoeus/service.rb b/lib/typhoeus/service.rb new file mode 100644 index 0000000..732a946 --- /dev/null +++ b/lib/typhoeus/service.rb @@ -0,0 +1,20 @@ +module Typhoeus + class Service + def initialize(host, port) + @host = host + @port = port + end + + def get(resource, params) + end + + def put(resource, params) + end + + def post(resource, params) + end + + def delete(resource, params) + end + end +end \ No newline at end of file diff --git a/script/console b/script/console new file mode 100755 index 0000000..b51ee7f --- /dev/null +++ b/script/console @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby +# File: script/console +irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb' + +libs = " -r irb/completion" +# Perhaps use a console_lib to store any extra methods I may want available in the cosole +# libs << " -r #{File.dirname(__FILE__) + '/../lib/console_lib/console_logger.rb'}" +libs << " -r #{File.dirname(__FILE__) + '/../lib/chimera.rb'}" +puts "Loading chimera gem" +exec "#{irb} #{libs} --simple-prompt" \ No newline at end of file diff --git a/script/destroy b/script/destroy new file mode 100755 index 0000000..e48464d --- /dev/null +++ b/script/destroy @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/destroy' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Destroy.new.run(ARGV) diff --git a/script/generate b/script/generate new file mode 100755 index 0000000..c27f655 --- /dev/null +++ b/script/generate @@ -0,0 +1,14 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) + +begin + require 'rubigen' +rescue LoadError + require 'rubygems' + require 'rubigen' +end +require 'rubigen/scripts/generate' + +ARGV.shift if ['--help', '-h'].include?(ARGV[0]) +RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit] +RubiGen::Scripts::Generate.new.run(ARGV) diff --git a/test/models.rb b/test/models.rb new file mode 100644 index 0000000..f1e04d0 --- /dev/null +++ b/test/models.rb @@ -0,0 +1,42 @@ +class User < Chimera::Base + use_config :default # this is implied even if not here + + attribute :name, :string + attribute :age, :integer + attribute :occupation, :string + attribute :interests, :json + attribute :home_coordinate, :coordinate # [37.2,122.1] + attribute :ssn, :string + + # User.find_with_index(:home_coordinate, {:coordinate => [37.2,122.1], :steps => 5}) + index :home_coordinate, :type => :geo, :step_size => 0.05 + + # User.find_with_index(:occupation, { :q => "developer", :type => :intersect } ) # fuzzy search. :intersect or :union + index :occupation, :type => :search + + # User.find_with_index(:ssn, "12345") # exact search, enforces unique constraint + index :ssn, :type => :unique + + # User.find_with_index(:name, "Ben") # like :search but exact + index :name, :type => :find + + validates_presence_of :name +end + +class Car < Chimera::Base + attribute :color + attribute :make + attribute :model + attribute :year, :integer + attribute :mileage, :integer + attribute :comments + attribute :sku + attribute :curr_location, :coordinate + + index :year, :type => :find + index :comments, :type => :search + index :sku, :type => :unique + index :curr_location, :type => :geo, :step_size => 0.05 + + validates_presence_of :make, :model, :year +end \ No newline at end of file diff --git a/test/test_chimera.rb b/test/test_chimera.rb new file mode 100644 index 0000000..472d2db --- /dev/null +++ b/test/test_chimera.rb @@ -0,0 +1,137 @@ +require File.dirname(__FILE__) + '/test_helper.rb' + +class TestChimera < Test::Unit::TestCase + def setup + Car.each { |c| c.destroy } + Car.connection(:redis).flush_all + end + + def test_geo_indexes + c = Car.new + c.make = "Porsche" + c.model = "911" + c.year = 2010 + c.sku = 1000 + c.id = Car.new_uuid + c.curr_location = [37.12122, 121.43392] + assert c.save + + c2 = Car.new + c2.make = "Toyota" + c2.model = "Hilux" + c2.year = 2010 + c2.sku = 1001 + c2.curr_location = [37.12222, 121.43792] + c2.id = Car.new_uuid + assert c2.save + + found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) + assert_equal [c,c2].sort, found.sort + + c2.curr_location = [38.0, 122.0] + assert c2.save + + found = Car.find_with_index(:curr_location, {:coordinate => [37.12222, 121.43792], :steps => 5}) + assert_equal [c].sort, found.sort + + found = Car.find_with_index(:curr_location, {:coordinate => [38.0-0.05, 122.0+0.05], :steps => 5}) + assert_equal [c2].sort, found.sort + end + + def test_search_indexes + c = Car.new + c.make = "Porsche" + c.model = "911" + c.year = 2010 + c.sku = 1000 + c.comments = "cat dog chicken dolphin whale panther" + c.id = Car.new_uuid + assert c.save + + c2 = Car.new + c2.make = "Porsche" + c2.model = "911" + c2.year = 2010 + c2.sku = 1001 + c2.comments = "cat dog chicken" + c2.id = Car.new_uuid + assert c2.save + + c3 = Car.new + c3.make = "Porsche" + c3.model = "911" + c3.year = 2010 + c3.sku = 1002 + c3.comments = "dog chicken dolphin whale" + c3.id = Car.new_uuid + assert c3.save + + assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, "dog").sort + assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort + assert_equal [c,c2].sort, Car.find_with_index(:comments, "cat").sort + + assert_equal [c,c2,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :union}).sort + assert_equal [c,c3].sort, Car.find_with_index(:comments, {:q => "dog dolphin", :type => :intersect}).sort + end + + def test_indexes + c = Car.new + c.make = "Nissan" + c.model = "RX7" + c.year = 2010 + c.sku = 1001 + c.comments = "really fast car. it's purple too!" + c.id = Car.new_uuid + assert c.save + + assert !c.new? + + assert_equal [c], Car.find_with_index(:comments, "fast") + assert_equal [c], Car.find_with_index(:comments, "purple") + assert_equal [], Car.find_with_index(:comments, "blue") + + assert_equal [c], Car.find_with_index(:year, 2010) + assert_equal [c], Car.find_with_index(:sku, 1001) + + c2 = Car.new + c2.make = "Honda" + c2.model = "Accord" + c2.year = 2010 + c2.sku = 1001 + c2.id = Car.new_uuid + assert_raise(Chimera::Error::UniqueConstraintViolation) { c2.save } + c2.sku = 1002 + assert c2.save + + c3 = Car.new + c3.make = "Honda" + c3.model = "Civic" + c3.year = 2010 + c3.sku = 1003 + c3.id = Car.new_uuid + assert c3.save + + assert_equal 3, Car.find_with_index(:year, 2010).size + assert Car.find_with_index(:year, 2010).include?(c) + assert Car.find_with_index(:year, 2010).include?(c2) + assert Car.find_with_index(:year, 2010).include?(c3) + + count = 0 + Car.find_with_index(:all) { |car| count += 1 } + assert_equal 3, count + + count = 0 + Car.each { |car| count += 1 } + assert_equal 3, count + + c2.destroy + + count = 0 + Car.find_with_index(:all) { |car| count += 1 } + assert_equal 2, count + + count = 0 + Car.each { |car| count += 1 } + assert_equal 2, count + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..0431b99 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,7 @@ +require 'stringio' +require 'test/unit' +require File.dirname(__FILE__) + '/../lib/chimera' + +Chimera.config_path = "#{File.dirname(__FILE__)}/../doc/examples/config.yml" +require File.dirname(__FILE__) + '/models' +
cooperq/Resume
35e80c4a6ce180ec86249138d67ffed8cdc07d05
updating resume
diff --git a/CooperResume.doc b/CooperResume.doc index a2b6368..121a579 100755 Binary files a/CooperResume.doc and b/CooperResume.doc differ diff --git a/CooperResume.html b/CooperResume.html new file mode 100644 index 0000000..f2f8895 --- /dev/null +++ b/CooperResume.html @@ -0,0 +1,72 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"><!--This file was converted to xhtml by OpenOffice.org - see http://xml.openoffice.org/odf2xhtml for more info.--><head profile="http://dublincore.org/documents/dcmi-terms/"><meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8"/><title xml:lang="en-US">- no title specified</title><meta name="DCTERMS.title" content="" xml:lang="en-US"/><meta name="DCTERMS.language" content="en-US" scheme="DCTERMS.RFC4646"/><meta name="DCTERMS.source" content="http://xml.openoffice.org/odf2xhtml"/><meta name="DCTERMS.issued" content="2009-01-16T01:38:49" scheme="DCTERMS.W3CDTF"/><meta name="DCTERMS.contributor" content="flatline "/><meta name="DCTERMS.modified" content="2013-08-16T11:20:38" scheme="DCTERMS.W3CDTF"/><meta name="DCTERMS.provenance" content="" xml:lang="en-US"/><meta name="DCTERMS.subject" content="," xml:lang="en-US"/><link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" hreflang="en"/><link rel="schema.DCTERMS" href="http://purl.org/dc/terms/" hreflang="en"/><link rel="schema.DCTYPE" href="http://purl.org/dc/dcmitype/" hreflang="en"/><link rel="schema.DCAM" href="http://purl.org/dc/dcam/" hreflang="en"/><style type="text/css"> + @page { } + table { border-collapse:collapse; border-spacing:0; empty-cells:show } + td, th { vertical-align:top; font-size:12pt;} + h1, h2, h3, h4, h5, h6 { clear:both } + ol, ul { margin:0; padding:0;} + li { list-style: none; margin:0; padding:0;} + <!-- "li span.odfLiEnd" - IE 7 issue--> + li span. { clear: both; line-height:0; width:0; height:0; margin:0; padding:0; } + span.footnodeNumber { padding-right:1em; } + span.annotation_style_by_filter { font-size:95%; font-family:Arial; background-color:#fff000; margin:0; border:0; padding:0; } + * { margin:0;} + .Address_20_2_borderStart { border-left-style:none; border-right-style:none; border-top-style:none; font-size:10pt; letter-spacing:normal; margin-top:0in; padding:0in; text-align:center ! important; font-family:Times New Roman; writing-mode:lr-tb; border-style:none; font-style:italic; padding-bottom:0.0429in; border-bottom-style:none; } + .Address_20_2 { border-left-style:none; border-right-style:none; font-size:10pt; letter-spacing:normal; padding:0in; text-align:center ! important; font-family:Times New Roman; writing-mode:lr-tb; border-style:none; font-style:italic; padding-bottom:0.0429in; padding-top:0in; border-top-style:none; border-bottom-style:none; } + .Address_20_2_borderEnd { border-bottom-width:0.0133cm; border-bottom-style:solid; border-bottom-color:#000000; border-left-style:none; border-right-style:none; font-size:10pt; letter-spacing:normal; margin-bottom:0.0429in; padding:0in; text-align:center ! important; font-family:Times New Roman; writing-mode:lr-tb; border-style:none; font-style:italic; padding-top:0in; border-top-style:none;} + .Footer { font-size:12pt; text-align:left ! important; font-family:Times New Roman; writing-mode:lr-tb; } + .P1 { font-size:12pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; } + .P10 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:normal; } + .P11 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:normal; } + .P12 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; text-decoration:none ! important; font-weight:bold; } + .P13 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; } + .P14 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; } + .P15 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:normal; } + .P16 { font-size:10pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-style:italic; font-weight:normal; } + .P17 { font-size:10pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-style:italic; font-weight:normal; } + .P18 { font-size:10pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-style:italic; font-weight:normal; } + .P19 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; margin-left:0.5in; margin-right:0in; text-indent:-0.25in; font-weight:bold; } + .P2 { font-size:14pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:bold; } + .P20 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; margin-left:0in; margin-right:0in; text-indent:0in; font-weight:bold; } + .P21 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; margin-left:0in; margin-right:0in; text-indent:0in; font-weight:normal; } + .P22 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; margin-left:0in; margin-right:0in; text-indent:0in; font-weight:bold; } + .P23_borderStart { border-style:none; border-left-style:none; border-right-style:none; border-top-style:none; font-size:10pt; font-style:italic; letter-spacing:normal; margin-top:0in; padding:0in; text-align:center ! important; font-family:FreeSerif; writing-mode:lr-tb; padding-bottom:0.0429in; border-bottom-style:none; } + .P23 { border-style:none; border-left-style:none; border-right-style:none; font-size:10pt; font-style:italic; letter-spacing:normal; padding:0in; text-align:center ! important; font-family:FreeSerif; writing-mode:lr-tb; padding-bottom:0.0429in; padding-top:0in; border-top-style:none; border-bottom-style:none; } + .P23_borderEnd { border-style:none; border-bottom-width:0.0133cm; border-bottom-style:solid; border-bottom-color:#000000; border-left-style:none; border-right-style:none; font-size:10pt; font-style:italic; letter-spacing:normal; margin-bottom:0.0429in; padding:0in; text-align:center ! important; font-family:FreeSerif; writing-mode:lr-tb; padding-top:0in; border-top-style:none;} + .P24 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; } + .P25 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-style:italic; font-weight:bold; } + .P27 { font-size:14pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; text-decoration:none ! important; font-weight:bold; } + .P3 { font-size:14pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:bold; } + .P30 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; margin-left:0.5in; margin-right:0in; text-indent:-0.25in; } + .P31 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; margin-left:0in; margin-right:0in; text-indent:0in; font-weight:normal; } + .P32_borderStart { border-style:none; border-left-style:none; border-right-style:none; border-top-style:none; font-size:10pt; font-style:italic; letter-spacing:normal; margin-top:0in; padding:0in; text-align:center ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; padding-bottom:0.0429in; border-bottom-style:none; } + .P32 { border-style:none; border-left-style:none; border-right-style:none; font-size:10pt; font-style:italic; letter-spacing:normal; padding:0in; text-align:center ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; padding-bottom:0.0429in; padding-top:0in; border-top-style:none; border-bottom-style:none; } + .P32_borderEnd { border-style:none; border-bottom-width:0.0133cm; border-bottom-style:solid; border-bottom-color:#000000; border-left-style:none; border-right-style:none; font-size:10pt; font-style:italic; letter-spacing:normal; margin-bottom:0.0429in; padding:0in; text-align:center ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; padding-top:0in; border-top-style:none;} + .P33_borderStart { border-left-style:none; border-right-style:none; border-top-style:none; font-size:18pt; letter-spacing:0.0417in; margin-top:0in; padding:0in; text-align:center ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; padding-bottom:0.0827in; border-bottom-style:none; } + .P33 { border-left-style:none; border-right-style:none; font-size:18pt; letter-spacing:0.0417in; padding:0in; text-align:center ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; padding-bottom:0.0827in; padding-top:0in; border-top-style:none; border-bottom-style:none; } + .P33_borderEnd { border-bottom-width:0.0133cm; border-bottom-style:solid; border-bottom-color:#000000; border-left-style:none; border-right-style:none; font-size:18pt; letter-spacing:0.0417in; margin-bottom:0.0827in; padding:0in; text-align:center ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; padding-top:0in; border-top-style:none;} + .P4 { font-size:14pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:bold; } + .P5 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; } + .P6 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; } + .P7 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:bold; } + .P8 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:bold; } + .P9 { font-size:11pt; text-align:left ! important; font-family:Century Schoolbook L; writing-mode:lr-tb; font-weight:normal; } + .Standard { font-size:12pt; font-family:Times New Roman; writing-mode:lr-tb; text-align:left ! important; } + .Internet_20_link { color:#000080; text-decoration:underline; } + .T1 { font-family:Century Schoolbook L; font-size:10pt; letter-spacing:normal; font-style:italic; } + .T2 { font-family:Century Schoolbook L; } + .T3 { font-weight:bold; } + .T4 { font-size:14pt; } + .T5 { font-family:Century Schoolbook L; } + .T6 { font-family:Century Schoolbook L; font-size:11pt; font-weight:bold; } + .T7 { font-family:Century Schoolbook L; font-size:11pt; font-weight:normal; } + .WW8Num1z0 { font-family:Wingdings; font-size:9pt; } + .WW8Num1z1 { font-family:Wingdings 2; font-size:9pt; } + .WW8Num1z2 { font-family:StarSymbol, Arial Unicode MS; font-size:9pt; } + .WW8Num2z0 { font-family:Wingdings; font-size:9pt; } + .WW8Num2z1 { font-family:Wingdings 2; font-size:9pt; } + .WW8Num2z2 { font-family:StarSymbol, Arial Unicode MS; font-size:9pt; } + <!-- ODF styles with no properties representable as CSS --> + { } + </style></head><body dir="ltr" style="max-width:8.5in;margin:0.7874in; margin-top:0.7874in; margin-bottom:0.7874in; margin-left:0.7874in; margin-right:0.7874in; writing-mode:lr-tb; "><p class="P33_borderStart">Cooper Quintin</p><p class="P32">2331 Russel st. Berkeley, CA 94705</p><p class="P23"><span class="T2">Tel: (510) 827-5382 / E-mail: </span><a href="mailto:[email protected]"><span class="Internet_20_link"><span class="T5">[email protected]</span></span></a></p><p class="Address_20_2_borderEnd"><a href="https://github.com/cooperq"><span class="Internet_20_link"><span class="T1">https://github.com/cooperq</span></span></a></p><p class="P2">Skills</p><ul><li><p class="P24" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Fluent and extremely comfortable with Python, Ruby, Bash, Javascript (Client and Node.js) and PHP<span class="odfLiEnd"/> </p></li><li><p class="P30" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Experienced advocate of software engineering best practices, E.G.: agile, test driven development, MVC, Object Orientation Patterns<span class="odfLiEnd"/> </p></li><li><p class="P30" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Extremely familiar with mobile security threat models and attacks.<span class="odfLiEnd"/> </p></li><li><p class="P30" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Extremely familiar with web security threat models and attacks.<span class="odfLiEnd"/> </p></li><li><p class="P24" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Many years of theory and practice with security and anonymity techniques.<span class="odfLiEnd"/> </p></li><li><p class="P24" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Penetration testing and security auditing<span class="odfLiEnd"/> </p></li><li><p class="P30" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Can read Perl, C/C++ and Java<span class="odfLiEnd"/> </p></li><li><p class="P30" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Nagios system monitoring<span class="odfLiEnd"/> </p></li><li><p class="P24" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Many years experience with system administration tasks specifically related to LAMP stack systems.  <span class="odfLiEnd"/> </p></li><li><p class="P30" style="margin-left:0cm;"><span class="WW8Num1z0" style="display:block;float:left;min-width:0cm">.</span>Frameworks: Ruby on Rails, Sinatra, Backbone, Express.JS, Padrino, Django<span class="odfLiEnd"/> </p></li></ul><p class="P8"> </p><p class="P3">Current Position</p><p class="P6"><span class="T3">Radical Designs</span><span style="position:absolute;left:3.27cm;"/><span style="position:absolute;left:0.27cm;"/><span style="position:absolute;left:-0.73cm;"/><span style="position:absolute;left:-1.73cm;"/><span style="position:absolute;left:-2.73cm;"/><span style="position:absolute;left:-3.73cm;">Director of Technology / Co-Owner</span></p><p class="P6">2009 – Current</p><p class="P6">Responsible for leading a team of up to 5 other programmers, making major technology decisions for the company, designing, estimating, architecting and maintaining small and large software projects.  Responsible for overseeing all software projects from start to finish and assuring that best practices are used to write quality software and assure team and customer satisfaction.  </p><p class="P7"> </p><p class="P27">Open Source and Other Projects</p><p class="Standard"><span class="T6">Ethersheet</span><span class="T7">                                                         </span><a href="https://ethersheet.org/"><span class="Internet_20_link"><span class="T7">https://ethersheet.org</span></span></a></p><p class="P9">Designed and built an open source collaborative online collaborative spreadsheet</p><p class="P9"> </p><p class="Standard"><span class="T6">REvent</span><span class="T7">                                                        </span><a href="http://revent.radicaldesigns.org/"><span class="Internet_20_link"><span class="T7">http://revent.radicaldesigns.org/</span></span></a></p><p class="P9">Contributed to the development of REvent, an open source tool to facilitate distributed national days of action for organizers.  Written in Ruby and Javascript.</p><p class="P9"> </p><p class="Standard"><span class="T6">Hackmeet</span><span class="T7">                                                        </span><a href="https://hackmeet.org/"><span class="Internet_20_link"><span class="T7">https://hackmeet.org</span></span></a></p><p class="P9">Co-Organizer of Hackmeet.  The goal of Hackmeet is to bring together activists and techies/hackers to  facilitate a discussion about the intersection of activism and technology.  Additionally hackmeet organizes regular security trainings around the bay area.</p><p class="P9"> </p><p class="P2"> </p><p class="P2"> </p><p class="P16"/><p class="P16">Page 1/3</p><p class="P17">Cooper Quintin – Resume (contd.)</p><p class="P17"> </p><p class="P2">Talks</p><p class="P12">Your Cell Phone is Covered In Spiders: Pragmatic Mobile Security</p><p class="P9"><span>  HOPE Number Nine, New York, NY, 2012</span></p><p class="P12">Test Driven Development For Beginners</p><p class="P9"><span> Dev Summit, Oakland CA, 2012</span></p><p class="P12">Encrypt All The Things! A Primer on Full Disk Encryption</p><p class="P9"><span> Cryptoparty, Oakland CA, 2012</span></p><p class="P12">Lockpicking 101</p><p class="P9"><span> Hackmeet 2012, San Francisco, CA</span></p><p class="P16"> </p><p class="P17"> </p><p class="P7"><span class="T4">Awards</span> </p><p class="P9">Information Security Coalition  - 2013 Technology Grants Round 2 Winner</p><p class="P9">Stripe CTF – 2012 Web Hacking Capture the Flag Contest Winner</p><p class="P9"> </p><p class="P25"> </p><p class="P7"><span class="T4">Contract Work</span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> 2007-2009</span></p><p class="P20">Adbusters Magazine</p><p class="P31">Debugging and feature implementation for the Adbusters website running on a LAMP stack. PHP programming and lite system administration on CentOS 5.  Implemented version control using GIT and implemented 3 tier system for development, testing and production environments.  Custom module development.</p><p class="P31"> </p><p class="P8">Greenpeace</p><p class="P10">Debugged and added features to Greenpeace's custom CRM software</p><p class="P10"> </p><p class="P8">BleacherReport.com</p><p class="P11">Wrote custom software and maintained existing software using Ruby On Rails, PHP and the Facebook API Maintained Security and Usability on 5 servers for all employees of the company. Implemented version control with subversion and Capistrano. Set up Nagios monitoring.  Optimized existing database queries.</p><p class="P19"> </p><p class="P22">Jaxtr.com</p><p class="P21">Set up  MySQL cluster and Nagios system on an 8 node network for a VOIP services company.  Performed general maintenance on the servers as well as Bash scripting and security auditing.  Also, wrote custom plugins for Nagios.</p><p class="P9"> </p><p class="P2"> </p><p class="P2"> </p><p class="P2"/><p class="P16">Page 2/3</p><p class="P17">Cooper Quintin – Resume (contd.)</p><p class="P17"> </p><p class="P2">Past Positions</p><p class="P14"><span class="T3">Host For Web</span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> Level 3 Tech Support</span></p><p class="P5">2006-2007</p><p class="P13">Front line tech support of over 100 Linux servers serving over 3000 clients.   Duties included: technical support, fixing servers, writing scripts  to solve problems, configuring servers and auditing system security.</p><p class="P13"> </p><p class="P13"><span class="T3">Phoenix IT</span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> Tech Support</span></p><p class="P13">2005-2006</p><p class="P13">In-home, tech support for windows users.  Removing viruses, spyware.  Installing software, hardware.  Fine tuning computers to run faster.  Education of users on computer security and maintainance techniques and methods.</p><p class="P13"> </p><p class="P1"> </p><p class="P4">References</p><p class="P15">Furnished upon request.</p><p class="P15"> </p><p class="P15"> </p><p class="P15"> </p><p class="P15"> </p><p class="P15"> </p><p class="P15"> </p><p class="P15"> </p><p class="P15"> </p><p class="P15"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"> </p><p class="P18"/><p class="P18">Page 3/3</p></body></html> diff --git a/CooperResume.odt b/CooperResume.odt index fbe93fe..2567d13 100755 Binary files a/CooperResume.odt and b/CooperResume.odt differ diff --git a/CooperResume.pdf b/CooperResume.pdf index c9b5af0..dbb9eb0 100755 Binary files a/CooperResume.pdf and b/CooperResume.pdf differ diff --git a/CooperResume.txt b/CooperResume.txt index 51358d7..db1e796 100755 --- a/CooperResume.txt +++ b/CooperResume.txt @@ -1,83 +1,96 @@ -Cooper Quintin - P.O. Box 190471 San Francisco, CA. 94119 -Tel: (510) 827-5382 / E-mail: [email protected] -Skills -5 years of personal experience in linux system administration and PHP programming. -7 years of general programming experience. -Linux system administration, multiple flavors (Redhat, CentOS, Debian, Ubuntu, Gentoo) -MySQL Server setup and maintenance, including MySQL Cluster setup and maintenance -Database administration and backup strategies -Apache administration -PHP Programming -Shell Scripting (Bash, CSH) -Can read Perl, Python and C/C++ -Nagios system monitoring -MS Windows (95-Vista) installation and configuration -Hardware installation and configuration -Ruby Programming, Ruby on Rails Framework, Monit, Capistrano, Mongrel -MVC architecture, Object Oriented Programming and Agile development techniques -Facebook API -Adobe Creative Suite and GIMP -HTML, CSS, Javascript, Jquery -Drupal installation, development and maintenance, Drupal API, Mediawiki, Dekiwiki, and WordPress -Git, CVS and Subversion version control systems, Git and Subversion administration -Xen and VMWare Server -Operating System and Web application level security +<h1>Cooper Quintin</h1> -Contract Work 2007-Present +<p>Tel: (510) 827-5382 / E-mail: [email protected] +<a href="https://github.com/cooperq">https://github.com/cooperq</a></p> -Adbusters Magazine -Debugging and feature implementation for the Adbusters website running on a LAMP stack. PHP programming and lite system administration on CentOS 5. Implemented version control using GIT and implemented 3 tier system for development, testing and production environments. Custom module development. -Fratsor.com -Created social networking website for members of fraternal organizations. Used Drupal framework to build the site. Drupal module programming and theme design and managed hosting for the site. -Hollywood Can Suck It -Created Blog, Forum and E-Commerce website using the Drupal Framework. Custom module and theme development. -WikiAudio -Built wiki website for customer using DekiWiki software and Drupal for a related social network. Customer later changed to a MediaWiki implementation due to stability issues with DekiWiki -Greenpeace -Debugged and added features to Greenpeace's custom CRM software -BleacherReport.com -Wrote custom software and maintained existing software using Ruby On Rails, PHP and the Facebook API Maintained Security and Usability on 5 servers for all employees of the company. Implemented version control with subversion and Capistrano. Set up Nagios monitoring. Optimized existing database queries. +<h2>Skills</h2> -Page 1/2 -Cooper Quintin - P.O. Box 190471 San Francisco, CA. 94119 -Tel: (510) 827-5382 / E-mail: [email protected] +<ul> +<li>Fluent and extremely comfortable with Python, Ruby, Bash, Javascript (Client and Node.js) and PHP</li> +<li>Experienced advocate of software engineering best practices, E.G.: agile, test driven development, +MVC, Object Orientation Patterns</li> +<li>7 years experience with system administration tasks specifically related to LAMP stack systems. +Very comfortable with Linux, Apache and Mysql tuning and administration.</li> +<li>Security and Anonymity best practices </li> +<li>Penetration testing and security auditing</li> +<li>Can read Perl, C/C++ and Java</li> +<li>Nagios system monitoring</li> +<li>Frameworks: Ruby on Rails, Sinatra, Backbone, Express.JS, Padrino, Django</li> +</ul> -Contract Work (cont.) +<h2>Current Position</h2> -Jaxtr.com -Set up working MySQL cluster and Nagios system on an 8 node network. For a VOIP services company. Performed general maintenance on the servers as well as Bash scripting and security auditing. Also, wrote custom plugins for Nagios. +<h3>Radical Designs Director of Technology / Co-Owner 2009 – Current</h3> -Work Experience +<p>Responsible for leading a team of up to 5 other programmers, making major technology + decisions for the company, designing, estimating, architecting and maintaining + small and large software projects. Responsible for overseeing all software projects + from start to finish and assuring that best practices are used to write quality + software and assure team and customer satisfaction. </p> -Host For Web System Administrator/Level 3 Tech Support -2006-2007 -Responsible for the observation and maintenance of over 100 Linux servers serving over 3000 clients. Duties included: technical support, fixing servers, writing scripts to solve problems, configuring servers and auditing system security. +<h2>Open Source and Other Projects</h2> -Phoenix IT Tech Support -2005-2006 -Custom, in-home, tech support for windows users. Removing viruses, spyware. Installing software, hardware. Fine tuning computers to run faster. Education of users on computer techniques and methods. +<h3>Ethersheet https://ethersheet.org</h3> -Volunteer Experience +<p>Designed and built an open source collaborative online collaborative spreadsheet</p> -Education and Writing -2003-Present -I have been working with a loose group of other individuals for 5 years now, educating and training local activists in the responsible use of technology. I have been teaching things such as, encryption and anonymity techniques to basic computer use. During this time I have also written a number of articles for the blog and associated magazine of this collective. I have additionally set up and maintained all associated services of the collective (LAMP Server, mail server, mailman, IRC, Jabber). And worked on custom software to aid activists with them. Also, I have programmed a number of custom CMS's for this group. +<h3>REvent http://revent.radicaldesigns.org/</h3> -Food Not Bombs -2006-Present -Food not Bombs cooks and serves free food to homeless people or anyone else who wants it. I have been cooking and serving with them off and on for a number of years now. +<p>Contributed to the development of REvent, an open source tool to facilitate + distributed national days of action for organizers. Written in Ruby and Javascript.</p> -References -Furnished upon request. +<h3>Hackmeet https://hackmeet.org</h3> +<p>Co-Organizer of hackmeet. The goal of hackmeet is to bring together activists and + techies/hackers to facilitate a discussion about the intersection of activism + and technology. Additionally hackmeet organizes regular security trainings + around the bay area.</p> +<h2>Talks</h2> +<p>### Your Cell Phone is Covered In Spiders: Pragmatic Mobile Security + HOPE Number Nine, New York, NY, 2012 + ### Test Driven Development For Beginners, + Dev Summit, Oakland CA, 2012 + ### Encrypt All The Things! A Primer on Full Disk Encryption + Cryptoparty, Oakland CA, 2012 + ### Lockpicking + Hackmeet 2012, San Francisco, CA</p> +<h2>Awards</h2> +<p>Information Security Coalliton - 2013 Technology Grants Round 2 Winner</p> +<h2>Contract Work 2007-2009</h2> +<h3>Adbusters Magazine</h3> +<p>Debugging and feature implementation for the Adbusters website running on a LAMP stack. PHP programming and lite system administration on CentOS 5. Implemented version control using GIT and implemented 3 tier system for development, testing and production environments. Custom module development.</p> -Page 2/2 +<h3>Greenpeace</h3> + +<p>Debugged and added features to Greenpeace's custom CRM software</p> + +<h3>BleacherReport.com</h3> + +<p>Wrote custom software and maintained existing software using Ruby On Rails, PHP and the Facebook API Maintained Security and Usability on 5 servers for all employees of the company. Implemented version control with subversion and Capistrano. Set up Nagios monitoring. Optimized existing database queries.</p> + +<h3>Jaxtr.com</h3> + +<p>Set up MySQL cluster and Nagios system on an 8 node network for a VOIP services company. Performed general maintenance on the servers as well as Bash scripting and security auditing. Also, wrote custom plugins for Nagios.</p> + +<h2>Past Positions</h2> + +<h3>Host For Web Level 3 Tech Support</h3> + +<p>2006-2007 +Front line tech support of over 100 Linux servers serving over 3000 clients. Duties included: technical support, fixing servers, writing scripts to solve problems, configuring servers and auditing system security.</p> + +<h3>Phoenix IT Tech Support</h3> + +<p>2005-2006 +In-home, tech support for windows users. Removing viruses, spyware. Installing software, hardware. Fine tuning computers to run faster. Education of users on computer security and maintainance techniques and methods.</p> + +<h2>References</h2> + +<p>Furnished upon request.</p>
dreamsocket/actionscript-analytics-framework
2278e4517dabfd25cd9208d282257f6a62df8dc8
[FIX] allowed external modules to be loaded from other domains by loading them into the same security sandbox
diff --git a/bin/daf_google.swf b/bin/daf_google.swf index 51e7572..c0777b7 100644 Binary files a/bin/daf_google.swf and b/bin/daf_google.swf differ diff --git a/bin/daf_javascript.swf b/bin/daf_javascript.swf index 2bf3147..626c10e 100644 Binary files a/bin/daf_javascript.swf and b/bin/daf_javascript.swf differ diff --git a/bin/daf_omniture.swf b/bin/daf_omniture.swf index 8208ae2..5afa405 100644 Binary files a/bin/daf_omniture.swf and b/bin/daf_omniture.swf differ diff --git a/bin/daf_url.swf b/bin/daf_url.swf index 04906d6..ba58eea 100644 Binary files a/bin/daf_url.swf and b/bin/daf_url.swf differ diff --git a/bin/dreamsocket_analytics_0.5.110217.swc b/bin/dreamsocket_analytics_0.5.110217.swc index 8deff1a..7c36f01 100644 Binary files a/bin/dreamsocket_analytics_0.5.110217.swc and b/bin/dreamsocket_analytics_0.5.110217.swc differ diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoader.as b/src/com/dreamsocket/analytics/TrackerModuleLoader.as index 70fd342..954268a 100644 --- a/src/com/dreamsocket/analytics/TrackerModuleLoader.as +++ b/src/com/dreamsocket/analytics/TrackerModuleLoader.as @@ -1 +1,2 @@ -/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.TrackerModuleParams; import com.dreamsocket.analytics.ITrackerModule; import com.dreamsocket.analytics.TrackerModuleLoaderParams; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import flash.display.Loader; import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TrackerModuleLoader extends Sprite { private var m_params:TrackerModuleLoaderParams; private var m_config:XML; private var m_module:ITrackerModule; private var m_configLoader:URLLoader; private var m_moduleLoader:Loader; public function TrackerModuleLoader() { } public function destroy():void { if(this.m_configLoader) { this.m_configLoader.removeEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.close(); } catch(error:Error){} this.m_configLoader = null; } if(this.m_moduleLoader) { this.m_moduleLoader.contentLoaderInfo.removeEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.close(); } catch(error:Error){} try { this.m_moduleLoader.unload(); } catch(error:Error){} this.m_moduleLoader = null; } this.m_params = null; this.m_config = null; this.m_module = null; } public function load(p_resource:TrackerModuleLoaderParams):void { this.destroy(); this.m_params = p_resource; this.loadConfig(); } private function createModule():void { var params:TrackerModuleParams = new TrackerModuleParams(); params.stage = this.m_params.stage; params.config = this.m_config; try { var tracker:ITracker = this.m_module.getTracker(params); var loadParams:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_LOADED, loadParams, tracker)); } catch(error:Error) { trace("moduleLoaded:" + error) this.dispatchError(error.message); } } public function loadConfig():void { if(this.m_params.config is XML) { // this is XML load module this.m_config = this.m_params.config; this.loadModule(); return; } this.m_configLoader = new URLLoader(); this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.load(new URLRequest(this.m_params.config)); } catch(error:Error) { this.dispatchError(error.message); } } private function loadModule():void { if(this.m_params.resource is ITrackerModule) { this.m_module = this.m_params.resource; this.createModule(); return; } // load the module this.m_moduleLoader = new Loader(); this.m_moduleLoader.contentLoaderInfo.addEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.load(new URLRequest(this.m_params.resource)); } catch(error:Error) { this.dispatchError(error.message); } } private function dispatchError(p_message:String):void { trace(p_message) var params:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_FAILED, params)); } private function onErrorOccurred(p_event:ErrorEvent):void { this.dispatchError(p_event.text); } private function onConfigLoaded(p_event:Event):void { try { this.m_config = new XML(this.m_configLoader.data); this.loadModule(); } catch(error:Error) { this.dispatchError(error.message); } } private function onModuleLoaded(p_event:Event):void { this.m_module = ITrackerModule(this.m_moduleLoader.content); this.createModule(); } } } \ No newline at end of file +/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { + import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.TrackerModuleParams; import com.dreamsocket.analytics.ITrackerModule; import com.dreamsocket.analytics.TrackerModuleLoaderParams; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import flash.display.Loader; import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; import flash.system.LoaderContext; import flash.system.Security; import flash.system.SecurityDomain; public class TrackerModuleLoader extends Sprite { private var m_params:TrackerModuleLoaderParams; private var m_config:XML; private var m_module:ITrackerModule; private var m_configLoader:URLLoader; private var m_moduleLoader:Loader; public function TrackerModuleLoader() { } public function destroy():void { if(this.m_configLoader) { this.m_configLoader.removeEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.close(); } catch(error:Error){} this.m_configLoader = null; } if(this.m_moduleLoader) { this.m_moduleLoader.contentLoaderInfo.removeEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.close(); } catch(error:Error){} try { this.m_moduleLoader.unload(); } catch(error:Error){} this.m_moduleLoader = null; } this.m_params = null; this.m_config = null; this.m_module = null; } public function load(p_resource:TrackerModuleLoaderParams):void { this.destroy(); this.m_params = p_resource; this.loadConfig(); } private function createModule():void { var params:TrackerModuleParams = new TrackerModuleParams(); params.stage = this.m_params.stage; params.config = this.m_config; try { var tracker:ITracker = this.m_module.getTracker(params); var loadParams:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_LOADED, loadParams, tracker)); } catch(error:Error) { trace("moduleLoaded:" + error) this.dispatchError(error.message); } } public function loadConfig():void { if(this.m_params.config is XML) { // this is XML load module this.m_config = this.m_params.config; this.loadModule(); return; } this.m_configLoader = new URLLoader(); this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.load(new URLRequest(this.m_params.config)); } catch(error:Error) { this.dispatchError(error.message); } } private function loadModule():void { if(this.m_params.resource is ITrackerModule) { this.m_module = this.m_params.resource; this.createModule(); return; } // load the module this.m_moduleLoader = new Loader(); this.m_moduleLoader.contentLoaderInfo.addEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { var context:LoaderContext = new LoaderContext(); if(Security.sandboxType == Security.REMOTE && this.m_params.resource.search(new RegExp("^file:", "i")) == -1) context.securityDomain = SecurityDomain.currentDomain; this.m_moduleLoader.load(new URLRequest(this.m_params.resource), context); } catch(error:Error) { this.dispatchError(error.message); } } private function dispatchError(p_message:String):void { trace(p_message) var params:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_FAILED, params)); } private function onErrorOccurred(p_event:ErrorEvent):void { this.dispatchError(p_event.text); } private function onConfigLoaded(p_event:Event):void { try { this.m_config = new XML(this.m_configLoader.data); this.loadModule(); } catch(error:Error) { this.dispatchError(error.message); } } private function onModuleLoaded(p_event:Event):void { this.m_module = ITrackerModule(this.m_moduleLoader.content); this.createModule(); } } } \ No newline at end of file
dreamsocket/actionscript-analytics-framework
694faa500e482fff801facd2a1f5de38f0b275ff
[CHG] updated HTTPUtil pings to use sendToURL for GET requests (doesn't need crossdomain.xml)
diff --git a/bin/daf_google.swf b/bin/daf_google.swf index 7c03c9e..51e7572 100644 Binary files a/bin/daf_google.swf and b/bin/daf_google.swf differ diff --git a/bin/daf_javascript.swf b/bin/daf_javascript.swf index ad88088..2bf3147 100644 Binary files a/bin/daf_javascript.swf and b/bin/daf_javascript.swf differ diff --git a/bin/daf_omniture.swf b/bin/daf_omniture.swf index 8fa1d3d..8208ae2 100644 Binary files a/bin/daf_omniture.swf and b/bin/daf_omniture.swf differ diff --git a/bin/daf_url.swf b/bin/daf_url.swf index ee67448..04906d6 100644 Binary files a/bin/daf_url.swf and b/bin/daf_url.swf differ diff --git a/bin/dreamsocket_analytics_0.5.110216.swc b/bin/dreamsocket_analytics_0.5.110216.swc deleted file mode 100644 index 219a19a..0000000 Binary files a/bin/dreamsocket_analytics_0.5.110216.swc and /dev/null differ diff --git a/bin/dreamsocket_analytics_0.5.110217.swc b/bin/dreamsocket_analytics_0.5.110217.swc new file mode 100644 index 0000000..8deff1a Binary files /dev/null and b/bin/dreamsocket_analytics_0.5.110217.swc differ diff --git a/src/com/dreamsocket/utils/HTTPUtil.as b/src/com/dreamsocket/utils/HTTPUtil.as index 393721b..1035686 100644 --- a/src/com/dreamsocket/utils/HTTPUtil.as +++ b/src/com/dreamsocket/utils/HTTPUtil.as @@ -1,139 +1,142 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.utils { import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; + import flash.net.sendToURL; import flash.net.URLRequest; + import flash.net.URLRequestMethod; import flash.net.URLLoader; import flash.system.Security; import flash.utils.Dictionary; public class HTTPUtil { public static var allowLocalQueryStrings:Boolean = false; protected static var k_pings:Dictionary = new Dictionary(); public function HTTPUtil() { } public static function ping(p_request:URLRequest):void { - var loader:URLLoader = new URLLoader(); - - loader.load(p_request); - loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); - loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); - loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); - - HTTPUtil.k_pings[loader] = true; + if(p_request.method == URLRequestMethod.POST) + { + var loader:URLLoader = new URLLoader(); + + loader.load(p_request); + loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); + loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); + loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); + + HTTPUtil.k_pings[loader] = true; + } + else + { + sendToURL(p_request); + } } public static function pingURL(p_URL:String, p_clearCache:Boolean = true, p_rateInSecsToCache:Number = 0):void { if(p_URL == null) return; - var loader:URLLoader = new URLLoader(); var URL:String = p_URL; if(p_clearCache && (HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE)) { URL = HTTPUtil.resolveUniqueURL(p_URL, p_rateInSecsToCache); } - - loader.load(new URLRequest(URL)); - loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); - loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); - loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); - - HTTPUtil.k_pings[loader] = true; + + HTTPUtil.ping(new URLRequest(URL)); } public static function addQueryParam(p_URL:String, p_name:String, p_val:String, p_delimeter:String = null):String { if(HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) { if(p_delimeter == null) p_URL += (p_URL.indexOf( "?" ) != -1 ) ? "&" + p_name + "=" : "?" + p_name + "="; else p_URL += p_delimeter + p_name + "="; p_URL += p_val != null ? escape(p_val) : ""; } return p_URL; } public static function resolveUniqueURL(p_URL:String, p_rateInSecsToCache:Number = 0):String { var request:String = p_URL; if((HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) && p_URL.indexOf( "&cacheID=" ) == -1 && p_URL.indexOf( "?cacheID=" ) == -1) { request = HTTPUtil.addQueryParam(p_URL, "cacheID", HTTPUtil.getUniqueCacheID(p_rateInSecsToCache)); } return request; } public static function getUniqueCacheID(p_rateInSecsToCache:Number = 0):String { var d:Date = new Date(); var ID:String; var secsPassed:Number = (60 * d.getUTCMinutes()) + d.getUTCSeconds(); if(p_rateInSecsToCache == 0) { ID = String(d.valueOf()); } else { ID = d.getUTCFullYear() + "" + d.getUTCMonth() + "" +d.getUTCDate() + "" +d.getUTCHours() + "-" + Math.floor(secsPassed/p_rateInSecsToCache); } return ID; } protected static function onPingResult(p_event:Event):void { // NOTE: let errors be thrown or log them if you want to handle them URLLoader(p_event.target).removeEventListener(Event.COMPLETE, HTTPUtil.onPingResult); URLLoader(p_event.target).removeEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); URLLoader(p_event.target).removeEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); delete(HTTPUtil.k_pings[p_event.target]); } } }
dreamsocket/actionscript-analytics-framework
94193d7816ce78aa1706f61bae6973d0dc5ed80f
[NEW] added ability to queue tracks in TrackerManager. by default if enabled, tracks will be queued until a tracker has been added [NEW] added ability to specify properties using bracket syntax (ex: data['myProperty']) [NEW] added ability to specify ActionSource reference to be used by OmnitureTracker [FIX] corrected issue with URLTracker using previous params when tracking against the same ID
diff --git a/bin/daf_google.swf b/bin/daf_google.swf index 3a65f1e..7c03c9e 100644 Binary files a/bin/daf_google.swf and b/bin/daf_google.swf differ diff --git a/bin/daf_javascript.swf b/bin/daf_javascript.swf index 970da61..ad88088 100644 Binary files a/bin/daf_javascript.swf and b/bin/daf_javascript.swf differ diff --git a/bin/daf_omniture.swf b/bin/daf_omniture.swf index fbaf4df..8fa1d3d 100644 Binary files a/bin/daf_omniture.swf and b/bin/daf_omniture.swf differ diff --git a/bin/daf_url.swf b/bin/daf_url.swf index 355593c..ee67448 100644 Binary files a/bin/daf_url.swf and b/bin/daf_url.swf differ diff --git a/bin/dreamsocket_analytics_0.4.100406.swc b/bin/dreamsocket_analytics_0.4.100406.swc deleted file mode 100644 index c29c2a6..0000000 Binary files a/bin/dreamsocket_analytics_0.4.100406.swc and /dev/null differ diff --git a/bin/dreamsocket_analytics_0.5.110216.swc b/bin/dreamsocket_analytics_0.5.110216.swc new file mode 100644 index 0000000..219a19a Binary files /dev/null and b/bin/dreamsocket_analytics_0.5.110216.swc differ diff --git a/build.xml b/build.xml index 38c8f2b..ca86ca2 100644 --- a/build.xml +++ b/build.xml @@ -1,139 +1,139 @@ <?xml version="1.0" encoding="UTF-8"?> <project name="dreamsocket_actionscript_analytics" default="buildAll" basedir="."> <!-- FLEX TASKS --> <property name="FLEX_HOME" value="/tools/flash/flexsdk/4_0"/> <taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> <tstamp><format property="build.date" pattern="yyMMdd" locale="en"/></tstamp> <property name="build.version.major" value="0" /> - <property name="build.version.minor" value="4" /> + <property name="build.version.minor" value="5" /> <property name="build.version.build" value="0" /> <!-- DIRECTORIES --> <property name="project.docs" value="${basedir}/docs/"/> <property name="project.libs" value="${basedir}/libs/"/> <property name="project.output" value="${basedir}/bin/" /> <property name="project.src" value="${basedir}/src/" /> <property name="project.name" value="dreamsocket_analytics" /> <property name="swf.framerate" value="31" /> <property name="swf.width" value="1" /> <property name="swf.height" value="1" /> <!-- BUILD ALL --> <target name="buildAll" depends="clean,buildSWC,buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD ALL PLUGINS --> <target name="buildAllModules" depends="buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD GOOGLE PLUGIN --> <target name="buildGoogleModule"> <antcall target="compileModule"> <param name="module.name" value="daf_google" /> <param name="module.class" value="com/dreamsocket/analytics/google/GoogleTrackerModule.as" /> </antcall> </target> <!-- BUILD JAVASCRIPT PLUGIN --> <target name="buildJavaScriptModule"> <antcall target="compileModule"> <param name="module.name" value="daf_javascript" /> <param name="module.class" value="com/dreamsocket/analytics/js/JSTrackerModule.as" /> </antcall> </target> <!-- BUILD OMNITURE PLUGIN --> <target name="buildOmnitureModule"> <antcall target="compileModule"> <param name="module.name" value="daf_omniture" /> <param name="module.class" value="com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as" /> </antcall> </target> <!-- BUILD URL PLUGIN --> <target name="buildURLModule"> <antcall target="compileModule"> <param name="module.name" value="daf_url" /> <param name="module.class" value="com/dreamsocket/analytics/url/URLTrackerModule.as" /> </antcall> </target> <!-- COMPILE SWC --> <target name="buildSWC"> <compc output="${project.output}/${project.name}_${build.version.major}.${build.version.minor}.${build.date}.swc"> <external-library-path dir="${project.libs}/" append="true" includes="**" /> <include-sources dir="${project.src}" includes="**"/> </compc> </target> <!-- COMPILE PLUGIN--> <target name="compileModule"> <mxmlc file="${project.src}${module.class}" output="${project.output}${module.name}.swf" strict="true" static-link-runtime-shared-libraries="true" > <default-size width="1" height="1" /> <source-path path-element="${project.src}"/> <compiler.library-path dir="${basedir}" append="true"> <include name="libs" /> </compiler.library-path> </mxmlc> </target> <!-- CLEAN --> <target name="clean"> <mkdir dir="${project.output}"/> <delete> <fileset dir="${project.output}" includes="**"/> </delete> </target> <!-- PACKAGE --> <target name="package" depends="buildAll"> <zip update="true" destfile="${project.output}${project.name}_${build.version.major}.${build.version.minor}.${build.date}.zip" > <zipfileset dir="${basedir}" includes="bin/**,libs/**,src/**,test/**,build.xml" /> </zip> </target> <!-- BUILD DOCS --> <target name="buildDocs"> <delete dir="${project.docs}"/> <mkdir dir="${project.docs}"/> <asdoc output="${project.docs}" lenient="true" failonerror="true" main-title="${project.name} ${build.version.major}.${build.version.minor}.${build.date}" window-title="${project.name} ${build.version.major}.${build.version.minor}.${build.date}"> <doc-sources path-element="${project.src}"/> <compiler.library-path dir="${basedir}" append="true"> <include name="libs" /> </compiler.library-path> </asdoc> </target> </project> diff --git a/src/com/dreamsocket/analytics/TrackerManager.as b/src/com/dreamsocket/analytics/TrackerManager.as index 94205bd..bd91742 100644 --- a/src/com/dreamsocket/analytics/TrackerManager.as +++ b/src/com/dreamsocket/analytics/TrackerManager.as @@ -1,88 +1,139 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import flash.utils.Dictionary; public class TrackerManager { protected static var k_enabled:Boolean = true; + protected static var k_queued:Boolean = false; + protected static var k_queuedTracks:Array = []; protected static var k_trackers:Dictionary = new Dictionary(); + protected static var k_trackerCount:uint; public function TrackerManager() { } public static function get enabled():Boolean { return k_enabled; } public static function set enabled(p_enabled:Boolean):void { k_enabled = p_enabled; } + public static function get queued():Boolean + { + return k_queued; + } + + + public static function set queued(p_value:Boolean):void + { + if(p_value != k_queued) + { + k_queued = p_value; + + if(!p_value) + { // if previously queued, track all items in the queue + trackItemsInQueue(); + } + } + } + public static function track(p_track:ITrack):void { if(!k_enabled) return; + if(k_queued || k_trackerCount == 0) + { + k_queuedTracks.push(p_track); + return; + } var tracker:Object; + // if any queued items exist assume that all trackers have been added and send out their payloads + trackItemsInQueue(); // send track payload to all trackers for each(tracker in k_trackers) { ITracker(tracker).track(p_track); } } public static function addTracker(p_ID:String, p_tracker:ITracker):void { + if(!k_trackers[p_ID]) + { + k_trackerCount++; + } k_trackers[p_ID] = p_tracker; } + public static function clearQueue():void + { + k_queuedTracks.splice(0); + } + + public static function getTracker(p_ID:String):ITracker { return k_trackers[p_ID] as ITracker; } public static function removeTracker(p_ID:String):void { + if(!k_trackers[p_ID]) + { + k_trackerCount--; + } delete(k_trackers[p_ID]); - } + } + + + public static function trackItemsInQueue():void + { + var queuedTrack:ITrack; + while(queuedTrack = k_queuedTracks.shift()) + track(queuedTrack); + } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureService.as b/src/com/dreamsocket/analytics/omniture/OmnitureService.as index 84ad128..058acf2 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureService.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureService.as @@ -1,240 +1,240 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import flash.display.Stage; import flash.utils.describeType; import flash.utils.Dictionary; import com.dreamsocket.analytics.omniture.OmnitureParams; import com.dreamsocket.analytics.omniture.OmnitureSingleton; import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParams; import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParams; import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParams; import com.dreamsocket.analytics.omniture.OmnitureMediaStopParams; import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParams; import com.dreamsocket.analytics.omniture.OmnitureTrackParams; import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParams; import com.dreamsocket.analytics.omniture.OmnitureTrackType; import com.omniture.ActionSource; public class OmnitureService { protected var m_config:OmnitureParams; protected var m_enabled:Boolean; protected var m_lastTrackParams:OmnitureParams; protected var m_tracker:ActionSource; protected var m_functions:Dictionary; - public function OmnitureService(p_stage:Stage = null) + public function OmnitureService(p_stage:Stage = null, p_actionSource:ActionSource = null) { - this.m_tracker = OmnitureSingleton.create(p_stage); + this.m_tracker = OmnitureSingleton.create(p_stage, p_actionSource); this.m_enabled = true; this.m_functions = new Dictionary(); this.m_functions[OmnitureTrackType.MEDIA_CLOSE] = this.trackMediaClose; this.m_functions[OmnitureTrackType.MEDIA_OPEN] = this.trackMediaOpen; this.m_functions[OmnitureTrackType.MEDIA_PLAY] = this.trackMediaPlay; this.m_functions[OmnitureTrackType.MEDIA_STOP] = this.trackMediaStop; this.m_functions[OmnitureTrackType.MEDIA_TRACK] = this.trackMedia; this.m_functions[OmnitureTrackType.TRACK] = this.trackEvent; this.m_functions[OmnitureTrackType.TRACK_LINK] = this.trackLink; } public function get config():OmnitureParams { return this.m_config; } public function set config(p_config:OmnitureParams):void { if(p_config != this.m_config) { this.mergeParams(p_config, this.m_tracker, this.m_config == null ? p_config : this.m_config); this.mergeParams(p_config.Media, this.m_tracker.Media, this.m_config == null ? p_config.Media : this.m_config.Media); this.m_config = p_config; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function destroy():void { this.m_tracker = null; this.m_config = null; this.m_lastTrackParams = null; } public function track(p_type:String, p_params:Object):void { if(!this.m_enabled) return; this.setParams(p_params.params); try { this.m_functions[p_type](p_params); } catch(error:Error) { trace(error); } this.resetParams(); } protected function trackEvent(p_params:OmnitureTrackParams):void { this.m_tracker.track(); } protected function trackLink(p_params:OmnitureTrackLinkParams):void { this.m_tracker.trackLink(p_params.URL, p_params.type, p_params.name); } protected function trackMedia(p_params:OmnitureMediaTrackParams):void { this.m_tracker.Media.track(p_params.mediaName); } protected function trackMediaOpen(p_params:OmnitureMediaOpenParams):void { this.m_tracker.Media.open(p_params.mediaName, Number(p_params.mediaLength), p_params.mediaPlayerName); } protected function trackMediaClose(p_params:OmnitureMediaCloseParams):void { this.m_tracker.Media.close(p_params.mediaName); } protected function trackMediaPlay(p_params:OmnitureMediaPlayParams):void { this.m_tracker.Media.play(p_params.mediaName, Number(p_params.mediaOffset)); } protected function trackMediaStop(p_params:OmnitureMediaStopParams):void { this.m_tracker.Media.stop(p_params.mediaName, Number(p_params.mediaOffset)); } protected function mergeParams(p_newValues:Object, p_destination:Object, p_oldValues:Object):void { var desc:XML = describeType(p_newValues); var propNode:XML; var props:XMLList = desc..variable; var type:String; var name:String; var oldVal:*; var newVal:*; // instance props for each(propNode in props) { name = propNode.@name; type = propNode.@type; oldVal = p_oldValues[name]; newVal = p_newValues[name]; if(oldVal is String && oldVal != null) { p_destination[name] = newVal; } else if(oldVal is Number && !isNaN(oldVal)) { p_destination[name] = newVal; } else if(oldVal is Boolean && oldVal) { p_destination[name] = newVal; } } // dynamic props for(name in p_oldValues) { oldVal = p_oldValues[name]; newVal = p_newValues[name]; if(oldVal is String && oldVal != null) { p_destination[name] = newVal; } else if(oldVal is Number && !isNaN(oldVal)) { p_destination[name] = newVal; } else if(oldVal is Boolean && oldVal) { p_destination[name] = newVal; } } } protected function resetParams():void { if(this.m_lastTrackParams == null) return; this.mergeParams(this.m_config, this.m_tracker, this.m_lastTrackParams); this.mergeParams(this.m_config.Media, this.m_tracker.Media, this.m_lastTrackParams.Media); } protected function setParams(p_params:OmnitureParams):void { this.m_lastTrackParams = p_params; this.mergeParams(p_params, this.m_tracker, p_params); this.mergeParams(p_params.Media, this.m_tracker.Media, p_params.Media); } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureSingleton.as b/src/com/dreamsocket/analytics/omniture/OmnitureSingleton.as index 00e7e51..c5aa057 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureSingleton.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureSingleton.as @@ -1,73 +1,82 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import flash.display.Stage; import com.omniture.ActionSource; public class OmnitureSingleton { protected static var k_stage:Stage; protected static var k_instance:ActionSource; public function OmnitureSingleton() { } public static function set stage(p_display:Stage):void { OmnitureSingleton.create(p_display); } - public static function create(p_display:Stage):ActionSource + public static function create(p_display:Stage, p_actionSource:ActionSource = null):ActionSource { + if(p_actionSource) + k_instance = p_actionSource; + var mod:ActionSource = OmnitureSingleton.instance; - if(p_display != null) + if(p_display != null && !mod.parent) { p_display.addChild(mod); } return k_instance; } public static function get instance():ActionSource { if(k_instance == null) { k_instance = new ActionSource(); } return k_instance; } + + + public static function set instance(p_value:ActionSource):void + { + k_instance = p_value; + } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as b/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as index 3976f69..f9f5a01 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as @@ -1,179 +1,181 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import flash.display.Stage; import flash.utils.Dictionary; import com.dreamsocket.analytics.ITrack; import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.omniture.OmnitureService; import com.dreamsocket.analytics.omniture.OmnitureTrackerConfig; import com.dreamsocket.analytics.omniture.OmnitureTrackHandler; import com.dreamsocket.analytics.omniture.OmnitureTrackType; import com.dreamsocket.analytics.omniture.OmnitureBatchParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaStopParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureTrackParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParamsMapper; + import com.omniture.ActionSource; + public class OmnitureTracker implements ITracker { public static const ID:String = "OmnitureTracker"; protected var m_config:OmnitureTrackerConfig; protected var m_enabled:Boolean; protected var m_service:OmnitureService; protected var m_handlers:Dictionary; protected var m_functions:Dictionary; protected var m_paramMappers:Dictionary; - public function OmnitureTracker(p_stage:Stage = null) + public function OmnitureTracker(p_stage:Stage = null, p_actionSource:ActionSource = null) { super(); this.m_config = new OmnitureTrackerConfig(); this.m_enabled = true; - this.m_service = new OmnitureService(p_stage); + this.m_service = new OmnitureService(p_stage, p_actionSource); this.m_handlers = new Dictionary(); this.m_functions = new Dictionary(); this.m_functions[OmnitureTrackType.BATCH] = this.batch; this.m_functions[OmnitureTrackType.MEDIA_CLOSE] = this.doTrack; this.m_functions[OmnitureTrackType.MEDIA_OPEN] = this.doTrack; this.m_functions[OmnitureTrackType.MEDIA_PLAY] = this.doTrack; this.m_functions[OmnitureTrackType.MEDIA_STOP] = this.doTrack; this.m_functions[OmnitureTrackType.MEDIA_TRACK] = this.doTrack; this.m_functions[OmnitureTrackType.TRACK] = this.doTrack; this.m_functions[OmnitureTrackType.TRACK_LINK] = this.doTrack; this.m_paramMappers = new Dictionary(); this.m_paramMappers[OmnitureTrackType.BATCH] = new OmnitureBatchParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_CLOSE] = new OmnitureMediaCloseParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_OPEN] = new OmnitureMediaOpenParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_PLAY] = new OmnitureMediaPlayParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_STOP] = new OmnitureMediaStopParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_TRACK] = new OmnitureMediaTrackParamsMapper(); this.m_paramMappers[OmnitureTrackType.TRACK] = new OmnitureTrackParamsMapper(); this.m_paramMappers[OmnitureTrackType.TRACK_LINK] = new OmnitureTrackLinkParamsMapper(); } public function get config():OmnitureTrackerConfig { return this.m_config; } public function set config(p_value:OmnitureTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; this.m_service.config = p_value.params; this.m_enabled = p_value.enabled; this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function get ID():String { return OmnitureTracker.ID; } public function addTrackHandler(p_ID:String, p_handler:OmnitureTrackHandler):void { this.m_handlers[p_ID] = p_handler; } public function getTrackHandler(p_ID:String):OmnitureTrackHandler { return this.m_handlers[p_ID] as OmnitureTrackHandler; } public function removeTrackHandler(p_ID:String):void { delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled) return; var handler:OmnitureTrackHandler = this.m_config.handlers[p_track.ID]; if(handler && this.m_functions[handler.type]) { // has a track handler this.m_functions[handler.type](handler, p_track.data); } } protected function doTrack(p_handler:OmnitureTrackHandler, p_data:*):void { if(p_handler.params != null && this.m_paramMappers[p_handler.type] != null) { // has a track handler this.m_service.track(p_handler.type, this.m_paramMappers[p_handler.type].map(p_handler.params, p_data)); } } protected function batch(p_handler:OmnitureTrackHandler, p_data:*):void { var params:Object = p_handler.params; var i:uint = 0; var len:uint = params.handlers.length; while(i < len) { this.doTrack(OmnitureTrackHandler(params.handlers[i++]), p_data); } } } } diff --git a/src/com/dreamsocket/analytics/url/URLTracker.as b/src/com/dreamsocket/analytics/url/URLTracker.as index cde8bda..1734fe4 100644 --- a/src/com/dreamsocket/analytics/url/URLTracker.as +++ b/src/com/dreamsocket/analytics/url/URLTracker.as @@ -1,154 +1,157 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.url { import flash.net.URLVariables; import flash.net.URLRequest; import flash.utils.Dictionary; import com.dreamsocket.utils.PropertyStringUtil; import com.dreamsocket.analytics.ITrack; import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.url.URLTrackerConfig; import com.dreamsocket.analytics.url.URLTrackHandler; import com.dreamsocket.utils.HTTPUtil; public class URLTracker implements ITracker { public static const ID:String = "URLTracker"; protected var m_config:URLTrackerConfig; protected var m_enabled:Boolean; protected var m_handlers:Dictionary; public function URLTracker() { super(); this.m_config = new URLTrackerConfig(); this.m_enabled = true; this.m_handlers = new Dictionary(); } public function get config():URLTrackerConfig { return this.m_config; } public function set config(p_value:URLTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; this.m_enabled = p_value.enabled; this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function get ID():String { return URLTracker.ID; } public function addTrackHandler(p_ID:String, p_handler:URLTrackHandler):void { this.m_handlers[p_ID] = p_handler; } public function getTrackHandler(p_ID:String):URLTrackHandler { return this.m_handlers[p_ID] as URLTrackHandler; } public function removeTrackHandler(p_ID:String):void { delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled) return; var handler:URLTrackHandler = this.m_handlers[p_track.ID]; - + if(handler != null) { // has the track type var requests:Array = handler.params; var i:uint = requests.length; var request:URLRequest; + var requestParams:URLRequest; var prop:String; var vars:Object; var urlVars:URLVariables; while(i--) { - request = URLRequest(requests[i]); - request.url = (PropertyStringUtil.evalPropertyString(p_track.data, request.url)); - vars = request.data; + requestParams = URLRequest(requests[i]); + request = new URLRequest(); + request.method = requestParams.method; + request.url = (PropertyStringUtil.evalPropertyString(p_track.data, requestParams.url)); + vars = requestParams.data; if(vars is String) { - PropertyStringUtil.evalPropertyString(p_track.data, String(vars)); + request.data = PropertyStringUtil.evalPropertyString(p_track.data, String(vars)); } else if(vars is Object) { request.data = urlVars = new URLVariables; for(prop in vars) { urlVars[prop] = (PropertyStringUtil.evalPropertyString(p_track.data, vars[prop])); } } HTTPUtil.ping(request); } } } } } \ No newline at end of file diff --git a/src/com/dreamsocket/utils/PropertyStringUtil.as b/src/com/dreamsocket/utils/PropertyStringUtil.as index 26ae4eb..bb6f5bb 100644 --- a/src/com/dreamsocket/utils/PropertyStringUtil.as +++ b/src/com/dreamsocket/utils/PropertyStringUtil.as @@ -1,90 +1,97 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.utils { public class PropertyStringUtil { public function PropertyStringUtil() { } public static function evalPropertyString(p_data:*, p_value:String):String { if(p_data == null || p_value == null) return null; return p_value.replace( new RegExp("\\${.*?}", "gi"), function():String { return (PropertyStringUtil.evalSinglePropertyString(p_data, arguments[0].replace(new RegExp( "\\${|}", "gi"), ""))); } ); } - protected static function evalSinglePropertyString(p_data:*, p_value:String = null):* + public static function evalSinglePropertyString(p_data:*, p_value:String = null):* { + var key:String; var val:String = p_value == null ? "" : p_value; var currPart:* = p_data; - var parts:Array; - var key:String; + var parts:Array = val.match(new RegExp( "\\['.+?'\\]", "gi")); + var i:uint = parts.length; + while(i--) + { + val = val.replace(parts[i], parts[i].replace(new RegExp("\\.", "gi"), "@@@@")); + } + val = val.replace(new RegExp("\\['", "gi"), "."); + val = val.replace(new RegExp("'\\]", "gi"), ""); parts = val.split("."); key = parts.shift(); - switch(key) { case "cache.UID": currPart = new Date().valueOf(); break; case "data": try { - var i:uint = 0; + i = 0; var len:uint = parts.length; if(len != 0) { for(; i < len; i++) { - currPart = currPart[parts[i]]; + currPart = currPart[parts[i].replace(new RegExp("@@@@", "gi"), ".")]; } } } catch(error:Error) { + trace("PropertyStringUtil.evalSinglePropertyString -" + error) currPart = null; } break; } return (currPart); } } }
dreamsocket/actionscript-analytics-framework
b265711fc8d1d4c312e17bb3c76ddba38b139ed7
[NEW] added ant task to build ASDocs
diff --git a/build.xml b/build.xml index 511a223..38c8f2b 100644 --- a/build.xml +++ b/build.xml @@ -1,117 +1,139 @@ <?xml version="1.0" encoding="UTF-8"?> <project name="dreamsocket_actionscript_analytics" default="buildAll" basedir="."> <!-- FLEX TASKS --> <property name="FLEX_HOME" value="/tools/flash/flexsdk/4_0"/> <taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> <tstamp><format property="build.date" pattern="yyMMdd" locale="en"/></tstamp> <property name="build.version.major" value="0" /> <property name="build.version.minor" value="4" /> <property name="build.version.build" value="0" /> <!-- DIRECTORIES --> + <property name="project.docs" value="${basedir}/docs/"/> <property name="project.libs" value="${basedir}/libs/"/> <property name="project.output" value="${basedir}/bin/" /> <property name="project.src" value="${basedir}/src/" /> <property name="project.name" value="dreamsocket_analytics" /> <property name="swf.framerate" value="31" /> <property name="swf.width" value="1" /> <property name="swf.height" value="1" /> <!-- BUILD ALL --> <target name="buildAll" depends="clean,buildSWC,buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD ALL PLUGINS --> <target name="buildAllModules" depends="buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD GOOGLE PLUGIN --> <target name="buildGoogleModule"> <antcall target="compileModule"> <param name="module.name" value="daf_google" /> <param name="module.class" value="com/dreamsocket/analytics/google/GoogleTrackerModule.as" /> </antcall> </target> <!-- BUILD JAVASCRIPT PLUGIN --> <target name="buildJavaScriptModule"> <antcall target="compileModule"> <param name="module.name" value="daf_javascript" /> <param name="module.class" value="com/dreamsocket/analytics/js/JSTrackerModule.as" /> </antcall> </target> <!-- BUILD OMNITURE PLUGIN --> <target name="buildOmnitureModule"> <antcall target="compileModule"> <param name="module.name" value="daf_omniture" /> <param name="module.class" value="com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as" /> </antcall> </target> <!-- BUILD URL PLUGIN --> <target name="buildURLModule"> <antcall target="compileModule"> <param name="module.name" value="daf_url" /> <param name="module.class" value="com/dreamsocket/analytics/url/URLTrackerModule.as" /> </antcall> </target> <!-- COMPILE SWC --> <target name="buildSWC"> <compc output="${project.output}/${project.name}_${build.version.major}.${build.version.minor}.${build.date}.swc"> <external-library-path dir="${project.libs}/" append="true" includes="**" /> <include-sources dir="${project.src}" includes="**"/> </compc> </target> <!-- COMPILE PLUGIN--> <target name="compileModule"> <mxmlc file="${project.src}${module.class}" output="${project.output}${module.name}.swf" strict="true" static-link-runtime-shared-libraries="true" > <default-size width="1" height="1" /> <source-path path-element="${project.src}"/> <compiler.library-path dir="${basedir}" append="true"> <include name="libs" /> </compiler.library-path> </mxmlc> </target> <!-- CLEAN --> <target name="clean"> <mkdir dir="${project.output}"/> <delete> <fileset dir="${project.output}" includes="**"/> </delete> </target> <!-- PACKAGE --> <target name="package" depends="buildAll"> <zip update="true" destfile="${project.output}${project.name}_${build.version.major}.${build.version.minor}.${build.date}.zip" > <zipfileset dir="${basedir}" includes="bin/**,libs/**,src/**,test/**,build.xml" /> </zip> </target> + <!-- BUILD DOCS --> + <target name="buildDocs"> + <delete dir="${project.docs}"/> + <mkdir dir="${project.docs}"/> + <asdoc + output="${project.docs}" + lenient="true" + failonerror="true" + main-title="${project.name} ${build.version.major}.${build.version.minor}.${build.date}" + window-title="${project.name} ${build.version.major}.${build.version.minor}.${build.date}"> + + <doc-sources path-element="${project.src}"/> + <compiler.library-path + dir="${basedir}" + append="true"> + <include + name="libs" /> + </compiler.library-path> + </asdoc> + </target> + </project>
dreamsocket/actionscript-analytics-framework
0dd3490974ac4088f6eca90daebdeeadbf52b9f9
[CHG] updated version minor to 4 [CHG] recompiled all binaries with changes from last checkin
diff --git a/bin/daf_google.swf b/bin/daf_google.swf index c0b5ff5..3a65f1e 100644 Binary files a/bin/daf_google.swf and b/bin/daf_google.swf differ diff --git a/bin/daf_javascript.swf b/bin/daf_javascript.swf index f297d4d..970da61 100644 Binary files a/bin/daf_javascript.swf and b/bin/daf_javascript.swf differ diff --git a/bin/daf_omniture.swf b/bin/daf_omniture.swf index 4a958dd..fbaf4df 100644 Binary files a/bin/daf_omniture.swf and b/bin/daf_omniture.swf differ diff --git a/bin/daf_url.swf b/bin/daf_url.swf index 87d0a09..355593c 100644 Binary files a/bin/daf_url.swf and b/bin/daf_url.swf differ diff --git a/bin/dreamsocket_analytics_0.3.100405.swc b/bin/dreamsocket_analytics_0.3.100405.swc deleted file mode 100644 index 67dcdcf..0000000 Binary files a/bin/dreamsocket_analytics_0.3.100405.swc and /dev/null differ diff --git a/bin/dreamsocket_analytics_0.4.100406.swc b/bin/dreamsocket_analytics_0.4.100406.swc new file mode 100644 index 0000000..c29c2a6 Binary files /dev/null and b/bin/dreamsocket_analytics_0.4.100406.swc differ diff --git a/build.xml b/build.xml index ed74cb5..511a223 100644 --- a/build.xml +++ b/build.xml @@ -1,117 +1,117 @@ <?xml version="1.0" encoding="UTF-8"?> <project name="dreamsocket_actionscript_analytics" default="buildAll" basedir="."> <!-- FLEX TASKS --> <property name="FLEX_HOME" value="/tools/flash/flexsdk/4_0"/> <taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> <tstamp><format property="build.date" pattern="yyMMdd" locale="en"/></tstamp> <property name="build.version.major" value="0" /> - <property name="build.version.minor" value="3" /> + <property name="build.version.minor" value="4" /> <property name="build.version.build" value="0" /> <!-- DIRECTORIES --> <property name="project.libs" value="${basedir}/libs/"/> <property name="project.output" value="${basedir}/bin/" /> <property name="project.src" value="${basedir}/src/" /> <property name="project.name" value="dreamsocket_analytics" /> <property name="swf.framerate" value="31" /> <property name="swf.width" value="1" /> <property name="swf.height" value="1" /> <!-- BUILD ALL --> <target name="buildAll" depends="clean,buildSWC,buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD ALL PLUGINS --> <target name="buildAllModules" depends="buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD GOOGLE PLUGIN --> <target name="buildGoogleModule"> <antcall target="compileModule"> <param name="module.name" value="daf_google" /> <param name="module.class" value="com/dreamsocket/analytics/google/GoogleTrackerModule.as" /> </antcall> </target> <!-- BUILD JAVASCRIPT PLUGIN --> <target name="buildJavaScriptModule"> <antcall target="compileModule"> <param name="module.name" value="daf_javascript" /> <param name="module.class" value="com/dreamsocket/analytics/js/JSTrackerModule.as" /> </antcall> </target> <!-- BUILD OMNITURE PLUGIN --> <target name="buildOmnitureModule"> <antcall target="compileModule"> <param name="module.name" value="daf_omniture" /> <param name="module.class" value="com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as" /> </antcall> </target> <!-- BUILD URL PLUGIN --> <target name="buildURLModule"> <antcall target="compileModule"> <param name="module.name" value="daf_url" /> <param name="module.class" value="com/dreamsocket/analytics/url/URLTrackerModule.as" /> </antcall> </target> <!-- COMPILE SWC --> <target name="buildSWC"> <compc output="${project.output}/${project.name}_${build.version.major}.${build.version.minor}.${build.date}.swc"> <external-library-path dir="${project.libs}/" append="true" includes="**" /> <include-sources dir="${project.src}" includes="**"/> </compc> </target> <!-- COMPILE PLUGIN--> <target name="compileModule"> <mxmlc file="${project.src}${module.class}" output="${project.output}${module.name}.swf" strict="true" static-link-runtime-shared-libraries="true" > <default-size width="1" height="1" /> <source-path path-element="${project.src}"/> <compiler.library-path dir="${basedir}" append="true"> <include name="libs" /> </compiler.library-path> </mxmlc> </target> <!-- CLEAN --> <target name="clean"> <mkdir dir="${project.output}"/> <delete> <fileset dir="${project.output}" includes="**"/> </delete> </target> <!-- PACKAGE --> <target name="package" depends="buildAll"> <zip update="true" destfile="${project.output}${project.name}_${build.version.major}.${build.version.minor}.${build.date}.zip" > <zipfileset dir="${basedir}" includes="bin/**,libs/**,src/**,test/**,build.xml" /> </zip> </target> </project>
dreamsocket/actionscript-analytics-framework
79165e673fc9c3ed2b6d5d2f523825bbd61043d3
[CHG] renamed resource property to params property on TrackerModuleLoaderEvent [CHG] general trace, import cleanups [NEW] added evar and prop properties to OmnitureParams [DEL] removed unused file GoogleTrackerParams
diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoader.as b/src/com/dreamsocket/analytics/TrackerModuleLoader.as index 8545d2e..70fd342 100644 --- a/src/com/dreamsocket/analytics/TrackerModuleLoader.as +++ b/src/com/dreamsocket/analytics/TrackerModuleLoader.as @@ -1 +1 @@ -/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.TrackerModuleParams; import com.dreamsocket.analytics.ITrackerModule; import com.dreamsocket.analytics.TrackerModuleLoaderParams; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import flash.display.Loader; import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TrackerModuleLoader extends Sprite { private var m_params:TrackerModuleLoaderParams; private var m_config:XML; private var m_module:ITrackerModule; private var m_configLoader:URLLoader; private var m_moduleLoader:Loader; public function TrackerModuleLoader() { } public function destroy():void { if(this.m_configLoader) { this.m_configLoader.removeEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.close(); } catch(error:Error){} this.m_configLoader = null; } if(this.m_moduleLoader) { this.m_moduleLoader.contentLoaderInfo.removeEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.close(); } catch(error:Error){} try { this.m_moduleLoader.unload(); } catch(error:Error){} this.m_moduleLoader = null; } this.m_params = null; this.m_config = null; this.m_module = null; } public function load(p_resource:TrackerModuleLoaderParams):void { this.destroy(); this.m_params = p_resource; this.loadConfig(); } private function createModule():void { var params:TrackerModuleParams = new TrackerModuleParams(); params.stage = this.m_params.stage; params.config = this.m_config; try { var tracker:ITracker = this.m_module.getTracker(params); var loadParams:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_LOADED, loadParams, tracker)); } catch(error:Error) { trace("moduleLoaded:" + error) this.dispatchError(error.message); } } public function loadConfig():void { if(this.m_params.config is XML) { // this is XML load module this.m_config = this.m_params.config; this.loadModule(); return; } this.m_configLoader = new URLLoader(); this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.load(new URLRequest(this.m_params.config)); } catch(error:Error) { this.dispatchError(error.message); } } private function loadModule():void { if(this.m_params.resource is ITrackerModule) { this.m_module = this.m_params.resource; this.createModule(); return; } // load the module this.m_moduleLoader = new Loader(); this.m_moduleLoader.contentLoaderInfo.addEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.load(new URLRequest(this.m_params.resource)); } catch(error:Error) { this.dispatchError(error.message); } } private function dispatchError(p_message:String):void { trace(p_message) var params:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_FAILED, params)); } private function onErrorOccurred(p_event:ErrorEvent):void { trace(p_event) this.dispatchError(p_event.text); } private function onConfigLoaded(p_event:Event):void { trace("config loaded") try { this.m_config = new XML(this.m_configLoader.data); this.loadModule(); } catch(error:Error) { this.dispatchError(error.message); } } private function onModuleLoaded(p_event:Event):void { this.m_module = ITrackerModule(this.m_moduleLoader.content); this.createModule(); } } } \ No newline at end of file +/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.TrackerModuleParams; import com.dreamsocket.analytics.ITrackerModule; import com.dreamsocket.analytics.TrackerModuleLoaderParams; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import flash.display.Loader; import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TrackerModuleLoader extends Sprite { private var m_params:TrackerModuleLoaderParams; private var m_config:XML; private var m_module:ITrackerModule; private var m_configLoader:URLLoader; private var m_moduleLoader:Loader; public function TrackerModuleLoader() { } public function destroy():void { if(this.m_configLoader) { this.m_configLoader.removeEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.close(); } catch(error:Error){} this.m_configLoader = null; } if(this.m_moduleLoader) { this.m_moduleLoader.contentLoaderInfo.removeEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.close(); } catch(error:Error){} try { this.m_moduleLoader.unload(); } catch(error:Error){} this.m_moduleLoader = null; } this.m_params = null; this.m_config = null; this.m_module = null; } public function load(p_resource:TrackerModuleLoaderParams):void { this.destroy(); this.m_params = p_resource; this.loadConfig(); } private function createModule():void { var params:TrackerModuleParams = new TrackerModuleParams(); params.stage = this.m_params.stage; params.config = this.m_config; try { var tracker:ITracker = this.m_module.getTracker(params); var loadParams:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_LOADED, loadParams, tracker)); } catch(error:Error) { trace("moduleLoaded:" + error) this.dispatchError(error.message); } } public function loadConfig():void { if(this.m_params.config is XML) { // this is XML load module this.m_config = this.m_params.config; this.loadModule(); return; } this.m_configLoader = new URLLoader(); this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.load(new URLRequest(this.m_params.config)); } catch(error:Error) { this.dispatchError(error.message); } } private function loadModule():void { if(this.m_params.resource is ITrackerModule) { this.m_module = this.m_params.resource; this.createModule(); return; } // load the module this.m_moduleLoader = new Loader(); this.m_moduleLoader.contentLoaderInfo.addEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.load(new URLRequest(this.m_params.resource)); } catch(error:Error) { this.dispatchError(error.message); } } private function dispatchError(p_message:String):void { trace(p_message) var params:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_FAILED, params)); } private function onErrorOccurred(p_event:ErrorEvent):void { this.dispatchError(p_event.text); } private function onConfigLoaded(p_event:Event):void { try { this.m_config = new XML(this.m_configLoader.data); this.loadModule(); } catch(error:Error) { this.dispatchError(error.message); } } private function onModuleLoaded(p_event:Event):void { this.m_module = ITrackerModule(this.m_moduleLoader.content); this.createModule(); } } } \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoaderEvent.as b/src/com/dreamsocket/analytics/TrackerModuleLoaderEvent.as index a6a25db..78c2825 100644 --- a/src/com/dreamsocket/analytics/TrackerModuleLoaderEvent.as +++ b/src/com/dreamsocket/analytics/TrackerModuleLoaderEvent.as @@ -1,77 +1,77 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import flash.events.Event; import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.TrackerModuleLoaderParams; public class TrackerModuleLoaderEvent extends Event { public static const MODULE_LOADED:String = "moduleLoaded"; public static const MODULE_FAILED:String = "moduleFailed"; - private var m_resource:TrackerModuleLoaderParams; + private var m_params:TrackerModuleLoaderParams; private var m_tracker:ITracker; - public function TrackerModuleLoaderEvent(p_eventType:String, p_resource:TrackerModuleLoaderParams, p_tracker:ITracker = null, p_bubbles:Boolean = false, p_cancelable:Boolean = false) + public function TrackerModuleLoaderEvent(p_eventType:String, p_params:TrackerModuleLoaderParams, p_tracker:ITracker = null, p_bubbles:Boolean = false, p_cancelable:Boolean = false) { super(p_eventType, p_bubbles, p_cancelable); - this.m_resource = p_resource; + this.m_params = p_params; this.m_tracker = p_tracker; } - public function get resource():TrackerModuleLoaderParams + public function get params():TrackerModuleLoaderParams { - return this.m_resource; + return this.m_params; } public function get tracker():ITracker { return this.m_tracker; } override public function clone():Event { - return new TrackerModuleLoaderEvent(this.type, this.resource, this.tracker, this.bubbles, this.cancelable); + return new TrackerModuleLoaderEvent(this.type, this.params, this.tracker, this.bubbles, this.cancelable); } override public function toString():String { return this.formatToString("TrackerModuleLoaderEvent", "type", "bubbles", "eventPhase"); } } } \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as b/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as index 535ee87..0ac8408 100644 --- a/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as +++ b/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as @@ -1,99 +1,99 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import flash.events.Event; import flash.events.EventDispatcher; import com.dreamsocket.analytics.TrackerModuleLoader; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import com.dreamsocket.analytics.TrackerModuleLoaderParams; public class TrackerModuleLoaderQueue extends EventDispatcher { private var m_manifest:Array; private var m_moduleLoader:TrackerModuleLoader; public function TrackerModuleLoaderQueue() { this.m_manifest = []; this.m_moduleLoader = new TrackerModuleLoader(); this.m_moduleLoader.addEventListener(TrackerModuleLoaderEvent.MODULE_LOADED, this.onModuleLoaded); this.m_moduleLoader.addEventListener(TrackerModuleLoaderEvent.MODULE_FAILED, this.onModuleFailed); } public function set manifest(p_value:Array):void { this.m_manifest = p_value; } public function add(p_params:TrackerModuleLoaderParams):void { this.m_manifest.push(p_params); } public function destroy():void { this.m_moduleLoader.destroy(); this.m_manifest.slice(); } public function load():void { var params:TrackerModuleLoaderParams = TrackerModuleLoaderParams(this.m_manifest.shift()); if(params) { this.m_moduleLoader.load(params); } else { this.dispatchEvent(new Event(Event.COMPLETE)); } } private function onModuleFailed(p_event:TrackerModuleLoaderEvent):void { - trace(p_event) + trace(p_event); this.load(); } private function onModuleLoaded(p_event:TrackerModuleLoaderEvent):void { TrackerManager.addTracker(p_event.tracker.ID, p_event.tracker); this.load(); } } } diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackerParams.as b/src/com/dreamsocket/analytics/google/GoogleTrackerParams.as deleted file mode 100644 index 6c5505f..0000000 --- a/src/com/dreamsocket/analytics/google/GoogleTrackerParams.as +++ /dev/null @@ -1,34 +0,0 @@ -/** -* Dreamsocket, Inc. -* http://dreamsocket.com -* Copyright 2010 Dreamsocket, Inc. -* -* 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. -**/ - - -package com.dreamsocket.analytics.google -{ - public class GoogleTrackerParams - { - } -} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureParams.as index 201335a..86c6aa9 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureParams.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureParams.as @@ -1,71 +1,176 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import com.dreamsocket.analytics.omniture.OmnitureMediaParams; public dynamic class OmnitureParams { // debug vars public var debugTracking:Boolean; public var trackLocal:Boolean; // required public var account:String; public var dc:String; public var pageName:String; public var pageURL:String; public var visitorNameSpace:String; // optional public var autoTrack:Boolean; public var charSet:String; public var cookieDomainPeriods:Number; public var cookieLifetime:String; public var currencyCode:String; public var delayTracking:Number; public var events:String; public var linkLeaveQueryString:Boolean; public var movieID:String; public var pageType:String; public var referrer:String; public var trackClickMap:Boolean; public var trackingServer:String; public var trackingServerBase:String; public var trackingServerSecure:String; public var vmk:String; + // optional evars + public var eVar1:String; + public var eVar2:String; + public var eVar3:String; + public var eVar4:String; + public var eVar5:String; + public var eVar6:String; + public var eVar7:String; + public var eVar8:String; + public var eVar9:String; + public var eVar10:String; + public var eVar11:String; + public var eVar12:String; + public var eVar13:String; + public var eVar14:String; + public var eVar15:String; + public var eVar16:String; + public var eVar17:String; + public var eVar18:String; + public var eVar19:String; + public var eVar20:String; + public var eVar21:String; + public var eVar22:String; + public var eVar23:String; + public var eVar24:String; + public var eVar25:String; + public var eVar26:String; + public var eVar27:String; + public var eVar28:String; + public var eVar29:String; + public var eVar30:String; + public var eVar31:String; + public var eVar32:String; + public var eVar33:String; + public var eVar34:String; + public var eVar35:String; + public var eVar36:String; + public var eVar37:String; + public var eVar38:String; + public var eVar39:String; + public var eVar40:String; + public var eVar41:String; + public var eVar42:String; + public var eVar43:String; + public var eVar44:String; + public var eVar45:String; + public var eVar46:String; + public var eVar47:String; + public var eVar48:String; + public var eVar49:String; + public var eVar50:String; + + // optional props + public var prop1:String; + public var prop2:String; + public var prop3:String; + public var prop4:String; + public var prop5:String; + public var prop6:String; + public var prop7:String; + public var prop8:String; + public var prop9:String; + public var prop10:String; + public var prop11:String; + public var prop12:String; + public var prop13:String; + public var prop14:String; + public var prop15:String; + public var prop16:String; + public var prop17:String; + public var prop18:String; + public var prop19:String; + public var prop20:String; + public var prop21:String; + public var prop22:String; + public var prop23:String; + public var prop24:String; + public var prop25:String; + public var prop26:String; + public var prop27:String; + public var prop28:String; + public var prop29:String; + public var prop30:String; + public var prop31:String; + public var prop32:String; + public var prop33:String; + public var prop34:String; + public var prop35:String; + public var prop36:String; + public var prop37:String; + public var prop38:String; + public var prop39:String; + public var prop40:String; + public var prop41:String; + public var prop42:String; + public var prop43:String; + public var prop44:String; + public var prop45:String; + public var prop46:String; + public var prop47:String; + public var prop48:String; + public var prop49:String; + public var prop50:String; + + public var Media:OmnitureMediaParams; public function OmnitureParams() { this.Media = new OmnitureMediaParams(); } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureService.as b/src/com/dreamsocket/analytics/omniture/OmnitureService.as index 6a8534e..84ad128 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureService.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureService.as @@ -1,244 +1,240 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import flash.display.Stage; import flash.utils.describeType; import flash.utils.Dictionary; import com.dreamsocket.analytics.omniture.OmnitureParams; import com.dreamsocket.analytics.omniture.OmnitureSingleton; import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParams; import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParams; import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParams; import com.dreamsocket.analytics.omniture.OmnitureMediaStopParams; import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParams; import com.dreamsocket.analytics.omniture.OmnitureTrackParams; import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParams; import com.dreamsocket.analytics.omniture.OmnitureTrackType; import com.omniture.ActionSource; public class OmnitureService { protected var m_config:OmnitureParams; protected var m_enabled:Boolean; protected var m_lastTrackParams:OmnitureParams; protected var m_tracker:ActionSource; protected var m_functions:Dictionary; public function OmnitureService(p_stage:Stage = null) { this.m_tracker = OmnitureSingleton.create(p_stage); this.m_enabled = true; this.m_functions = new Dictionary(); this.m_functions[OmnitureTrackType.MEDIA_CLOSE] = this.trackMediaClose; this.m_functions[OmnitureTrackType.MEDIA_OPEN] = this.trackMediaOpen; this.m_functions[OmnitureTrackType.MEDIA_PLAY] = this.trackMediaPlay; this.m_functions[OmnitureTrackType.MEDIA_STOP] = this.trackMediaStop; this.m_functions[OmnitureTrackType.MEDIA_TRACK] = this.trackMedia; this.m_functions[OmnitureTrackType.TRACK] = this.trackEvent; this.m_functions[OmnitureTrackType.TRACK_LINK] = this.trackLink; } public function get config():OmnitureParams { return this.m_config; } public function set config(p_config:OmnitureParams):void { if(p_config != this.m_config) { this.mergeParams(p_config, this.m_tracker, this.m_config == null ? p_config : this.m_config); this.mergeParams(p_config.Media, this.m_tracker.Media, this.m_config == null ? p_config.Media : this.m_config.Media); this.m_config = p_config; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function destroy():void { this.m_tracker = null; this.m_config = null; this.m_lastTrackParams = null; } public function track(p_type:String, p_params:Object):void { if(!this.m_enabled) return; this.setParams(p_params.params); try { this.m_functions[p_type](p_params); } catch(error:Error) { trace(error); } this.resetParams(); } protected function trackEvent(p_params:OmnitureTrackParams):void { this.m_tracker.track(); } protected function trackLink(p_params:OmnitureTrackLinkParams):void { this.m_tracker.trackLink(p_params.URL, p_params.type, p_params.name); } protected function trackMedia(p_params:OmnitureMediaTrackParams):void { this.m_tracker.Media.track(p_params.mediaName); } protected function trackMediaOpen(p_params:OmnitureMediaOpenParams):void { - trace("open") this.m_tracker.Media.open(p_params.mediaName, Number(p_params.mediaLength), p_params.mediaPlayerName); } protected function trackMediaClose(p_params:OmnitureMediaCloseParams):void { - trace("close") this.m_tracker.Media.close(p_params.mediaName); } protected function trackMediaPlay(p_params:OmnitureMediaPlayParams):void { - trace("play") this.m_tracker.Media.play(p_params.mediaName, Number(p_params.mediaOffset)); } protected function trackMediaStop(p_params:OmnitureMediaStopParams):void { - trace("stop") this.m_tracker.Media.stop(p_params.mediaName, Number(p_params.mediaOffset)); } protected function mergeParams(p_newValues:Object, p_destination:Object, p_oldValues:Object):void { var desc:XML = describeType(p_newValues); var propNode:XML; var props:XMLList = desc..variable; var type:String; var name:String; var oldVal:*; var newVal:*; // instance props for each(propNode in props) { name = propNode.@name; type = propNode.@type; oldVal = p_oldValues[name]; newVal = p_newValues[name]; if(oldVal is String && oldVal != null) { p_destination[name] = newVal; } else if(oldVal is Number && !isNaN(oldVal)) { p_destination[name] = newVal; } else if(oldVal is Boolean && oldVal) { p_destination[name] = newVal; } } // dynamic props for(name in p_oldValues) { oldVal = p_oldValues[name]; newVal = p_newValues[name]; if(oldVal is String && oldVal != null) { p_destination[name] = newVal; } else if(oldVal is Number && !isNaN(oldVal)) { p_destination[name] = newVal; } else if(oldVal is Boolean && oldVal) { p_destination[name] = newVal; } } } protected function resetParams():void { if(this.m_lastTrackParams == null) return; this.mergeParams(this.m_config, this.m_tracker, this.m_lastTrackParams); this.mergeParams(this.m_config.Media, this.m_tracker.Media, this.m_lastTrackParams.Media); } protected function setParams(p_params:OmnitureParams):void { this.m_lastTrackParams = p_params; this.mergeParams(p_params, this.m_tracker, p_params); this.mergeParams(p_params.Media, this.m_tracker.Media, p_params.Media); } } } diff --git a/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as b/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as index ae0bafa..3507343 100644 --- a/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as +++ b/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as @@ -1,77 +1,76 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.url { import flash.net.URLRequest; import flash.net.URLRequestMethod; - import flash.net.URLVariables; public class URLTrackParamsXMLDecoder { public function decode(p_XML:XML):Array { var params:Array = []; var requestNode:XML; var requestNodes:XMLList = p_XML.request; var request:URLRequest; for each(requestNode in requestNodes) { request = new URLRequest(requestNode.URL.toString()); if(requestNode.data[0] != null) { request.method = URLRequestMethod.POST; request.data = this.decodeVars(requestNode.data[0]); } params.push(request); } return params; } protected function decodeVars(p_data:XML):Object { if(p_data.hasSimpleContent()) { return p_data.children().toString(); } var vars:Object = {}; var varNode:XML; var varNodes:XMLList = p_data.children(); for each(varNode in varNodes) { vars[varNode.name()] = varNode.children(); } return vars; } } }
dreamsocket/actionscript-analytics-framework
69eff098547aa1a2044e8804ec607175250e4585
[CHG] corrected some of the license header files (made MIT license) [CHG] removed some random traces
diff --git a/bin/daf_google.swf b/bin/daf_google.swf index ac5d6e0..c0b5ff5 100644 Binary files a/bin/daf_google.swf and b/bin/daf_google.swf differ diff --git a/bin/daf_javascript.swf b/bin/daf_javascript.swf index 51899c8..f297d4d 100644 Binary files a/bin/daf_javascript.swf and b/bin/daf_javascript.swf differ diff --git a/bin/daf_omniture.swf b/bin/daf_omniture.swf index 5fb7932..4a958dd 100644 Binary files a/bin/daf_omniture.swf and b/bin/daf_omniture.swf differ diff --git a/bin/daf_url.swf b/bin/daf_url.swf index c3d2c55..87d0a09 100644 Binary files a/bin/daf_url.swf and b/bin/daf_url.swf differ diff --git a/bin/dreamsocket_analytics_0.3.100405.swc b/bin/dreamsocket_analytics_0.3.100405.swc index b51639d..67dcdcf 100644 Binary files a/bin/dreamsocket_analytics_0.3.100405.swc and b/bin/dreamsocket_analytics_0.3.100405.swc differ diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoader.as b/src/com/dreamsocket/analytics/TrackerModuleLoader.as index a0c03a9..8545d2e 100644 --- a/src/com/dreamsocket/analytics/TrackerModuleLoader.as +++ b/src/com/dreamsocket/analytics/TrackerModuleLoader.as @@ -1 +1 @@ -/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.TrackerModuleParams; import com.dreamsocket.analytics.ITrackerModule; import com.dreamsocket.analytics.TrackerModuleLoaderParams; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import flash.display.Loader; import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TrackerModuleLoader extends Sprite { private var m_params:TrackerModuleLoaderParams; private var m_config:XML; private var m_module:ITrackerModule; private var m_configLoader:URLLoader; private var m_moduleLoader:Loader; public function TrackerModuleLoader() { } public function destroy():void { if(this.m_configLoader) { this.m_configLoader.removeEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.close(); } catch(error:Error){} this.m_configLoader = null; } if(this.m_moduleLoader) { this.m_moduleLoader.contentLoaderInfo.removeEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.close(); } catch(error:Error){} try { this.m_moduleLoader.unload(); } catch(error:Error){} this.m_moduleLoader = null; } this.m_params = null; this.m_config = null; this.m_module = null; } public function load(p_resource:TrackerModuleLoaderParams):void { this.destroy(); this.m_params = p_resource; this.loadConfig(); } private function createModule():void { var params:TrackerModuleParams = new TrackerModuleParams(); params.stage = this.m_params.stage; params.config = this.m_config; try { var tracker:ITracker = this.m_module.getTracker(params); var loadParams:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_LOADED, loadParams, tracker)); } catch(error:Error) { trace("moduleLoaded:" + error) this.dispatchError(error.message); } } public function loadConfig():void { if(this.m_params.config is XML) { // this is XML load module this.m_config = this.m_params.config; this.loadModule(); trace("config XML") return; } this.m_configLoader = new URLLoader(); this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { trace("config URL " + this.m_params.config) this.m_configLoader.load(new URLRequest(this.m_params.config)); } catch(error:Error) { trace("loadConfig:" + error) this.dispatchError(error.message); } } private function loadModule():void { if(this.m_params.resource is ITrackerModule) { this.m_module = this.m_params.resource; this.createModule(); return; } // load the module this.m_moduleLoader = new Loader(); this.m_moduleLoader.contentLoaderInfo.addEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.load(new URLRequest(this.m_params.resource)); } catch(error:Error) { trace("loadModule:" +error) this.dispatchError(error.message); } } private function dispatchError(p_message:String):void { trace("---" + p_message) var params:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_FAILED, params)); } private function onErrorOccurred(p_event:ErrorEvent):void { trace(p_event) this.dispatchError(p_event.text); } private function onConfigLoaded(p_event:Event):void { trace("config loaded") try { this.m_config = new XML(this.m_configLoader.data); this.loadModule(); } catch(error:Error) { this.dispatchError(error.message); } } private function onModuleLoaded(p_event:Event):void { this.m_module = ITrackerModule(this.m_moduleLoader.content); this.createModule(); } } } \ No newline at end of file +/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.TrackerModuleParams; import com.dreamsocket.analytics.ITrackerModule; import com.dreamsocket.analytics.TrackerModuleLoaderParams; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import flash.display.Loader; import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TrackerModuleLoader extends Sprite { private var m_params:TrackerModuleLoaderParams; private var m_config:XML; private var m_module:ITrackerModule; private var m_configLoader:URLLoader; private var m_moduleLoader:Loader; public function TrackerModuleLoader() { } public function destroy():void { if(this.m_configLoader) { this.m_configLoader.removeEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.close(); } catch(error:Error){} this.m_configLoader = null; } if(this.m_moduleLoader) { this.m_moduleLoader.contentLoaderInfo.removeEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.close(); } catch(error:Error){} try { this.m_moduleLoader.unload(); } catch(error:Error){} this.m_moduleLoader = null; } this.m_params = null; this.m_config = null; this.m_module = null; } public function load(p_resource:TrackerModuleLoaderParams):void { this.destroy(); this.m_params = p_resource; this.loadConfig(); } private function createModule():void { var params:TrackerModuleParams = new TrackerModuleParams(); params.stage = this.m_params.stage; params.config = this.m_config; try { var tracker:ITracker = this.m_module.getTracker(params); var loadParams:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_LOADED, loadParams, tracker)); } catch(error:Error) { trace("moduleLoaded:" + error) this.dispatchError(error.message); } } public function loadConfig():void { if(this.m_params.config is XML) { // this is XML load module this.m_config = this.m_params.config; this.loadModule(); return; } this.m_configLoader = new URLLoader(); this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.load(new URLRequest(this.m_params.config)); } catch(error:Error) { this.dispatchError(error.message); } } private function loadModule():void { if(this.m_params.resource is ITrackerModule) { this.m_module = this.m_params.resource; this.createModule(); return; } // load the module this.m_moduleLoader = new Loader(); this.m_moduleLoader.contentLoaderInfo.addEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.load(new URLRequest(this.m_params.resource)); } catch(error:Error) { this.dispatchError(error.message); } } private function dispatchError(p_message:String):void { trace(p_message) var params:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_FAILED, params)); } private function onErrorOccurred(p_event:ErrorEvent):void { trace(p_event) this.dispatchError(p_event.text); } private function onConfigLoaded(p_event:Event):void { trace("config loaded") try { this.m_config = new XML(this.m_configLoader.data); this.loadModule(); } catch(error:Error) { this.dispatchError(error.message); } } private function onModuleLoaded(p_event:Event):void { this.m_module = ITrackerModule(this.m_moduleLoader.content); this.createModule(); } } } \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as b/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as index f035ebf..535ee87 100644 --- a/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as +++ b/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as @@ -1,101 +1,99 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import flash.events.Event; import flash.events.EventDispatcher; import com.dreamsocket.analytics.TrackerModuleLoader; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import com.dreamsocket.analytics.TrackerModuleLoaderParams; public class TrackerModuleLoaderQueue extends EventDispatcher { private var m_manifest:Array; private var m_moduleLoader:TrackerModuleLoader; public function TrackerModuleLoaderQueue() { this.m_manifest = []; this.m_moduleLoader = new TrackerModuleLoader(); this.m_moduleLoader.addEventListener(TrackerModuleLoaderEvent.MODULE_LOADED, this.onModuleLoaded); this.m_moduleLoader.addEventListener(TrackerModuleLoaderEvent.MODULE_FAILED, this.onModuleFailed); } public function set manifest(p_value:Array):void { this.m_manifest = p_value; } public function add(p_params:TrackerModuleLoaderParams):void { this.m_manifest.push(p_params); } public function destroy():void { this.m_moduleLoader.destroy(); this.m_manifest.slice(); } public function load():void { var params:TrackerModuleLoaderParams = TrackerModuleLoaderParams(this.m_manifest.shift()); if(params) { this.m_moduleLoader.load(params); } else { - trace("done") this.dispatchEvent(new Event(Event.COMPLETE)); } } private function onModuleFailed(p_event:TrackerModuleLoaderEvent):void { - trace("failed") + trace(p_event) this.load(); } private function onModuleLoaded(p_event:TrackerModuleLoaderEvent):void { - trace("created" + p_event.tracker) TrackerManager.addTracker(p_event.tracker.ID, p_event.tracker); this.load(); } } } diff --git a/src/com/dreamsocket/analytics/google/GoogleBatchParams.as b/src/com/dreamsocket/analytics/google/GoogleBatchParams.as index e40dec2..37cbf01 100644 --- a/src/com/dreamsocket/analytics/google/GoogleBatchParams.as +++ b/src/com/dreamsocket/analytics/google/GoogleBatchParams.as @@ -1,33 +1,42 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ -/** - * Dreamsocket - * - * Copyright 2007 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ package com.dreamsocket.analytics.google { public class GoogleBatchParams { public var data:*; public var handlers:Array; public function GoogleBatchParams() { this.handlers = []; } } } diff --git a/src/com/dreamsocket/analytics/google/GoogleBatchParamsMapper.as b/src/com/dreamsocket/analytics/google/GoogleBatchParamsMapper.as index 67a9ea3..1516a56 100644 --- a/src/com/dreamsocket/analytics/google/GoogleBatchParamsMapper.as +++ b/src/com/dreamsocket/analytics/google/GoogleBatchParamsMapper.as @@ -1,33 +1,42 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ -/** - * Dreamsocket - * - * Copyright 2007 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ package com.dreamsocket.analytics.google { import com.dreamsocket.analytics.google.GoogleBatchParams; public class GoogleBatchParamsMapper { public function map(p_params:GoogleBatchParams, p_data:*):GoogleBatchParams { p_params.data = p_data; return p_params; } } } diff --git a/src/com/dreamsocket/analytics/google/GoogleBatchParamsXMLDecoder.as b/src/com/dreamsocket/analytics/google/GoogleBatchParamsXMLDecoder.as index 1275928..c12fecf 100644 --- a/src/com/dreamsocket/analytics/google/GoogleBatchParamsXMLDecoder.as +++ b/src/com/dreamsocket/analytics/google/GoogleBatchParamsXMLDecoder.as @@ -1,65 +1,74 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ -/** - * Dreamsocket - * - * Copyright 2007 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ package com.dreamsocket.analytics.google { import flash.utils.Dictionary; import com.dreamsocket.analytics.google.GoogleBatchParams; import com.dreamsocket.analytics.google.GoogleTrackHandler; import com.dreamsocket.analytics.google.GoogleTrackEventParamsXMLDecoder; import com.dreamsocket.analytics.google.GoogleTrackPageViewParamsXMLDecoder; public class GoogleBatchParamsXMLDecoder { protected var m_decoders:Dictionary; public function GoogleBatchParamsXMLDecoder() { this.m_decoders = new Dictionary(); this.m_decoders[GoogleTrackType.TRACK_EVENT] = new GoogleTrackEventParamsXMLDecoder(); this.m_decoders[GoogleTrackType.TRACK_PAGE_VIEW] = new GoogleTrackPageViewParamsXMLDecoder(); } public function decode(p_XML:XML):GoogleBatchParams { var handlerNode:XML; var handlerNodes:XMLList = p_XML.handler; var params:GoogleBatchParams = new GoogleBatchParams(); var handler:GoogleTrackHandler; var handlers:Array = params.handlers; var type:String; for each(handlerNode in handlerNodes) { type = handlerNode.type.toString(); if(this.m_decoders[type]) { handler = new GoogleTrackHandler(); handler.type = type; handler.params = this.m_decoders[type].decode(handlerNode.params[0]); handlers.push(handler); } } return params; } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParams.as index b450251..d5f3366 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParams.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParams.as @@ -1,32 +1,41 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ -/** - * Dreamsocket - * - * Copyright 2007 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ package com.dreamsocket.analytics.omniture { public class OmnitureBatchParams { public var handlers:Array; public function OmnitureBatchParams() { this.handlers = []; } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsMapper.as index c899410..ec606e3 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsMapper.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsMapper.as @@ -1,31 +1,40 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ -/** - * Dreamsocket - * - * Copyright 2007 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ package com.dreamsocket.analytics.omniture { import com.dreamsocket.analytics.omniture.OmnitureBatchParams; public class OmnitureBatchParamsMapper { public function map(p_params:OmnitureBatchParams, p_data:*):OmnitureBatchParams { return p_params; } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsXMLDecoder.as index fd8c20a..d9deeb9 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsXMLDecoder.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsXMLDecoder.as @@ -1,76 +1,85 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ -/** - * Dreamsocket - * - * Copyright 2007 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ package com.dreamsocket.analytics.omniture { import flash.utils.Dictionary; import com.dreamsocket.analytics.omniture.OmnitureBatchParams; import com.dreamsocket.analytics.omniture.OmnitureTrackHandler; import com.dreamsocket.analytics.omniture.OmnitureTrackParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaStopParamsXMLDecoder; public class OmnitureBatchParamsXMLDecoder { protected var m_decoders:Dictionary; public function OmnitureBatchParamsXMLDecoder() { this.m_decoders = new Dictionary(); this.m_decoders[OmnitureTrackType.TRACK] = new OmnitureTrackParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.TRACK_LINK] = new OmnitureTrackLinkParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_TRACK] = new OmnitureMediaTrackParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_CLOSE] = new OmnitureMediaCloseParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_OPEN] = new OmnitureMediaOpenParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_PLAY] = new OmnitureMediaPlayParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_STOP] = new OmnitureMediaStopParamsXMLDecoder(); } public function decode(p_XML:XML):OmnitureBatchParams { var handlerNode:XML; var handlerNodes:XMLList = p_XML.handler; var params:OmnitureBatchParams = new OmnitureBatchParams(); var handler:OmnitureTrackHandler; var handlers:Array = params.handlers; var type:String; for each(handlerNode in handlerNodes) { type = handlerNode.type.toString(); if(this.m_decoders[type]) { handler = new OmnitureTrackHandler(); handler.type = type; handler.params = this.m_decoders[type].decode(handlerNode.params[0]); handlers.push(handler); } } return params; } } } diff --git a/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as b/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as index 52c5fcd..ae0bafa 100644 --- a/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as +++ b/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as @@ -1,68 +1,77 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ -/** - * Dreamsocket - * - * Copyright 2007 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ package com.dreamsocket.analytics.url { import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; public class URLTrackParamsXMLDecoder { public function decode(p_XML:XML):Array { var params:Array = []; var requestNode:XML; var requestNodes:XMLList = p_XML.request; var request:URLRequest; for each(requestNode in requestNodes) { request = new URLRequest(requestNode.URL.toString()); if(requestNode.data[0] != null) { request.method = URLRequestMethod.POST; request.data = this.decodeVars(requestNode.data[0]); } params.push(request); } return params; } protected function decodeVars(p_data:XML):Object { if(p_data.hasSimpleContent()) { return p_data.children().toString(); } var vars:Object = {}; var varNode:XML; var varNodes:XMLList = p_data.children(); for each(varNode in varNodes) { vars[varNode.name()] = varNode.children(); } return vars; } } }
dreamsocket/actionscript-analytics-framework
9913dd83dd5c02aa724e61cbba5d01938edbef76
[CHG] made default size of swfs 1x1
diff --git a/build.xml b/build.xml index 34b0687..ed74cb5 100644 --- a/build.xml +++ b/build.xml @@ -1,117 +1,117 @@ <?xml version="1.0" encoding="UTF-8"?> <project name="dreamsocket_actionscript_analytics" default="buildAll" basedir="."> <!-- FLEX TASKS --> <property name="FLEX_HOME" value="/tools/flash/flexsdk/4_0"/> <taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> <tstamp><format property="build.date" pattern="yyMMdd" locale="en"/></tstamp> <property name="build.version.major" value="0" /> <property name="build.version.minor" value="3" /> <property name="build.version.build" value="0" /> <!-- DIRECTORIES --> <property name="project.libs" value="${basedir}/libs/"/> <property name="project.output" value="${basedir}/bin/" /> <property name="project.src" value="${basedir}/src/" /> <property name="project.name" value="dreamsocket_analytics" /> <property name="swf.framerate" value="31" /> - <property name="swf.width" value="480" /> - <property name="swf.height" value="320" /> + <property name="swf.width" value="1" /> + <property name="swf.height" value="1" /> <!-- BUILD ALL --> <target name="buildAll" depends="clean,buildSWC,buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD ALL PLUGINS --> <target name="buildAllModules" depends="buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD GOOGLE PLUGIN --> <target name="buildGoogleModule"> <antcall target="compileModule"> <param name="module.name" value="daf_google" /> <param name="module.class" value="com/dreamsocket/analytics/google/GoogleTrackerModule.as" /> </antcall> </target> <!-- BUILD JAVASCRIPT PLUGIN --> <target name="buildJavaScriptModule"> <antcall target="compileModule"> <param name="module.name" value="daf_javascript" /> <param name="module.class" value="com/dreamsocket/analytics/js/JSTrackerModule.as" /> </antcall> </target> <!-- BUILD OMNITURE PLUGIN --> <target name="buildOmnitureModule"> <antcall target="compileModule"> <param name="module.name" value="daf_omniture" /> <param name="module.class" value="com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as" /> </antcall> </target> <!-- BUILD URL PLUGIN --> <target name="buildURLModule"> <antcall target="compileModule"> <param name="module.name" value="daf_url" /> <param name="module.class" value="com/dreamsocket/analytics/url/URLTrackerModule.as" /> </antcall> </target> <!-- COMPILE SWC --> <target name="buildSWC"> <compc output="${project.output}/${project.name}_${build.version.major}.${build.version.minor}.${build.date}.swc"> <external-library-path dir="${project.libs}/" append="true" includes="**" /> <include-sources dir="${project.src}" includes="**"/> </compc> </target> <!-- COMPILE PLUGIN--> <target name="compileModule"> <mxmlc file="${project.src}${module.class}" output="${project.output}${module.name}.swf" strict="true" static-link-runtime-shared-libraries="true" > <default-size width="1" height="1" /> <source-path path-element="${project.src}"/> <compiler.library-path dir="${basedir}" append="true"> <include name="libs" /> </compiler.library-path> </mxmlc> </target> <!-- CLEAN --> <target name="clean"> <mkdir dir="${project.output}"/> <delete> <fileset dir="${project.output}" includes="**"/> </delete> </target> <!-- PACKAGE --> <target name="package" depends="buildAll"> <zip update="true" destfile="${project.output}${project.name}_${build.version.major}.${build.version.minor}.${build.date}.zip" > <zipfileset dir="${basedir}" includes="bin/**,libs/**,src/**,test/**,build.xml" /> </zip> </target> </project>
dreamsocket/actionscript-analytics-framework
b3931514e8a65b81b2483cc1b28c059dc09ecb89
[FIX] adding TestOmnitureMediaTracking with a change, GitHub wasn't recognizing an ammendment
diff --git a/test/TestOmnitureMediaTracking.as b/test/TestOmnitureMediaTracking.as index 135f1db..4cff893 100644 --- a/test/TestOmnitureMediaTracking.as +++ b/test/TestOmnitureMediaTracking.as @@ -1,122 +1,122 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package { import flash.events.MouseEvent; import com.dreamsocket.analytics.Track; import com.dreamsocket.analytics.omniture.OmnitureTrackerConfig; import com.dreamsocket.analytics.omniture.OmnitureTrackerConfigXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureTracker; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TestOmnitureMediaTracking extends Sprite { private var m_loader:URLLoader; private var m_tracker:OmnitureTracker; public var requestBtn:Object; public var startBtn:Object; public var playBtn:Object; public var pauseBtn:Object; public var closeBtn:Object; public function TestOmnitureMediaTracking() { this.m_loader = new URLLoader(); this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); this.m_loader.load(new URLRequest("test_omniture_media.xml")); this.requestBtn.addEventListener(MouseEvent.CLICK, this.onRequestClicked); this.startBtn.addEventListener(MouseEvent.CLICK, this.onStartClicked); this.playBtn.addEventListener(MouseEvent.CLICK, this.onPlayClicked); this.pauseBtn.addEventListener(MouseEvent.CLICK, this.onPauseClicked); this.closeBtn.addEventListener(MouseEvent.CLICK, this.onCloseClicked); } private function onErrorOccurred(p_event:Event):void { trace(p_event); } private function onRequestClicked(p_event:MouseEvent):void { this.m_tracker.track(new Track("mediaRequested", {duration:120, position:0, title:"testid"})); } private function onStartClicked(p_event:MouseEvent):void { this.m_tracker.track(new Track("mediaStarted", {duration:120, position:0, title:"testid"})); } private function onPlayClicked(p_event:MouseEvent):void { this.m_tracker.track(new Track("mediaPlaying", {duration:120, position:30, title:"testid"})); } private function onPauseClicked(p_event:MouseEvent):void { this.m_tracker.track(new Track("mediaPaused", {duration:120, position:30, title:"testid"})); } private function onCloseClicked(p_event:MouseEvent):void { this.m_tracker.track(new Track("mediaClosed", {duration:120, position:0, title:"testid"})); } private function onXMLLoaded(p_event:Event):void { var config:OmnitureTrackerConfig = new OmnitureTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); this.m_tracker = new OmnitureTracker(this.stage); this.m_tracker.config = config; this.m_tracker.track(new Track("mediaRequested", {duration:120, title:"testid", position:0})); this.m_tracker.track(new Track("mediaStarted", {duration:120, title:"testid", position:0})); this.m_tracker.track(new Track("mediaPaused", {position:30, title:"testid"})); this.m_tracker.track(new Track("mediaPlaying", {position:30, title:"testid"})); this.m_tracker.track(new Track("mediaClosed", {position:110, title:"testid"})); } } -} +} \ No newline at end of file
dreamsocket/actionscript-analytics-framework
a900fe8488889678b51f37c2be756d9ffe8cda2f
[FIX] added TestOmnitureMediaTracking.as that was missing before [NEW] added batch type for Google and Omniture allowing multiple calls for an ID [NEW] added ability to do POST data requests (raw string or name/value pairs) [CHG] removed mediaOffset from OmnitureMediaCloseParams since this wasn't inline with native call [CHG] made Omniture media close call only call that method (also called stop before) [CHG] added mapping of params for Google changin it from a switch to lookup [CHG] updated build minor to 3 due to XML differences with URLs and additional APIs [CHG] renamed type property in Track to ID to match with XML
diff --git a/bin/daf_google.swf b/bin/daf_google.swf index d87ff7b..ac5d6e0 100644 Binary files a/bin/daf_google.swf and b/bin/daf_google.swf differ diff --git a/bin/daf_javascript.swf b/bin/daf_javascript.swf index 4ec3466..51899c8 100644 Binary files a/bin/daf_javascript.swf and b/bin/daf_javascript.swf differ diff --git a/bin/daf_omniture.swf b/bin/daf_omniture.swf index 319fc15..5fb7932 100644 Binary files a/bin/daf_omniture.swf and b/bin/daf_omniture.swf differ diff --git a/bin/daf_url.swf b/bin/daf_url.swf index b24e2c3..c3d2c55 100644 Binary files a/bin/daf_url.swf and b/bin/daf_url.swf differ diff --git a/bin/dreamsocket_analytics_0.2.100402.swc b/bin/dreamsocket_analytics_0.2.100402.swc deleted file mode 100644 index 5a1eccf..0000000 Binary files a/bin/dreamsocket_analytics_0.2.100402.swc and /dev/null differ diff --git a/bin/dreamsocket_analytics_0.3.100405.swc b/bin/dreamsocket_analytics_0.3.100405.swc new file mode 100644 index 0000000..b51639d Binary files /dev/null and b/bin/dreamsocket_analytics_0.3.100405.swc differ diff --git a/build.xml b/build.xml index 1d854d3..34b0687 100644 --- a/build.xml +++ b/build.xml @@ -1,117 +1,117 @@ <?xml version="1.0" encoding="UTF-8"?> <project name="dreamsocket_actionscript_analytics" default="buildAll" basedir="."> <!-- FLEX TASKS --> <property name="FLEX_HOME" value="/tools/flash/flexsdk/4_0"/> <taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> <tstamp><format property="build.date" pattern="yyMMdd" locale="en"/></tstamp> <property name="build.version.major" value="0" /> - <property name="build.version.minor" value="2" /> + <property name="build.version.minor" value="3" /> <property name="build.version.build" value="0" /> <!-- DIRECTORIES --> <property name="project.libs" value="${basedir}/libs/"/> <property name="project.output" value="${basedir}/bin/" /> <property name="project.src" value="${basedir}/src/" /> <property name="project.name" value="dreamsocket_analytics" /> <property name="swf.framerate" value="31" /> <property name="swf.width" value="480" /> <property name="swf.height" value="320" /> <!-- BUILD ALL --> <target name="buildAll" depends="clean,buildSWC,buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD ALL PLUGINS --> <target name="buildAllModules" depends="buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> <!-- BUILD GOOGLE PLUGIN --> <target name="buildGoogleModule"> <antcall target="compileModule"> <param name="module.name" value="daf_google" /> <param name="module.class" value="com/dreamsocket/analytics/google/GoogleTrackerModule.as" /> </antcall> </target> <!-- BUILD JAVASCRIPT PLUGIN --> <target name="buildJavaScriptModule"> <antcall target="compileModule"> <param name="module.name" value="daf_javascript" /> <param name="module.class" value="com/dreamsocket/analytics/js/JSTrackerModule.as" /> </antcall> </target> <!-- BUILD OMNITURE PLUGIN --> <target name="buildOmnitureModule"> <antcall target="compileModule"> <param name="module.name" value="daf_omniture" /> <param name="module.class" value="com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as" /> </antcall> </target> <!-- BUILD URL PLUGIN --> <target name="buildURLModule"> <antcall target="compileModule"> <param name="module.name" value="daf_url" /> <param name="module.class" value="com/dreamsocket/analytics/url/URLTrackerModule.as" /> </antcall> </target> <!-- COMPILE SWC --> <target name="buildSWC"> <compc output="${project.output}/${project.name}_${build.version.major}.${build.version.minor}.${build.date}.swc"> <external-library-path dir="${project.libs}/" append="true" includes="**" /> <include-sources dir="${project.src}" includes="**"/> </compc> </target> <!-- COMPILE PLUGIN--> <target name="compileModule"> <mxmlc file="${project.src}${module.class}" output="${project.output}${module.name}.swf" strict="true" static-link-runtime-shared-libraries="true" > <default-size width="1" height="1" /> <source-path path-element="${project.src}"/> <compiler.library-path dir="${basedir}" append="true"> <include name="libs" /> </compiler.library-path> </mxmlc> </target> <!-- CLEAN --> <target name="clean"> <mkdir dir="${project.output}"/> <delete> <fileset dir="${project.output}" includes="**"/> </delete> </target> <!-- PACKAGE --> <target name="package" depends="buildAll"> <zip update="true" destfile="${project.output}${project.name}_${build.version.major}.${build.version.minor}.${build.date}.zip" > <zipfileset dir="${basedir}" includes="bin/**,libs/**,src/**,test/**,build.xml" /> </zip> </target> </project> diff --git a/src/com/dreamsocket/analytics/ITrack.as b/src/com/dreamsocket/analytics/ITrack.as index 0dec3cf..77827a4 100644 --- a/src/com/dreamsocket/analytics/ITrack.as +++ b/src/com/dreamsocket/analytics/ITrack.as @@ -1,37 +1,37 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { public interface ITrack { function get data():*; - function get type():String; + function get ID():String; } } diff --git a/src/com/dreamsocket/analytics/Track.as b/src/com/dreamsocket/analytics/Track.as index 75e86de..d36d6ab 100644 --- a/src/com/dreamsocket/analytics/Track.as +++ b/src/com/dreamsocket/analytics/Track.as @@ -1,56 +1,56 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import com.dreamsocket.analytics.ITrack; public class Track implements ITrack { protected var m_data:*; - protected var m_type:String; + protected var m_ID:String; - public function Track(p_type:String, p_data:* = null) + public function Track(p_ID:String, p_data:* = null) { - this.m_type = p_type; + this.m_ID = p_ID; this.m_data = p_data; } public function get data():* { return this.m_data; } - public function get type():String + public function get ID():String { - return this.m_type; + return this.m_ID; } } } diff --git a/src/com/dreamsocket/analytics/google/GoogleBatchParams.as b/src/com/dreamsocket/analytics/google/GoogleBatchParams.as new file mode 100644 index 0000000..e40dec2 --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleBatchParams.as @@ -0,0 +1,33 @@ + + +/** + * Dreamsocket + * + * Copyright 2007 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ +package com.dreamsocket.analytics.google +{ + + public class GoogleBatchParams + { + public var data:*; + public var handlers:Array; + + public function GoogleBatchParams() + { + this.handlers = []; + } + } +} diff --git a/src/com/dreamsocket/analytics/google/GoogleBatchParamsMapper.as b/src/com/dreamsocket/analytics/google/GoogleBatchParamsMapper.as new file mode 100644 index 0000000..67a9ea3 --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleBatchParamsMapper.as @@ -0,0 +1,33 @@ + + +/** + * Dreamsocket + * + * Copyright 2007 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ +package com.dreamsocket.analytics.google +{ + import com.dreamsocket.analytics.google.GoogleBatchParams; + + public class GoogleBatchParamsMapper + { + public function map(p_params:GoogleBatchParams, p_data:*):GoogleBatchParams + { + p_params.data = p_data; + + return p_params; + } + } +} diff --git a/src/com/dreamsocket/analytics/google/GoogleBatchParamsXMLDecoder.as b/src/com/dreamsocket/analytics/google/GoogleBatchParamsXMLDecoder.as new file mode 100644 index 0000000..1275928 --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleBatchParamsXMLDecoder.as @@ -0,0 +1,65 @@ + + +/** + * Dreamsocket + * + * Copyright 2007 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ +package com.dreamsocket.analytics.google +{ + import flash.utils.Dictionary; + + import com.dreamsocket.analytics.google.GoogleBatchParams; + import com.dreamsocket.analytics.google.GoogleTrackHandler; + import com.dreamsocket.analytics.google.GoogleTrackEventParamsXMLDecoder; + import com.dreamsocket.analytics.google.GoogleTrackPageViewParamsXMLDecoder; + + public class GoogleBatchParamsXMLDecoder + { + protected var m_decoders:Dictionary; + + public function GoogleBatchParamsXMLDecoder() + { + this.m_decoders = new Dictionary(); + this.m_decoders[GoogleTrackType.TRACK_EVENT] = new GoogleTrackEventParamsXMLDecoder(); + this.m_decoders[GoogleTrackType.TRACK_PAGE_VIEW] = new GoogleTrackPageViewParamsXMLDecoder(); + } + + + public function decode(p_XML:XML):GoogleBatchParams + { + var handlerNode:XML; + var handlerNodes:XMLList = p_XML.handler; + var params:GoogleBatchParams = new GoogleBatchParams(); + var handler:GoogleTrackHandler; + var handlers:Array = params.handlers; + var type:String; + + for each(handlerNode in handlerNodes) + { + type = handlerNode.type.toString(); + if(this.m_decoders[type]) + { + handler = new GoogleTrackHandler(); + handler.type = type; + handler.params = this.m_decoders[type].decode(handlerNode.params[0]); + handlers.push(handler); + } + } + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackEventParamsMapper.as b/src/com/dreamsocket/analytics/google/GoogleTrackEventParamsMapper.as new file mode 100644 index 0000000..f61d72f --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleTrackEventParamsMapper.as @@ -0,0 +1,54 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + + +package com.dreamsocket.analytics.google +{ + import com.dreamsocket.analytics.google.GoogleTrackEventParams; + import com.dreamsocket.utils.PropertyStringUtil; + + public class GoogleTrackEventParamsMapper + { + public function GoogleTrackEventParamsMapper() + { + } + + public function map(p_params:GoogleTrackEventParams, p_data:*):GoogleTrackEventParams + { + var mapped:GoogleTrackEventParams = new GoogleTrackEventParams(); + + mapped.category = PropertyStringUtil.evalPropertyString(p_data, p_params.category); + mapped.action = PropertyStringUtil.evalPropertyString(p_data, p_params.action); + mapped.label = PropertyStringUtil.evalPropertyString(p_data, p_params.label); + mapped.value = (PropertyStringUtil.evalPropertyString(p_data, p_params.value)); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackPageViewParamsMapper.as b/src/com/dreamsocket/analytics/google/GoogleTrackPageViewParamsMapper.as new file mode 100644 index 0000000..4cfc8b4 --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleTrackPageViewParamsMapper.as @@ -0,0 +1,51 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + + +package com.dreamsocket.analytics.google +{ + import com.dreamsocket.analytics.google.GoogleTrackPageViewParams; + import com.dreamsocket.utils.PropertyStringUtil; + + public class GoogleTrackPageViewParamsMapper + { + public function GoogleTrackPageViewParamsMapper() + { + } + + public function map(p_params:GoogleTrackPageViewParams, p_data:*):GoogleTrackPageViewParams + { + var mapped:GoogleTrackPageViewParams = new GoogleTrackPageViewParams(); + + mapped.URL = PropertyStringUtil.evalPropertyString(p_data, p_params.URL); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackType.as b/src/com/dreamsocket/analytics/google/GoogleTrackType.as index 5bc3ee5..380c605 100644 --- a/src/com/dreamsocket/analytics/google/GoogleTrackType.as +++ b/src/com/dreamsocket/analytics/google/GoogleTrackType.as @@ -1,36 +1,37 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.google { public class GoogleTrackType { + public static const BATCH:String = "batch"; public static const TRACK_PAGE_VIEW:String = "trackPageView"; public static const TRACK_EVENT:String = "trackEvent"; } -} \ No newline at end of file +} diff --git a/src/com/dreamsocket/analytics/google/GoogleTracker.as b/src/com/dreamsocket/analytics/google/GoogleTracker.as index abe1f78..b9ba5e9 100644 --- a/src/com/dreamsocket/analytics/google/GoogleTracker.as +++ b/src/com/dreamsocket/analytics/google/GoogleTracker.as @@ -1,172 +1,195 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.google { import flash.display.Stage; import flash.utils.Dictionary; - - import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.analytics.ITrack; import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.google.GoogleBatchParamsMapper; import com.dreamsocket.analytics.google.GoogleSingleton; import com.dreamsocket.analytics.google.GoogleTrackerConfig; + import com.dreamsocket.analytics.google.GoogleTrackEventParamsMapper; + import com.dreamsocket.analytics.google.GoogleTrackPageViewParamsMapper; import com.dreamsocket.analytics.google.GoogleTrackHandler; + import com.dreamsocket.analytics.google.GoogleTrackType; import com.google.analytics.GATracker; public class GoogleTracker implements ITracker { public static const ID:String = "GoogleTracker"; protected var m_config:GoogleTrackerConfig; protected var m_enabled:Boolean; protected var m_service:GATracker; protected var m_handlers:Dictionary; + protected var m_functions:Dictionary; + protected var m_paramMappers:Dictionary; public function GoogleTracker(p_stage:Stage = null) { super(); GoogleSingleton.stage = p_stage; this.m_config = new GoogleTrackerConfig(); this.m_enabled = true; this.m_handlers = new Dictionary(); + + this.m_functions = new Dictionary(); + this.m_functions[GoogleTrackType.TRACK_EVENT] = this.trackEvent; + this.m_functions[GoogleTrackType.TRACK_PAGE_VIEW] = this.trackPageview; + this.m_functions[GoogleTrackType.BATCH] = this.batch; + + this.m_paramMappers = new Dictionary(); + this.m_paramMappers[GoogleTrackType.TRACK_EVENT] = new GoogleTrackEventParamsMapper(); + this.m_paramMappers[GoogleTrackType.TRACK_PAGE_VIEW] = new GoogleTrackPageViewParamsMapper(); + this.m_paramMappers[GoogleTrackType.BATCH] = new GoogleBatchParamsMapper(); } public function get config():GoogleTrackerConfig { return this.m_config; } public function set config(p_value:GoogleTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; try { this.m_service = GoogleSingleton.create(p_value.account, p_value.trackingMode, p_value.visualDebug); } catch(error:Error) { trace(error); } this.m_enabled = p_value.enabled; this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function get ID():String { return GoogleTracker.ID; } public function addTrackHandler(p_ID:String, p_handler:GoogleTrackHandler):void { this.m_handlers[p_ID] = p_handler; } public function destroy():void { } public function getTrackHandler(p_ID:String):GoogleTrackHandler { return this.m_handlers[p_ID] as GoogleTrackHandler; } public function removeTrackHandler(p_ID:String):void { delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled || this.m_service == null) return; - var handler:GoogleTrackHandler = this.m_config.handlers[p_track.type]; - - - if(handler != null) + var handler:GoogleTrackHandler = this.m_config.handlers[p_track.ID]; + + if(handler == null) return; + this.doTrack(handler, p_track.data); + } + + + protected function doTrack(p_handler:GoogleTrackHandler, p_data:*):void + { + if(p_handler.params != null && this.m_paramMappers[p_handler.type] != null && this.m_functions[p_handler.type]) { // has a track handler - // call correct track method - switch(handler.type) + try { - case GoogleTrackType.TRACK_EVENT: - var category:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.params.category); - var action:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.params.action); - var label:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.params.label); - var value:Number = Number(PropertyStringUtil.evalPropertyString(p_track.data, handler.params.value)); - - try - { - this.m_service.trackEvent(category, action, label, value); - } - catch(error:Error) - { - trace(error); - } - break; - case GoogleTrackType.TRACK_PAGE_VIEW: - try - { - this.m_service.trackPageview(PropertyStringUtil.evalPropertyString(p_track.data, handler.params.URL)); - } - catch(error:Error) - { - trace(error); - } - break; + this.m_functions[p_handler.type](this.m_paramMappers[p_handler.type].map(p_handler.params, p_data)); + } + catch(error:Error) + { + trace(error); } + } + } + + + protected function batch(p_params:GoogleBatchParams):void + { + var i:uint = 0; + var len:uint = p_params.handlers.length; + while(i < len) + { + this.doTrack(GoogleTrackHandler(p_params.handlers[i++]), p_params.data); } } + + + protected function trackEvent(p_params:GoogleTrackEventParams):void + { + this.m_service.trackEvent(p_params.category, p_params.action, p_params.label, Number(p_params.value)); + } + + + protected function trackPageview(p_params:GoogleTrackPageViewParams):void + { + this.m_service.trackPageview(p_params.URL); + } } } diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackerConfigXMLDecoder.as b/src/com/dreamsocket/analytics/google/GoogleTrackerConfigXMLDecoder.as index 8cc01d3..0caa5d7 100644 --- a/src/com/dreamsocket/analytics/google/GoogleTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/analytics/google/GoogleTrackerConfigXMLDecoder.as @@ -1,98 +1,101 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.google { import flash.utils.Dictionary; + import com.dreamsocket.analytics.google.GoogleBatchParamsXMLDecoder; import com.dreamsocket.analytics.google.GoogleTrackerConfig; import com.dreamsocket.analytics.google.GoogleTrackHandler; import com.dreamsocket.analytics.google.GoogleTrackEventParamsXMLDecoder; import com.dreamsocket.analytics.google.GoogleTrackPageViewParamsXMLDecoder; import com.dreamsocket.analytics.google.GoogleTrackType; import com.google.analytics.core.TrackerMode; public class GoogleTrackerConfigXMLDecoder { protected var m_decoders:Dictionary; public function GoogleTrackerConfigXMLDecoder() { super(); this.m_decoders = new Dictionary(); + + this.m_decoders[GoogleTrackType.BATCH] = new GoogleBatchParamsXMLDecoder(); this.m_decoders[GoogleTrackType.TRACK_EVENT] = new GoogleTrackEventParamsXMLDecoder(); this.m_decoders[GoogleTrackType.TRACK_PAGE_VIEW] = new GoogleTrackPageViewParamsXMLDecoder(); } public function decode(p_XML:XML):GoogleTrackerConfig { var config:GoogleTrackerConfig = new GoogleTrackerConfig(); if(p_XML.account.toString().length) config.account = p_XML.account.toString(); config.enabled = p_XML.enabled.toString() != "false"; config.trackingMode = p_XML.trackingMode.toString() == TrackerMode.AS3 ? TrackerMode.AS3 : TrackerMode.BRIDGE; config.visualDebug = p_XML.visualDebug.toString() != "false"; - this.setTrackHandlers(config.handlers, p_XML.handlers.handler); + this.createHandlers(config.handlers, p_XML.handlers.handler); return config; } - public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void + protected function createHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void { var handler:GoogleTrackHandler; var handlerNode:XML; var ID:String; for each(handlerNode in p_handlerNodes) { ID = handlerNode.ID.toString(); if(ID.length > 0) { handler = new GoogleTrackHandler(); handler.ID = ID; handler.type = handlerNode.type.toString(); - + if(this.m_decoders[handler.type]) { - handler.params = this.m_decoders[handler.type].decode(handlerNode.params[0]); - p_handlers[ID] = handler; + handler.params = this.m_decoders[handler.type].decode(handlerNode.params[0]); } + p_handlers[ID] = handler; } } - } + } } } diff --git a/src/com/dreamsocket/analytics/js/JSTracker.as b/src/com/dreamsocket/analytics/js/JSTracker.as index 24ca423..50a9eea 100644 --- a/src/com/dreamsocket/analytics/js/JSTracker.as +++ b/src/com/dreamsocket/analytics/js/JSTracker.as @@ -1,151 +1,151 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.js { import flash.external.ExternalInterface; import flash.utils.Dictionary; import com.dreamsocket.utils.PropertyStringUtil; import com.dreamsocket.analytics.ITrack; import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.js.JSTrackerConfig; import com.dreamsocket.analytics.js.JSTrackHandler; public class JSTracker implements ITracker { public static const ID:String = "JSTracker"; protected var m_config:JSTrackerConfig; protected var m_enabled:Boolean; protected var m_handlers:Dictionary; public function JSTracker() { super(); this.m_config = new JSTrackerConfig(); this.m_enabled = true; this.m_handlers = new Dictionary(); } public function get config():JSTrackerConfig { return this.m_config; } public function set config(p_value:JSTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; this.m_enabled = p_value.enabled; this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function get ID():String { return JSTracker.ID; } public function addTrackHandler(p_ID:String, p_handler:JSTrackHandler):void { this.m_handlers[p_ID] = p_handler; } public function getTrackHandler(p_ID:String):JSTrackHandler { return this.m_handlers[p_ID] as JSTrackHandler; } public function removeTrackHandler(p_ID:String):void { delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled) return; - var handler:JSTrackHandler = this.m_handlers[p_track.type]; + var handler:JSTrackHandler = this.m_handlers[p_track.ID]; if(handler != null) { // has the track type this.performJSCall(handler.params, p_track.data); } } protected function performJSCall(p_methodCall:JSTrackParams, p_data:* = null):void { if(ExternalInterface.available) { try { var args:Array = p_methodCall.arguments.concat(); var i:int = args.length; while(i--) { args[i] = PropertyStringUtil.evalPropertyString(p_data, args[i]); } args.unshift(p_methodCall.method); ExternalInterface.call.apply(ExternalInterface, args); } catch(error:Error) { // do nothing trace("JSTracker.track - " + error); } } } } } \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParams.as new file mode 100644 index 0000000..b450251 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParams.as @@ -0,0 +1,32 @@ + + +/** + * Dreamsocket + * + * Copyright 2007 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ +package com.dreamsocket.analytics.omniture +{ + + public class OmnitureBatchParams + { + public var handlers:Array; + + public function OmnitureBatchParams() + { + this.handlers = []; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsMapper.as new file mode 100644 index 0000000..c899410 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsMapper.as @@ -0,0 +1,31 @@ + + +/** + * Dreamsocket + * + * Copyright 2007 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureBatchParams; + + public class OmnitureBatchParamsMapper + { + public function map(p_params:OmnitureBatchParams, p_data:*):OmnitureBatchParams + { + return p_params; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsXMLDecoder.as new file mode 100644 index 0000000..fd8c20a --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureBatchParamsXMLDecoder.as @@ -0,0 +1,76 @@ + + +/** + * Dreamsocket + * + * Copyright 2007 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ +package com.dreamsocket.analytics.omniture +{ + import flash.utils.Dictionary; + + import com.dreamsocket.analytics.omniture.OmnitureBatchParams; + import com.dreamsocket.analytics.omniture.OmnitureTrackHandler; + import com.dreamsocket.analytics.omniture.OmnitureTrackParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaStopParamsXMLDecoder; + + + public class OmnitureBatchParamsXMLDecoder + { + protected var m_decoders:Dictionary; + + public function OmnitureBatchParamsXMLDecoder() + { + this.m_decoders = new Dictionary(); + this.m_decoders[OmnitureTrackType.TRACK] = new OmnitureTrackParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.TRACK_LINK] = new OmnitureTrackLinkParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_TRACK] = new OmnitureMediaTrackParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_CLOSE] = new OmnitureMediaCloseParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_OPEN] = new OmnitureMediaOpenParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_PLAY] = new OmnitureMediaPlayParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_STOP] = new OmnitureMediaStopParamsXMLDecoder(); + } + + + public function decode(p_XML:XML):OmnitureBatchParams + { + var handlerNode:XML; + var handlerNodes:XMLList = p_XML.handler; + var params:OmnitureBatchParams = new OmnitureBatchParams(); + var handler:OmnitureTrackHandler; + var handlers:Array = params.handlers; + var type:String; + + for each(handlerNode in handlerNodes) + { + type = handlerNode.type.toString(); + if(this.m_decoders[type]) + { + handler = new OmnitureTrackHandler(); + handler.type = type; + handler.params = this.m_decoders[type].decode(handlerNode.params[0]); + handlers.push(handler); + } + } + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParams.as index 694b831..dedfa52 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParams.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParams.as @@ -1,44 +1,43 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import com.dreamsocket.analytics.omniture.OmnitureParams; public class OmnitureMediaCloseParams { public var mediaName:String; - public var mediaOffset:String; public var params:OmnitureParams; public function OmnitureMediaCloseParams() { this.params = new OmnitureParams(); } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsMapper.as index 65048c4..99b3daa 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsMapper.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsMapper.as @@ -1,54 +1,53 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParams; import com.dreamsocket.analytics.omniture.OmnitureParamsMapper; import com.dreamsocket.utils.PropertyStringUtil; public class OmnitureMediaCloseParamsMapper { public function OmnitureMediaCloseParamsMapper() { } public function map(p_params:OmnitureMediaCloseParams, p_data:*):OmnitureMediaCloseParams { var mapped:OmnitureMediaCloseParams = new OmnitureMediaCloseParams(); mapped.mediaName = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaName); - mapped.mediaOffset = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaOffset); mapped.params = new OmnitureParamsMapper().map(p_params.params, p_data); return mapped; } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsXMLDecoder.as index b7109a7..de5e34b 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsXMLDecoder.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsXMLDecoder.as @@ -1,51 +1,49 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParams; import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; public class OmnitureMediaCloseParamsXMLDecoder { public function decode(p_XML:XML):OmnitureMediaCloseParams { var params:OmnitureMediaCloseParams = new OmnitureMediaCloseParams(); if(p_XML.mediaName.toString().length) params.mediaName = p_XML.mediaName.toString(); - if(p_XML.mediaOffset.toString().length) - params.mediaOffset = p_XML.mediaOffset.toString(); params.params = new OmnitureParamsXMLDecoder().decode(p_XML.params[0]); return params; } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureService.as b/src/com/dreamsocket/analytics/omniture/OmnitureService.as index 7c94480..6a8534e 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureService.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureService.as @@ -1,241 +1,244 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import flash.display.Stage; import flash.utils.describeType; import flash.utils.Dictionary; import com.dreamsocket.analytics.omniture.OmnitureParams; import com.dreamsocket.analytics.omniture.OmnitureSingleton; import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParams; import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParams; import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParams; import com.dreamsocket.analytics.omniture.OmnitureMediaStopParams; import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParams; import com.dreamsocket.analytics.omniture.OmnitureTrackParams; import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParams; import com.dreamsocket.analytics.omniture.OmnitureTrackType; import com.omniture.ActionSource; public class OmnitureService { protected var m_config:OmnitureParams; protected var m_enabled:Boolean; protected var m_lastTrackParams:OmnitureParams; protected var m_tracker:ActionSource; protected var m_functions:Dictionary; public function OmnitureService(p_stage:Stage = null) { this.m_tracker = OmnitureSingleton.create(p_stage); this.m_enabled = true; this.m_functions = new Dictionary(); this.m_functions[OmnitureTrackType.MEDIA_CLOSE] = this.trackMediaClose; this.m_functions[OmnitureTrackType.MEDIA_OPEN] = this.trackMediaOpen; this.m_functions[OmnitureTrackType.MEDIA_PLAY] = this.trackMediaPlay; this.m_functions[OmnitureTrackType.MEDIA_STOP] = this.trackMediaStop; this.m_functions[OmnitureTrackType.MEDIA_TRACK] = this.trackMedia; this.m_functions[OmnitureTrackType.TRACK] = this.trackEvent; this.m_functions[OmnitureTrackType.TRACK_LINK] = this.trackLink; } public function get config():OmnitureParams { return this.m_config; } public function set config(p_config:OmnitureParams):void { if(p_config != this.m_config) { this.mergeParams(p_config, this.m_tracker, this.m_config == null ? p_config : this.m_config); this.mergeParams(p_config.Media, this.m_tracker.Media, this.m_config == null ? p_config.Media : this.m_config.Media); this.m_config = p_config; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function destroy():void { this.m_tracker = null; this.m_config = null; this.m_lastTrackParams = null; } public function track(p_type:String, p_params:Object):void { if(!this.m_enabled) return; this.setParams(p_params.params); try { this.m_functions[p_type](p_params); } catch(error:Error) { trace(error); } this.resetParams(); } protected function trackEvent(p_params:OmnitureTrackParams):void { this.m_tracker.track(); } protected function trackLink(p_params:OmnitureTrackLinkParams):void { this.m_tracker.trackLink(p_params.URL, p_params.type, p_params.name); } protected function trackMedia(p_params:OmnitureMediaTrackParams):void { this.m_tracker.Media.track(p_params.mediaName); } protected function trackMediaOpen(p_params:OmnitureMediaOpenParams):void { + trace("open") this.m_tracker.Media.open(p_params.mediaName, Number(p_params.mediaLength), p_params.mediaPlayerName); } protected function trackMediaClose(p_params:OmnitureMediaCloseParams):void { - this.m_tracker.Media.stop(p_params.mediaName, Number(p_params.mediaOffset)); + trace("close") this.m_tracker.Media.close(p_params.mediaName); } protected function trackMediaPlay(p_params:OmnitureMediaPlayParams):void { + trace("play") this.m_tracker.Media.play(p_params.mediaName, Number(p_params.mediaOffset)); } protected function trackMediaStop(p_params:OmnitureMediaStopParams):void { + trace("stop") this.m_tracker.Media.stop(p_params.mediaName, Number(p_params.mediaOffset)); } protected function mergeParams(p_newValues:Object, p_destination:Object, p_oldValues:Object):void { var desc:XML = describeType(p_newValues); var propNode:XML; var props:XMLList = desc..variable; var type:String; var name:String; var oldVal:*; var newVal:*; // instance props for each(propNode in props) { name = propNode.@name; type = propNode.@type; oldVal = p_oldValues[name]; newVal = p_newValues[name]; if(oldVal is String && oldVal != null) { p_destination[name] = newVal; } else if(oldVal is Number && !isNaN(oldVal)) { p_destination[name] = newVal; } else if(oldVal is Boolean && oldVal) { p_destination[name] = newVal; } } // dynamic props for(name in p_oldValues) { oldVal = p_oldValues[name]; newVal = p_newValues[name]; if(oldVal is String && oldVal != null) { p_destination[name] = newVal; } else if(oldVal is Number && !isNaN(oldVal)) { p_destination[name] = newVal; } else if(oldVal is Boolean && oldVal) { p_destination[name] = newVal; } } } protected function resetParams():void { if(this.m_lastTrackParams == null) return; this.mergeParams(this.m_config, this.m_tracker, this.m_lastTrackParams); this.mergeParams(this.m_config.Media, this.m_tracker.Media, this.m_lastTrackParams.Media); } protected function setParams(p_params:OmnitureParams):void { this.m_lastTrackParams = p_params; this.mergeParams(p_params, this.m_tracker, p_params); this.mergeParams(p_params.Media, this.m_tracker.Media, p_params.Media); } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTrackType.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackType.as index 2b528fe..256c88f 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureTrackType.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackType.as @@ -1,41 +1,42 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { public class OmnitureTrackType { + public static const BATCH:String = "batch"; public static const TRACK:String = "track"; public static const TRACK_LINK:String = "trackLink"; public static const MEDIA_TRACK:String = "Media.track"; public static const MEDIA_OPEN:String = "Media.open"; public static const MEDIA_CLOSE:String = "Media.close"; public static const MEDIA_PLAY:String = "Media.play"; public static const MEDIA_STOP:String = "Media.stop"; } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as b/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as index 3956941..3976f69 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as @@ -1,145 +1,179 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import flash.display.Stage; import flash.utils.Dictionary; import com.dreamsocket.analytics.ITrack; import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.omniture.OmnitureService; import com.dreamsocket.analytics.omniture.OmnitureTrackerConfig; import com.dreamsocket.analytics.omniture.OmnitureTrackHandler; import com.dreamsocket.analytics.omniture.OmnitureTrackType; + import com.dreamsocket.analytics.omniture.OmnitureBatchParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaStopParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureTrackParamsMapper; import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParamsMapper; public class OmnitureTracker implements ITracker { public static const ID:String = "OmnitureTracker"; protected var m_config:OmnitureTrackerConfig; protected var m_enabled:Boolean; protected var m_service:OmnitureService; protected var m_handlers:Dictionary; + protected var m_functions:Dictionary; protected var m_paramMappers:Dictionary; public function OmnitureTracker(p_stage:Stage = null) { super(); this.m_config = new OmnitureTrackerConfig(); this.m_enabled = true; this.m_service = new OmnitureService(p_stage); this.m_handlers = new Dictionary(); + this.m_functions = new Dictionary(); + this.m_functions[OmnitureTrackType.BATCH] = this.batch; + this.m_functions[OmnitureTrackType.MEDIA_CLOSE] = this.doTrack; + this.m_functions[OmnitureTrackType.MEDIA_OPEN] = this.doTrack; + this.m_functions[OmnitureTrackType.MEDIA_PLAY] = this.doTrack; + this.m_functions[OmnitureTrackType.MEDIA_STOP] = this.doTrack; + this.m_functions[OmnitureTrackType.MEDIA_TRACK] = this.doTrack; + this.m_functions[OmnitureTrackType.TRACK] = this.doTrack; + this.m_functions[OmnitureTrackType.TRACK_LINK] = this.doTrack; + this.m_paramMappers = new Dictionary(); + this.m_paramMappers[OmnitureTrackType.BATCH] = new OmnitureBatchParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_CLOSE] = new OmnitureMediaCloseParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_OPEN] = new OmnitureMediaOpenParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_PLAY] = new OmnitureMediaPlayParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_STOP] = new OmnitureMediaStopParamsMapper(); this.m_paramMappers[OmnitureTrackType.MEDIA_TRACK] = new OmnitureMediaTrackParamsMapper(); this.m_paramMappers[OmnitureTrackType.TRACK] = new OmnitureTrackParamsMapper(); this.m_paramMappers[OmnitureTrackType.TRACK_LINK] = new OmnitureTrackLinkParamsMapper(); } public function get config():OmnitureTrackerConfig { return this.m_config; } public function set config(p_value:OmnitureTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; this.m_service.config = p_value.params; this.m_enabled = p_value.enabled; this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function get ID():String { return OmnitureTracker.ID; } public function addTrackHandler(p_ID:String, p_handler:OmnitureTrackHandler):void { this.m_handlers[p_ID] = p_handler; } public function getTrackHandler(p_ID:String):OmnitureTrackHandler { return this.m_handlers[p_ID] as OmnitureTrackHandler; } public function removeTrackHandler(p_ID:String):void { delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled) return; - var handler:OmnitureTrackHandler = this.m_config.handlers[p_track.type]; + var handler:OmnitureTrackHandler = this.m_config.handlers[p_track.ID]; - if(handler != null && handler.params != null && this.m_paramMappers[handler.type] != null) + if(handler && this.m_functions[handler.type]) { // has a track handler - this.m_service.track(handler.type, this.m_paramMappers[handler.type].map(handler.params, p_track.data)); - } + this.m_functions[handler.type](handler, p_track.data); + } + } + + + protected function doTrack(p_handler:OmnitureTrackHandler, p_data:*):void + { + if(p_handler.params != null && this.m_paramMappers[p_handler.type] != null) + { // has a track handler + this.m_service.track(p_handler.type, this.m_paramMappers[p_handler.type].map(p_handler.params, p_data)); + } } + + + protected function batch(p_handler:OmnitureTrackHandler, p_data:*):void + { + var params:Object = p_handler.params; + var i:uint = 0; + var len:uint = params.handlers.length; + while(i < len) + { + this.doTrack(OmnitureTrackHandler(params.handlers[i++]), p_data); + } + } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfigXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfigXMLDecoder.as index cccdb4d..0f1894a 100644 --- a/src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfigXMLDecoder.as @@ -1,98 +1,100 @@ -/** +/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.omniture { import flash.utils.Dictionary; import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureTrackerConfig; import com.dreamsocket.analytics.omniture.OmnitureTrackHandler; import com.dreamsocket.analytics.omniture.OmnitureTrackType; + import com.dreamsocket.analytics.omniture.OmnitureBatchParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureTrackParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParamsXMLDecoder; import com.dreamsocket.analytics.omniture.OmnitureMediaStopParamsXMLDecoder; public class OmnitureTrackerConfigXMLDecoder { protected var m_decoders:Dictionary; public function OmnitureTrackerConfigXMLDecoder() { this.m_decoders = new Dictionary(); + this.m_decoders[OmnitureTrackType.BATCH] = new OmnitureBatchParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.TRACK] = new OmnitureTrackParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.TRACK_LINK] = new OmnitureTrackLinkParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_TRACK] = new OmnitureMediaTrackParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_CLOSE] = new OmnitureMediaCloseParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_OPEN] = new OmnitureMediaOpenParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_PLAY] = new OmnitureMediaPlayParamsXMLDecoder(); this.m_decoders[OmnitureTrackType.MEDIA_STOP] = new OmnitureMediaStopParamsXMLDecoder(); } public function decode(p_xml:XML):OmnitureTrackerConfig { var config:OmnitureTrackerConfig = new OmnitureTrackerConfig(); config.enabled = p_xml.enabled.toString() != "false"; config.params = new OmnitureParamsXMLDecoder().decode(p_xml.params[0]); - this.setTrackHandlers(config.handlers, p_xml.handlers.handler); + this.createHandlers(config.handlers, p_xml.handlers.handler); return config; } - public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void + protected function createHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void { var handler:OmnitureTrackHandler; var handlerNode:XML; var ID:String; for each(handlerNode in p_handlerNodes) { ID = handlerNode.ID.toString(); if(ID.length > 0) { handler = new OmnitureTrackHandler(); handler.ID = ID; handler.type = handlerNode.type.toString(); - + if(this.m_decoders[handler.type]) { - handler.params = this.m_decoders[handler.type].decode(handlerNode.params[0]); - p_handlers[ID] = handler; - } + handler.params = this.m_decoders[handler.type].decode(handlerNode.params[0]); + } + p_handlers[ID] = handler; } } } } } diff --git a/src/com/dreamsocket/analytics/url/URLTrackHandler.as b/src/com/dreamsocket/analytics/url/URLTrackHandler.as index 39f3f7e..e360884 100644 --- a/src/com/dreamsocket/analytics/url/URLTrackHandler.as +++ b/src/com/dreamsocket/analytics/url/URLTrackHandler.as @@ -1,43 +1,42 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.url { - public class URLTrackHandler { public var ID:String; public var params:Array; - public function URLTrackHandler(p_ID:String = null, p_URLs:Array = null) + public function URLTrackHandler(p_ID:String = null, p_params:Array = null) { this.ID = p_ID; - this.params = p_URLs == null ? [] : p_URLs; + this.params = p_params; } } } diff --git a/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as b/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as new file mode 100644 index 0000000..52c5fcd --- /dev/null +++ b/src/com/dreamsocket/analytics/url/URLTrackParamsXMLDecoder.as @@ -0,0 +1,68 @@ + + +/** + * Dreamsocket + * + * Copyright 2007 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ +package com.dreamsocket.analytics.url +{ + import flash.net.URLRequest; + import flash.net.URLRequestMethod; + import flash.net.URLVariables; + + public class URLTrackParamsXMLDecoder + { + public function decode(p_XML:XML):Array + { + var params:Array = []; + var requestNode:XML; + var requestNodes:XMLList = p_XML.request; + var request:URLRequest; + + for each(requestNode in requestNodes) + { + request = new URLRequest(requestNode.URL.toString()); + + if(requestNode.data[0] != null) + { + request.method = URLRequestMethod.POST; + request.data = this.decodeVars(requestNode.data[0]); + } + params.push(request); + } + + return params; + } + + + protected function decodeVars(p_data:XML):Object + { + if(p_data.hasSimpleContent()) + { + return p_data.children().toString(); + } + + var vars:Object = {}; + var varNode:XML; + var varNodes:XMLList = p_data.children(); + for each(varNode in varNodes) + { + vars[varNode.name()] = varNode.children(); + } + return vars; + } + } +} diff --git a/src/com/dreamsocket/analytics/url/URLTracker.as b/src/com/dreamsocket/analytics/url/URLTracker.as index 7a0b08b..cde8bda 100644 --- a/src/com/dreamsocket/analytics/url/URLTracker.as +++ b/src/com/dreamsocket/analytics/url/URLTracker.as @@ -1,132 +1,154 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.url { + import flash.net.URLVariables; + import flash.net.URLRequest; import flash.utils.Dictionary; import com.dreamsocket.utils.PropertyStringUtil; import com.dreamsocket.analytics.ITrack; import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.url.URLTrackerConfig; import com.dreamsocket.analytics.url.URLTrackHandler; import com.dreamsocket.utils.HTTPUtil; public class URLTracker implements ITracker { public static const ID:String = "URLTracker"; protected var m_config:URLTrackerConfig; protected var m_enabled:Boolean; protected var m_handlers:Dictionary; public function URLTracker() { super(); this.m_config = new URLTrackerConfig(); this.m_enabled = true; this.m_handlers = new Dictionary(); } public function get config():URLTrackerConfig { return this.m_config; } public function set config(p_value:URLTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; this.m_enabled = p_value.enabled; this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function get ID():String { return URLTracker.ID; } public function addTrackHandler(p_ID:String, p_handler:URLTrackHandler):void { this.m_handlers[p_ID] = p_handler; } public function getTrackHandler(p_ID:String):URLTrackHandler { return this.m_handlers[p_ID] as URLTrackHandler; } public function removeTrackHandler(p_ID:String):void { delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled) return; - var handler:URLTrackHandler = this.m_handlers[p_track.type]; + var handler:URLTrackHandler = this.m_handlers[p_track.ID]; if(handler != null) { // has the track type - var URLs:Array = handler.params; - var i:uint = URLs.length; + var requests:Array = handler.params; + var i:uint = requests.length; + var request:URLRequest; + var prop:String; + var vars:Object; + var urlVars:URLVariables; while(i--) { - HTTPUtil.pingURL(PropertyStringUtil.evalPropertyString(p_track.data, URLs[i])); + request = URLRequest(requests[i]); + request.url = (PropertyStringUtil.evalPropertyString(p_track.data, request.url)); + vars = request.data; + if(vars is String) + { + PropertyStringUtil.evalPropertyString(p_track.data, String(vars)); + } + else if(vars is Object) + { + request.data = urlVars = new URLVariables; + for(prop in vars) + { + urlVars[prop] = (PropertyStringUtil.evalPropertyString(p_track.data, vars[prop])); + } + } + + HTTPUtil.ping(request); } } } } } \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/url/URLTrackerConfigXMLDecoder.as b/src/com/dreamsocket/analytics/url/URLTrackerConfigXMLDecoder.as index 2b00bec..7bbd8c2 100644 --- a/src/com/dreamsocket/analytics/url/URLTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/analytics/url/URLTrackerConfigXMLDecoder.as @@ -1,81 +1,80 @@ -/** +/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics.url { import flash.utils.Dictionary; import com.dreamsocket.analytics.url.URLTrackerConfig; import com.dreamsocket.analytics.url.URLTrackHandler; - + import com.dreamsocket.analytics.url.URLTrackParamsXMLDecoder; public class URLTrackerConfigXMLDecoder { + protected var m_paramDecoder:URLTrackParamsXMLDecoder; + public function URLTrackerConfigXMLDecoder() { + this.m_paramDecoder = new URLTrackParamsXMLDecoder(); } - + public function decode(p_xml:XML):URLTrackerConfig { var config:URLTrackerConfig = new URLTrackerConfig(); var handlerNodes:XMLList = p_xml.handlers.handler; var handlerNode:XML; var handlers:Dictionary = config.handlers; // handlers for each(handlerNode in handlerNodes) { this.addTrack(handlers, handlerNode); } // enabled config.enabled = p_xml.enabled.toString() != "false"; return config; } protected function addTrack(p_handlers:Dictionary, p_handlerNode:XML):void { var ID:String = p_handlerNode.ID.toString(); - var urlNode:XML; var handler:URLTrackHandler; if(ID.length > 0) { handler = new URLTrackHandler(); - for each(urlNode in p_handlerNode.params.URL) - { - handler.params.push(urlNode.toString()); - } + handler.params = this.m_paramDecoder.decode(p_handlerNode.params[0]); handler.ID = ID; p_handlers[ID] = handler; } } } } diff --git a/src/com/dreamsocket/utils/HTTPUtil.as b/src/com/dreamsocket/utils/HTTPUtil.as index d14408f..393721b 100644 --- a/src/com/dreamsocket/utils/HTTPUtil.as +++ b/src/com/dreamsocket/utils/HTTPUtil.as @@ -1,126 +1,139 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.utils { import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; import flash.system.Security; import flash.utils.Dictionary; public class HTTPUtil { public static var allowLocalQueryStrings:Boolean = false; protected static var k_pings:Dictionary = new Dictionary(); public function HTTPUtil() { } + + public static function ping(p_request:URLRequest):void + { + var loader:URLLoader = new URLLoader(); + + loader.load(p_request); + loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); + loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); + loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); + + HTTPUtil.k_pings[loader] = true; + } + public static function pingURL(p_URL:String, p_clearCache:Boolean = true, p_rateInSecsToCache:Number = 0):void { if(p_URL == null) return; var loader:URLLoader = new URLLoader(); var URL:String = p_URL; if(p_clearCache && (HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE)) { URL = HTTPUtil.resolveUniqueURL(p_URL, p_rateInSecsToCache); } loader.load(new URLRequest(URL)); loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); HTTPUtil.k_pings[loader] = true; } public static function addQueryParam(p_URL:String, p_name:String, p_val:String, p_delimeter:String = null):String { if(HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) { if(p_delimeter == null) p_URL += (p_URL.indexOf( "?" ) != -1 ) ? "&" + p_name + "=" : "?" + p_name + "="; else p_URL += p_delimeter + p_name + "="; p_URL += p_val != null ? escape(p_val) : ""; } return p_URL; } public static function resolveUniqueURL(p_URL:String, p_rateInSecsToCache:Number = 0):String { var request:String = p_URL; if((HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) && p_URL.indexOf( "&cacheID=" ) == -1 && p_URL.indexOf( "?cacheID=" ) == -1) { request = HTTPUtil.addQueryParam(p_URL, "cacheID", HTTPUtil.getUniqueCacheID(p_rateInSecsToCache)); } return request; } public static function getUniqueCacheID(p_rateInSecsToCache:Number = 0):String { var d:Date = new Date(); var ID:String; var secsPassed:Number = (60 * d.getUTCMinutes()) + d.getUTCSeconds(); if(p_rateInSecsToCache == 0) { ID = String(d.valueOf()); } else { ID = d.getUTCFullYear() + "" + d.getUTCMonth() + "" +d.getUTCDate() + "" +d.getUTCHours() + "-" + Math.floor(secsPassed/p_rateInSecsToCache); } return ID; } protected static function onPingResult(p_event:Event):void { // NOTE: let errors be thrown or log them if you want to handle them URLLoader(p_event.target).removeEventListener(Event.COMPLETE, HTTPUtil.onPingResult); URLLoader(p_event.target).removeEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); URLLoader(p_event.target).removeEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); delete(HTTPUtil.k_pings[p_event.target]); } } } diff --git a/test/TestOmnitureMediaTracking.as b/test/TestOmnitureMediaTracking.as new file mode 100644 index 0000000..135f1db --- /dev/null +++ b/test/TestOmnitureMediaTracking.as @@ -0,0 +1,122 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package +{ + import flash.events.MouseEvent; + import com.dreamsocket.analytics.Track; + import com.dreamsocket.analytics.omniture.OmnitureTrackerConfig; + import com.dreamsocket.analytics.omniture.OmnitureTrackerConfigXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureTracker; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestOmnitureMediaTracking extends Sprite + { + private var m_loader:URLLoader; + private var m_tracker:OmnitureTracker; + + public var requestBtn:Object; + public var startBtn:Object; + public var playBtn:Object; + public var pauseBtn:Object; + public var closeBtn:Object; + + public function TestOmnitureMediaTracking() + { + this.m_loader = new URLLoader(); + this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_loader.load(new URLRequest("test_omniture_media.xml")); + + this.requestBtn.addEventListener(MouseEvent.CLICK, this.onRequestClicked); + this.startBtn.addEventListener(MouseEvent.CLICK, this.onStartClicked); + this.playBtn.addEventListener(MouseEvent.CLICK, this.onPlayClicked); + this.pauseBtn.addEventListener(MouseEvent.CLICK, this.onPauseClicked); + this.closeBtn.addEventListener(MouseEvent.CLICK, this.onCloseClicked); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onRequestClicked(p_event:MouseEvent):void + { + this.m_tracker.track(new Track("mediaRequested", {duration:120, position:0, title:"testid"})); + } + + + private function onStartClicked(p_event:MouseEvent):void + { + this.m_tracker.track(new Track("mediaStarted", {duration:120, position:0, title:"testid"})); + } + + + private function onPlayClicked(p_event:MouseEvent):void + { + this.m_tracker.track(new Track("mediaPlaying", {duration:120, position:30, title:"testid"})); + } + + + private function onPauseClicked(p_event:MouseEvent):void + { + this.m_tracker.track(new Track("mediaPaused", {duration:120, position:30, title:"testid"})); + } + + + private function onCloseClicked(p_event:MouseEvent):void + { + this.m_tracker.track(new Track("mediaClosed", {duration:120, position:0, title:"testid"})); + } + + + private function onXMLLoaded(p_event:Event):void + { + var config:OmnitureTrackerConfig = new OmnitureTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); + + this.m_tracker = new OmnitureTracker(this.stage); + this.m_tracker.config = config; + + this.m_tracker.track(new Track("mediaRequested", {duration:120, title:"testid", position:0})); + this.m_tracker.track(new Track("mediaStarted", {duration:120, title:"testid", position:0})); + + this.m_tracker.track(new Track("mediaPaused", {position:30, title:"testid"})); + this.m_tracker.track(new Track("mediaPlaying", {position:30, title:"testid"})); + + this.m_tracker.track(new Track("mediaClosed", {position:110, title:"testid"})); + } + } +} diff --git a/test/test_omniture_media.xml b/test/test_omniture_media.xml index 4a32e13..8ad0f5f 100644 --- a/test/test_omniture_media.xml +++ b/test/test_omniture_media.xml @@ -1,99 +1,96 @@ <?xml version="1.0" encoding="utf-8"?> <!-- tracking: OMNITURE --> <omniture> <!-- enabled: specifies whether Omniture tracking will be sent --> <enabled>true</enabled> <!-- params: allows you to generically assign values to all omniture values NOTE: params set will be sent for every track This can be use to set special props like <eVar23>pga_mosaic_player_09</eVar23> --> <params> <account>foodotcom</account> <dc>122</dc> <delayTracking>2</delayTracking> <trackingServer>stats.foo.com</trackingServer> <visitorNameSpace>foo</visitorNameSpace> <trackLocal>true</trackLocal> <eVar1>test evar1</eVar1> <eVar25>test evar25</eVar25> <Media> <playerName>livePlayer</playerName> <trackEvents>event2</trackEvents> <!--<trackMilestones>20,40,60,80</trackMilestones>--> <trackSeconds>5</trackSeconds> <!--<trackVars></trackVars>--> <trackWhilePlaying>true</trackWhilePlaying> </Media> </params> <handlers> <handler> <ID>mediaRequested</ID> <type>Media.open</type> <params> <mediaName>${data.title}</mediaName> <mediaLength>${data.duration}</mediaLength> <mediaPlayerName>livePlayer</mediaPlayerName> <params> <Media> <trackEvents>event2</trackEvents> <trackVars>eVar1,eVar25</trackVars> </Media> </params> </params> </handler> <handler> <ID>mediaClosed</ID> - <type>Media.close</type> + <type>batch</type> <params> - <mediaName>${data.title}</mediaName> - <mediaOffset>${data.position}</mediaOffset> + <handler> + <type>Media.stop</type> + <params> + <mediaName>${data.title}</mediaName> + <mediaOffset>${data.position}</mediaOffset> + </params> + </handler> + <handler> + <type>Media.close</type> + <params> + <mediaName>${data.title}</mediaName> + </params> + </handler> </params> </handler> <handler> <ID>mediaStarted</ID> <type>Media.play</type> <params> <mediaName>${data.title}</mediaName> <mediaOffset>${data.position}</mediaOffset> </params> </handler> <handler> <ID>mediaPlaying</ID> <type>Media.play</type> <params> <mediaName>${data.title}</mediaName> <mediaOffset>${data.position}</mediaOffset> </params> </handler> <handler> <ID>mediaPaused</ID> <type>Media.stop</type> <params> <mediaName>${data.title}</mediaName> <mediaOffset>${data.position}</mediaOffset> </params> </handler> - - - <handler> - <ID>mediaPaused</ID> - <type>Media.track</type> - <params> - <mediaName>${data.title}</mediaName> - <params> - <Media> - <trackVars>eVar7</trackVars> - </Media> - <eVar7>evar7- Leaderboard Link</eVar7> - </params> - </params> - </handler> + </handlers> </omniture> \ No newline at end of file diff --git a/test/test_tracking_google.xml b/test/test_tracking_google.xml index e2c4233..17800b4 100644 --- a/test/test_tracking_google.xml +++ b/test/test_tracking_google.xml @@ -1,42 +1,53 @@ <?xml version="1.0" encoding="utf-8"?> <!-- tracking: GOOGLE --> <google> <!-- enabled: specifies whether GOOGLE tracking will be sent --> <enabled>true</enabled> <account>UA-5555555-5</account> <visualDebug>false</visualDebug> <trackingMode>AS3</trackingMode> <handlers> <handler> <ID>track1</ID> - <type>trackPageView</type> - <params> - <URL>${data} Scorecard Nav</URL> + <type>batch</type> + <params> + <handler> + <type>trackPageView</type> + <params> + <URL>${data} Scorecard Nav1</URL> + </params> + </handler> + <handler> + <type>trackPageView</type> + <params> + <URL>${data} Scorecard Nav2</URL> + </params> + </handler> </params> - </handler> + </handler> <handler> <ID>track2</ID> <type>trackEvent</type> <params> <category>LiveAt_videoevent1</category> <action>o1</action> <label>Mosiac Live Stream1</label> <value>1</value> </params> </handler> <handler> <ID>track3</ID> <type>trackEvent</type> <params> <category>LiveAt_videoevent2</category> <action>o2</action> </params> </handler> </handlers> </google> \ No newline at end of file diff --git a/test/test_tracking_url.xml b/test/test_tracking_url.xml index 42ceaed..977b6c6 100644 --- a/test/test_tracking_url.xml +++ b/test/test_tracking_url.xml @@ -1,42 +1,53 @@ <?xml version="1.0" encoding="utf-8"?> <!-- url TRACKING defines a tracker that can ping URLs for a specific track request --> <URL> <!-- enabled: specifies whether url tracking will be sent --> <enabled>true</enabled> <!-- URL track handlers specify a way to respond to a specifically name track request ID - specifies the specific named track request URLs - specifies a list of URLs to ping for that specific track request each URL is actually a template. Therefore the URL can opt to use data which is specific to that named request. This is done using a wrapper notation {data}, specifying the value be replaced by dynamic data. For example: a mediaStarted request may be sent a media object. This media object is represented by {data} in the template. Thus a template of http://foo.com?{data.id} would replace {data.id} with the media's ID like http://foo.com?1234 --> <handlers> <handler> <ID>track1</ID> <params> - <URL>http://foo.com/track1.gif</URL> + <request> + <URL>http://foo.com/track1.gif</URL> + <data> + <test1>this is a test val1</test1> + <test2>this is a test val2</test2> + </data> + </request> </params> </handler> <handler> <ID>track2</ID> <params> - <URL>http://foo.com/track2.gif?id=${data.id}</URL> + <request> + <URL>http://foo.com/track2.gif?id=${data.id}</URL> + <data>post it</data> + </request> </params> </handler> <handler> <ID>track3</ID> <params> - <URL>http://foo.com/track3.gif?id=${data}</URL> + <request> + <URL>http://foo.com/track3.gif?id=${data}</URL> + </request> </params> </handler> </handlers> </URL> \ No newline at end of file
dreamsocket/actionscript-analytics-framework
3981af16be5a7bc6e141ecc78c33d5fd3549131e
[ADMIN] reattempting last commit since elements weren't added/deleted.
diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoaderEvent.as b/src/com/dreamsocket/analytics/TrackerModuleLoaderEvent.as new file mode 100644 index 0000000..a6a25db --- /dev/null +++ b/src/com/dreamsocket/analytics/TrackerModuleLoaderEvent.as @@ -0,0 +1,77 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics +{ + + import flash.events.Event; + + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.TrackerModuleLoaderParams; + + public class TrackerModuleLoaderEvent extends Event + { + public static const MODULE_LOADED:String = "moduleLoaded"; + public static const MODULE_FAILED:String = "moduleFailed"; + + private var m_resource:TrackerModuleLoaderParams; + private var m_tracker:ITracker; + + + public function TrackerModuleLoaderEvent(p_eventType:String, p_resource:TrackerModuleLoaderParams, p_tracker:ITracker = null, p_bubbles:Boolean = false, p_cancelable:Boolean = false) + { + super(p_eventType, p_bubbles, p_cancelable); + this.m_resource = p_resource; + this.m_tracker = p_tracker; + } + + + public function get resource():TrackerModuleLoaderParams + { + return this.m_resource; + } + + + public function get tracker():ITracker + { + return this.m_tracker; + } + + + override public function clone():Event + { + return new TrackerModuleLoaderEvent(this.type, this.resource, this.tracker, this.bubbles, this.cancelable); + } + + + override public function toString():String + { + return this.formatToString("TrackerModuleLoaderEvent", "type", "bubbles", "eventPhase"); + } + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoaderParams.as b/src/com/dreamsocket/analytics/TrackerModuleLoaderParams.as new file mode 100644 index 0000000..639ede3 --- /dev/null +++ b/src/com/dreamsocket/analytics/TrackerModuleLoaderParams.as @@ -0,0 +1,42 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package com.dreamsocket.analytics +{ + import flash.display.Stage; + + public class TrackerModuleLoaderParams + { + public var resource:*; + public var config:*; // XML, URL + public var stage:Stage; + + public function TrackerModuleLoaderParams() + { + } + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/TrackerModuleManifestLoader.as b/src/com/dreamsocket/analytics/TrackerModuleManifestLoader.as new file mode 100644 index 0000000..f8c85de --- /dev/null +++ b/src/com/dreamsocket/analytics/TrackerModuleManifestLoader.as @@ -0,0 +1,149 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics +{ + import flash.display.Stage; + import flash.events.IOErrorEvent; + import flash.events.ErrorEvent; + import flash.events.Event; + import flash.events.EventDispatcher; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + import com.dreamsocket.analytics.ITrackerModule; + import com.dreamsocket.analytics.TrackerModuleLoaderQueue; + import com.dreamsocket.analytics.TrackerModuleManifestXMLDecoder; + + + public class TrackerModuleManifestLoader extends EventDispatcher + { + protected var m_configLoader:URLLoader; + protected var m_decoder:TrackerModuleManifestXMLDecoder; + protected var m_moduleLoader:TrackerModuleLoaderQueue; + + public function TrackerModuleManifestLoader() + { + this.m_decoder = new TrackerModuleManifestXMLDecoder(); + } + + + public function set stage(p_value:Stage):void + { + this.m_decoder.stage = p_value; + } + + + public function addModuleDefinition(p_ID:String, p_module:ITrackerModule):void + { + this.m_decoder.addModuleDefinition(p_ID, p_module); + } + + + public function destroy():void + { + if(this.m_configLoader) + { + this.m_configLoader.removeEventListener(Event.COMPLETE, this.onConfigLoaded); + this.m_configLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_configLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + try + { + this.m_configLoader.close(); + } + catch(error:Error){} + + this.m_configLoader = null; + } + if(this.m_moduleLoader) + { + this.m_moduleLoader.removeEventListener(Event.COMPLETE, this.onModulesLoaded); + this.m_moduleLoader.destroy(); + + this.m_moduleLoader = null; + } + + } + + + public function load(p_URL:String):void + { + this.destroy(); + + this.m_configLoader = new URLLoader(); + this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); + this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + + try + { + this.m_configLoader.load(new URLRequest(p_URL)); + } + catch(error:Error) + { + this.dispatchError(error.message); + } + } + + + protected function dispatchError(p_message:String):void + { + this.dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, p_message)); + } + + + protected function onConfigLoaded(p_event:Event):void + { + try + { + this.m_moduleLoader = new TrackerModuleLoaderQueue(); + this.m_moduleLoader.addEventListener(Event.COMPLETE, this.onModulesLoaded); + this.m_moduleLoader.manifest = this.m_decoder.decode(new XML(this.m_configLoader.data)); + this.m_moduleLoader.load(); + + } + catch(error:Error) + { + this.dispatchError(error.message); + } + } + + + protected function onModulesLoaded(p_event:Event):void + { + this.dispatchEvent(new Event(Event.COMPLETE)); + } + + + protected function onErrorOccurred(p_event:ErrorEvent):void + { + this.dispatchError(p_event.text); + } + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/TrackerModuleManifestXMLDecoder.as b/src/com/dreamsocket/analytics/TrackerModuleManifestXMLDecoder.as new file mode 100644 index 0000000..157c0e8 --- /dev/null +++ b/src/com/dreamsocket/analytics/TrackerModuleManifestXMLDecoder.as @@ -0,0 +1,76 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics +{ + import flash.display.Stage; + import flash.utils.Dictionary; + + public class TrackerModuleManifestXMLDecoder + { + protected var m_modules:Dictionary; + protected var m_stage:Stage; + + public function TrackerModuleManifestXMLDecoder() + { + this.m_modules = new Dictionary(); + } + + + public function set stage(p_value:Stage):void + { + this.m_stage = p_value; + } + + + public function addModuleDefinition(p_ID:String, p_module:ITrackerModule):void + { + this.m_modules[p_ID] = p_module; + } + + + public function decode(p_XML:XML):Array + { + var manifest:Array = []; + var moduleNodeList:XMLList = p_XML.module; + var moduleNode:XML; + var moduleResource:TrackerModuleLoaderParams; + + for each(moduleNode in moduleNodeList) + { + moduleResource = new TrackerModuleLoaderParams(); + moduleResource.stage = this.m_stage; + moduleResource.config = moduleNode.config.hasComplexContent() ? XML(moduleNode.config[0]) : moduleNode.config.toString(); + moduleResource.resource = this.m_modules[moduleNode.resource.toString()] ? this.m_modules[moduleNode.resource.toString()] : moduleNode.resource.toString(); + manifest.push(moduleResource); + } + + return manifest; + } + } +} diff --git a/src/com/dreamsocket/analytics/js/JSMethodCall.as b/src/com/dreamsocket/analytics/TrackerModuleParams.as similarity index 79% rename from src/com/dreamsocket/analytics/js/JSMethodCall.as rename to src/com/dreamsocket/analytics/TrackerModuleParams.as index a4507d2..3cfc16d 100644 --- a/src/com/dreamsocket/analytics/js/JSMethodCall.as +++ b/src/com/dreamsocket/analytics/TrackerModuleParams.as @@ -1,42 +1,42 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ - -package com.dreamsocket.tracking.js +package com.dreamsocket.analytics { - public class JSMethodCall + import flash.display.Stage; + + public class TrackerModuleParams { - public var method:String; - public var arguments:Array; + public var config:XML; + public var stage:Stage; - public function JSMethodCall(p_method:String = null, p_arguments:Array = null) + public function TrackerModuleParams() { - this.method = p_method; - this.arguments = p_arguments == null ? [] : p_arguments; } + } -} +} \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackEventParamsXMLDecoder.as b/src/com/dreamsocket/analytics/google/GoogleTrackEventParamsXMLDecoder.as new file mode 100644 index 0000000..5811197 --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleTrackEventParamsXMLDecoder.as @@ -0,0 +1,51 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.google +{ + import com.dreamsocket.analytics.google.GoogleTrackEventParams; + + public class GoogleTrackEventParamsXMLDecoder + { + public function decode(p_XML:XML):GoogleTrackEventParams + { + var params:GoogleTrackEventParams = new GoogleTrackEventParams(); + + if(p_XML.action.toString().length) + params.action = p_XML.action.toString(); + if(p_XML.category.toString().length) + params.category = p_XML.category.toString(); + if(p_XML.label.toString().length) + params.label = p_XML.label.toString(); + if(p_XML.value.toString().length) + params.value = p_XML.value.toString(); + + return params; + } + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackPageViewParamsXMLDecoder.as b/src/com/dreamsocket/analytics/google/GoogleTrackPageViewParamsXMLDecoder.as new file mode 100644 index 0000000..bd707b8 --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleTrackPageViewParamsXMLDecoder.as @@ -0,0 +1,45 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.google +{ + import com.dreamsocket.analytics.google.GoogleTrackPageViewParams; + + public class GoogleTrackPageViewParamsXMLDecoder + { + public function decode(p_XML:XML):GoogleTrackPageViewParams + { + var params:GoogleTrackPageViewParams = new GoogleTrackPageViewParams(); + + if(p_XML.URL.toString().length) + params.URL = p_XML.URL.toString(); + + return params; + } + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackType.as b/src/com/dreamsocket/analytics/google/GoogleTrackType.as new file mode 100644 index 0000000..5bc3ee5 --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleTrackType.as @@ -0,0 +1,36 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package com.dreamsocket.analytics.google +{ + + public class GoogleTrackType + { + public static const TRACK_PAGE_VIEW:String = "trackPageView"; + public static const TRACK_EVENT:String = "trackEvent"; + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/google/GoogleTrackerModule.as b/src/com/dreamsocket/analytics/google/GoogleTrackerModule.as new file mode 100644 index 0000000..a07c55d --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleTrackerModule.as @@ -0,0 +1,55 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.google +{ + import flash.display.Sprite; + + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.ITrackerModule; + import com.dreamsocket.analytics.TrackerModuleParams; + import com.dreamsocket.analytics.google.GoogleTracker; + import com.dreamsocket.analytics.google.GoogleTrackerConfigXMLDecoder; + + public class GoogleTrackerModule extends Sprite implements ITrackerModule + { + public function GoogleTrackerModule() + { + } + + + public function getTracker(p_params:TrackerModuleParams):ITracker + { + var tracker:GoogleTracker = new GoogleTracker(p_params.stage); + + tracker.config = new GoogleTrackerConfigXMLDecoder().decode(p_params.config); + + return tracker; + } + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/js/JSTrackParamsXMLDecoder.as b/src/com/dreamsocket/analytics/js/JSTrackParamsXMLDecoder.as new file mode 100644 index 0000000..ffe86d0 --- /dev/null +++ b/src/com/dreamsocket/analytics/js/JSTrackParamsXMLDecoder.as @@ -0,0 +1,50 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package com.dreamsocket.analytics.js +{ + import com.dreamsocket.analytics.js.JSTrackParams; + + public class JSTrackParamsXMLDecoder + { + public function decode(p_XML:XML):JSTrackParams + { + var params:JSTrackParams = new JSTrackParams(p_XML.method.toString()); + var argumentNodes:XMLList = p_XML.arguments.argument; + var argumentNode:XML; + + for each(argumentNode in argumentNodes) + { + params.arguments.push(argumentNode); + } + + return params; + } + } + + +} diff --git a/src/com/dreamsocket/analytics/js/JSTrackerModule.as b/src/com/dreamsocket/analytics/js/JSTrackerModule.as new file mode 100644 index 0000000..e4ed70d --- /dev/null +++ b/src/com/dreamsocket/analytics/js/JSTrackerModule.as @@ -0,0 +1,54 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package com.dreamsocket.analytics.js +{ + import flash.display.Sprite; + + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.ITrackerModule; + import com.dreamsocket.analytics.TrackerModuleParams; + import com.dreamsocket.analytics.js.JSTracker; + import com.dreamsocket.analytics.js.JSTrackerConfigXMLDecoder; + + public class JSTrackerModule extends Sprite implements ITrackerModule + { + public function JSTrackerModule() + { + } + + + public function getTracker(p_params:TrackerModuleParams):ITracker + { + var tracker:JSTracker = new JSTracker(); + + tracker.config = new JSTrackerConfigXMLDecoder().decode(p_params.config); + + return tracker; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsMapper.as new file mode 100644 index 0000000..65048c4 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsMapper.as @@ -0,0 +1,54 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsMapper; + import com.dreamsocket.utils.PropertyStringUtil; + + public class OmnitureMediaCloseParamsMapper + { + public function OmnitureMediaCloseParamsMapper() + { + } + + public function map(p_params:OmnitureMediaCloseParams, p_data:*):OmnitureMediaCloseParams + { + var mapped:OmnitureMediaCloseParams = new OmnitureMediaCloseParams(); + + mapped.mediaName = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaName); + mapped.mediaOffset = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaOffset); + mapped.params = new OmnitureParamsMapper().map(p_params.params, p_data); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsXMLDecoder.as new file mode 100644 index 0000000..b7109a7 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParamsXMLDecoder.as @@ -0,0 +1,51 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; + + public class OmnitureMediaCloseParamsXMLDecoder + { + + public function decode(p_XML:XML):OmnitureMediaCloseParams + { + var params:OmnitureMediaCloseParams = new OmnitureMediaCloseParams(); + + if(p_XML.mediaName.toString().length) + params.mediaName = p_XML.mediaName.toString(); + if(p_XML.mediaOffset.toString().length) + params.mediaOffset = p_XML.mediaOffset.toString(); + + params.params = new OmnitureParamsXMLDecoder().decode(p_XML.params[0]); + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParamsMapper.as new file mode 100644 index 0000000..2cdd5fa --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParamsMapper.as @@ -0,0 +1,55 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsMapper; + import com.dreamsocket.utils.PropertyStringUtil; + + public class OmnitureMediaOpenParamsMapper + { + public function OmnitureMediaOpenParamsMapper() + { + } + + + public function map(p_params:OmnitureMediaOpenParams, p_data:*):OmnitureMediaOpenParams + { + var mapped:OmnitureMediaOpenParams = new OmnitureMediaOpenParams(); + + mapped.mediaName = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaName); + mapped.mediaLength = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaLength); + mapped.mediaPlayerName = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaPlayerName); + mapped.params = new OmnitureParamsMapper().map(p_params.params, p_data); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParamsXMLDecoder.as new file mode 100644 index 0000000..a9d8d23 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParamsXMLDecoder.as @@ -0,0 +1,53 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; + + public class OmnitureMediaOpenParamsXMLDecoder + { + + public function decode(p_XML:XML):OmnitureMediaOpenParams + { + var params:OmnitureMediaOpenParams = new OmnitureMediaOpenParams(); + + if(p_XML.mediaName.toString().length) + params.mediaName = p_XML.mediaName.toString(); + if(p_XML.mediaLength.toString().length) + params.mediaLength = p_XML.mediaLength.toString(); + if(p_XML.mediaName.toString().length) + params.mediaPlayerName = p_XML.mediaPlayerName.toString(); + + params.params = new OmnitureParamsXMLDecoder().decode(p_XML.params[0]); + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParamsMapper.as new file mode 100644 index 0000000..bfa6c67 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParamsMapper.as @@ -0,0 +1,54 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsMapper; + import com.dreamsocket.utils.PropertyStringUtil; + + public class OmnitureMediaPlayParamsMapper + { + public function OmnitureMediaPlayParamsMapper() + { + } + + + public function map(p_params:OmnitureMediaPlayParams, p_data:*):OmnitureMediaPlayParams + { + var mapped:OmnitureMediaPlayParams = new OmnitureMediaPlayParams(); + + mapped.mediaName = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaName); + mapped.mediaOffset = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaOffset); + mapped.params = new OmnitureParamsMapper().map(p_params.params, p_data); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParamsXMLDecoder.as new file mode 100644 index 0000000..179f537 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParamsXMLDecoder.as @@ -0,0 +1,51 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; + + public class OmnitureMediaPlayParamsXMLDecoder + { + + public function decode(p_XML:XML):OmnitureMediaPlayParams + { + var params:OmnitureMediaPlayParams = new OmnitureMediaPlayParams(); + + if(p_XML.mediaName.toString().length) + params.mediaName = p_XML.mediaName.toString(); + if(p_XML.mediaOffset.toString().length) + params.mediaOffset = p_XML.mediaOffset.toString(); + + params.params = new OmnitureParamsXMLDecoder().decode(p_XML.params[0]); + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParamsMapper.as new file mode 100644 index 0000000..e1c8e5c --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParamsMapper.as @@ -0,0 +1,54 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaStopParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsMapper; + import com.dreamsocket.utils.PropertyStringUtil; + + public class OmnitureMediaStopParamsMapper + { + public function OmnitureMediaStopParamsMapper() + { + } + + + public function map(p_params:OmnitureMediaStopParams, p_data:*):OmnitureMediaStopParams + { + var mapped:OmnitureMediaStopParams = new OmnitureMediaStopParams(); + + mapped.mediaName = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaName); + mapped.mediaOffset = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaOffset); + mapped.params = new OmnitureParamsMapper().map(p_params.params, p_data); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParamsXMLDecoder.as new file mode 100644 index 0000000..a737f67 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParamsXMLDecoder.as @@ -0,0 +1,51 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaStopParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; + + public class OmnitureMediaStopParamsXMLDecoder + { + + public function decode(p_XML:XML):OmnitureMediaStopParams + { + var params:OmnitureMediaStopParams = new OmnitureMediaStopParams(); + + if(p_XML.mediaName.toString().length) + params.mediaName = p_XML.mediaName.toString(); + if(p_XML.mediaOffset.toString().length) + params.mediaOffset = p_XML.mediaOffset.toString(); + + params.params = new OmnitureParamsXMLDecoder().decode(p_XML.params[0]); + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParamsMapper.as new file mode 100644 index 0000000..6d96c49 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParamsMapper.as @@ -0,0 +1,53 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsMapper; + import com.dreamsocket.utils.PropertyStringUtil; + + public class OmnitureMediaTrackParamsMapper + { + public function OmnitureMediaTrackParamsMapper() + { + } + + public function map(p_params:OmnitureMediaTrackParams, p_data:*):OmnitureMediaTrackParams + { + var mapped:OmnitureMediaTrackParams = new OmnitureMediaTrackParams(); + + mapped.mediaName = PropertyStringUtil.evalPropertyString(p_data, p_params.mediaName); + mapped.params = new OmnitureParamsMapper().map(p_params.params, p_data); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParamsXMLDecoder.as new file mode 100644 index 0000000..67680d6 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParamsXMLDecoder.as @@ -0,0 +1,48 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; + + public class OmnitureMediaTrackParamsXMLDecoder + { + + public function decode(p_XML:XML):OmnitureMediaTrackParams + { + var params:OmnitureMediaTrackParams = new OmnitureMediaTrackParams(); + + if(p_XML.mediaName.toString().length) + params.mediaName = p_XML.mediaName.toString(); + params.params = new OmnitureParamsXMLDecoder().decode(p_XML.params[0]); + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/TrackingManager.as b/src/com/dreamsocket/analytics/omniture/OmnitureSingleton.as similarity index 56% rename from src/com/dreamsocket/analytics/TrackingManager.as rename to src/com/dreamsocket/analytics/omniture/OmnitureSingleton.as index 431ce50..00e7e51 100644 --- a/src/com/dreamsocket/analytics/TrackingManager.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureSingleton.as @@ -1,88 +1,73 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ - - -package com.dreamsocket.tracking + +package com.dreamsocket.analytics.omniture { - import flash.utils.Dictionary; + import flash.display.Stage; - public class TrackingManager - { - protected static var k_enabled:Boolean = true; - protected static var k_trackers:Dictionary = new Dictionary(); + import com.omniture.ActionSource; - - public function TrackingManager() + public class OmnitureSingleton + { + protected static var k_stage:Stage; + protected static var k_instance:ActionSource; + + public function OmnitureSingleton() { } - public static function get enabled():Boolean - { - return k_enabled; - } - - - public static function set enabled(p_enabled:Boolean):void + public static function set stage(p_display:Stage):void { - k_enabled = p_enabled; + OmnitureSingleton.create(p_display); } - - - public static function track(p_track:ITrack):void + + public static function create(p_display:Stage):ActionSource { - if(!k_enabled) return; - - var tracker:Object; + var mod:ActionSource = OmnitureSingleton.instance; - // send track payload to all trackers - for each(tracker in k_trackers) + if(p_display != null) { - ITracker(tracker).track(p_track); + p_display.addChild(mod); } - } - - - public static function addTracker(p_ID:String, p_tracker:ITracker):void - { - k_trackers[p_ID] = p_tracker; - } + + return k_instance; + } - public static function getTracker(p_ID:String):ITracker + public static function get instance():ActionSource { - return k_trackers[p_ID] as ITracker; + if(k_instance == null) + { + k_instance = new ActionSource(); + } + + return k_instance; } - - - public static function removeTracker(p_ID:String):void - { - delete(k_trackers[p_ID]); - } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParamsMapper.as new file mode 100644 index 0000000..eb99b6a --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParamsMapper.as @@ -0,0 +1,55 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsMapper; + import com.dreamsocket.utils.PropertyStringUtil; + + public class OmnitureTrackLinkParamsMapper + { + public function OmnitureTrackLinkParamsMapper() + { + } + + + public function map(p_params:OmnitureTrackLinkParams, p_data:*):OmnitureTrackLinkParams + { + var mapped:OmnitureTrackLinkParams = new OmnitureTrackLinkParams(); + + mapped.name = PropertyStringUtil.evalPropertyString(p_data, p_params.name); + mapped.type = PropertyStringUtil.evalPropertyString(p_data, p_params.type); + mapped.URL = PropertyStringUtil.evalPropertyString(p_data, p_params.URL); + mapped.params = new OmnitureParamsMapper().map(p_params.params, p_data); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTrackParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackParamsMapper.as new file mode 100644 index 0000000..bbc4642 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackParamsMapper.as @@ -0,0 +1,51 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureTrackParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsMapper; + + public class OmnitureTrackParamsMapper + { + public function OmnitureTrackParamsMapper() + { + } + + + public function map(p_params:OmnitureTrackParams, p_data:*):OmnitureTrackParams + { + var mapped:OmnitureTrackParams = new OmnitureTrackParams(); + + mapped.params = new OmnitureParamsMapper().map(p_params.params, p_data); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/url/URLTrackerModule.as b/src/com/dreamsocket/analytics/url/URLTrackerModule.as new file mode 100644 index 0000000..1e77fca --- /dev/null +++ b/src/com/dreamsocket/analytics/url/URLTrackerModule.as @@ -0,0 +1,57 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + + +package com.dreamsocket.analytics.url +{ + import flash.display.Sprite; + + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.ITrackerModule; + import com.dreamsocket.analytics.TrackerModuleParams; + import com.dreamsocket.analytics.url.URLTracker; + import com.dreamsocket.analytics.url.URLTrackerConfigXMLDecoder; + + public class URLTrackerModule extends Sprite implements ITrackerModule + { + public function URLTrackerModule() + { + } + + + public function getTracker(p_params:TrackerModuleParams):ITracker + { + var tracker:URLTracker = new URLTracker(); + + tracker.config = new URLTrackerConfigXMLDecoder().decode(p_params.config); + + return tracker; + } + } +}
dreamsocket/actionscript-analytics-framework
54976adb3264a21011016502bc6a8db66453d347
[CHG] renamed tracking package to analytics [CHG] reworked XML schema for trackers [CHG] reworked OmnitureTracker significantly. all track mappings are now done with a lookup for speed [CHG] renamed Request based classes to Params [NEW] added native bindings for Omniture media calls (open, play, stop, close, track) [NEW] added native bindings for Omniture media params [NEW] create module capability for all Trackers [NEW] created ability to load tracker modules dynamically or statically [NEW] added ANT build file for compiling modules, swc, and package [NEW] added capability to load a modules manifest where trackers can be modules or statically defined, configs can be inline or external XML definitions
diff --git a/bin/daf_google.swf b/bin/daf_google.swf new file mode 100644 index 0000000..d87ff7b Binary files /dev/null and b/bin/daf_google.swf differ diff --git a/bin/daf_javascript.swf b/bin/daf_javascript.swf new file mode 100644 index 0000000..4ec3466 Binary files /dev/null and b/bin/daf_javascript.swf differ diff --git a/bin/daf_omniture.swf b/bin/daf_omniture.swf new file mode 100644 index 0000000..319fc15 Binary files /dev/null and b/bin/daf_omniture.swf differ diff --git a/bin/daf_url.swf b/bin/daf_url.swf new file mode 100644 index 0000000..b24e2c3 Binary files /dev/null and b/bin/daf_url.swf differ diff --git a/bin/dreamsocket_analytics_0.2.100402.swc b/bin/dreamsocket_analytics_0.2.100402.swc new file mode 100644 index 0000000..5a1eccf Binary files /dev/null and b/bin/dreamsocket_analytics_0.2.100402.swc differ diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..1d854d3 --- /dev/null +++ b/build.xml @@ -0,0 +1,117 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project name="dreamsocket_actionscript_analytics" default="buildAll" basedir="."> + + <!-- FLEX TASKS --> + <property name="FLEX_HOME" value="/tools/flash/flexsdk/4_0"/> + <taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar" /> + + <tstamp><format property="build.date" pattern="yyMMdd" locale="en"/></tstamp> + <property name="build.version.major" value="0" /> + <property name="build.version.minor" value="2" /> + <property name="build.version.build" value="0" /> + + <!-- DIRECTORIES --> + <property name="project.libs" value="${basedir}/libs/"/> + <property name="project.output" value="${basedir}/bin/" /> + <property name="project.src" value="${basedir}/src/" /> + <property name="project.name" value="dreamsocket_analytics" /> + + <property name="swf.framerate" value="31" /> + <property name="swf.width" value="480" /> + <property name="swf.height" value="320" /> + + <!-- BUILD ALL --> + <target name="buildAll" depends="clean,buildSWC,buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> + + + <!-- BUILD ALL PLUGINS --> + <target name="buildAllModules" depends="buildGoogleModule,buildJavaScriptModule,buildOmnitureModule,buildURLModule" /> + + + <!-- BUILD GOOGLE PLUGIN --> + <target name="buildGoogleModule"> + <antcall target="compileModule"> + <param name="module.name" value="daf_google" /> + <param name="module.class" value="com/dreamsocket/analytics/google/GoogleTrackerModule.as" /> + </antcall> + </target> + + + <!-- BUILD JAVASCRIPT PLUGIN --> + <target name="buildJavaScriptModule"> + <antcall target="compileModule"> + <param name="module.name" value="daf_javascript" /> + <param name="module.class" value="com/dreamsocket/analytics/js/JSTrackerModule.as" /> + </antcall> + </target> + + + <!-- BUILD OMNITURE PLUGIN --> + <target name="buildOmnitureModule"> + <antcall target="compileModule"> + <param name="module.name" value="daf_omniture" /> + <param name="module.class" value="com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as" /> + </antcall> + </target> + + + <!-- BUILD URL PLUGIN --> + <target name="buildURLModule"> + <antcall target="compileModule"> + <param name="module.name" value="daf_url" /> + <param name="module.class" value="com/dreamsocket/analytics/url/URLTrackerModule.as" /> + </antcall> + </target> + + + <!-- COMPILE SWC --> + <target name="buildSWC"> + <compc output="${project.output}/${project.name}_${build.version.major}.${build.version.minor}.${build.date}.swc"> + <external-library-path dir="${project.libs}/" append="true" includes="**" /> + <include-sources dir="${project.src}" includes="**"/> + </compc> + </target> + + + <!-- COMPILE PLUGIN--> + <target name="compileModule"> + <mxmlc + file="${project.src}${module.class}" + output="${project.output}${module.name}.swf" + strict="true" + static-link-runtime-shared-libraries="true" + > + <default-size + width="1" + height="1" /> + <source-path + path-element="${project.src}"/> + + <compiler.library-path + dir="${basedir}" + append="true"> + <include + name="libs" /> + </compiler.library-path> + </mxmlc> + </target> + + + <!-- CLEAN --> + <target name="clean"> + <mkdir dir="${project.output}"/> + <delete> + <fileset dir="${project.output}" includes="**"/> + </delete> + </target> + + + <!-- PACKAGE --> + <target name="package" depends="buildAll"> + <zip update="true" destfile="${project.output}${project.name}_${build.version.major}.${build.version.minor}.${build.date}.zip" > + <zipfileset dir="${basedir}" includes="bin/**,libs/**,src/**,test/**,build.xml" /> + </zip> + </target> + +</project> + diff --git a/src/com/dreamsocket/tracking/ITrack.as b/src/com/dreamsocket/analytics/ITrack.as similarity index 97% rename from src/com/dreamsocket/tracking/ITrack.as rename to src/com/dreamsocket/analytics/ITrack.as index 17b0b47..0dec3cf 100644 --- a/src/com/dreamsocket/tracking/ITrack.as +++ b/src/com/dreamsocket/analytics/ITrack.as @@ -1,37 +1,37 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking +package com.dreamsocket.analytics { public interface ITrack { function get data():*; function get type():String; } } diff --git a/src/com/dreamsocket/tracking/ITracker.as b/src/com/dreamsocket/analytics/ITracker.as similarity index 91% rename from src/com/dreamsocket/tracking/ITracker.as rename to src/com/dreamsocket/analytics/ITracker.as index f9267bd..b2ee8ec 100644 --- a/src/com/dreamsocket/tracking/ITracker.as +++ b/src/com/dreamsocket/analytics/ITracker.as @@ -1,38 +1,40 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking +package com.dreamsocket.analytics { - import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.analytics.ITrack; public interface ITracker { + function get ID():String; + function track(p_track:ITrack):void } } diff --git a/src/com/dreamsocket/analytics/ITrackerModule.as b/src/com/dreamsocket/analytics/ITrackerModule.as new file mode 100644 index 0000000..ef32a98 --- /dev/null +++ b/src/com/dreamsocket/analytics/ITrackerModule.as @@ -0,0 +1,37 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics +{ + import com.dreamsocket.analytics.TrackerModuleParams; + + public interface ITrackerModule + { + function getTracker(p_paramsL:TrackerModuleParams):ITracker; + } +} diff --git a/src/com/dreamsocket/tracking/Track.as b/src/com/dreamsocket/analytics/Track.as similarity index 95% rename from src/com/dreamsocket/tracking/Track.as rename to src/com/dreamsocket/analytics/Track.as index 5acf52b..75e86de 100644 --- a/src/com/dreamsocket/tracking/Track.as +++ b/src/com/dreamsocket/analytics/Track.as @@ -1,56 +1,56 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking +package com.dreamsocket.analytics { - import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.analytics.ITrack; public class Track implements ITrack { protected var m_data:*; protected var m_type:String; public function Track(p_type:String, p_data:* = null) { this.m_type = p_type; this.m_data = p_data; } public function get data():* { return this.m_data; } public function get type():String { return this.m_type; } } } diff --git a/src/com/dreamsocket/analytics/TrackerManager.as b/src/com/dreamsocket/analytics/TrackerManager.as new file mode 100644 index 0000000..94205bd --- /dev/null +++ b/src/com/dreamsocket/analytics/TrackerManager.as @@ -0,0 +1,88 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics +{ + import flash.utils.Dictionary; + + public class TrackerManager + { + protected static var k_enabled:Boolean = true; + protected static var k_trackers:Dictionary = new Dictionary(); + + + public function TrackerManager() + { + } + + + public static function get enabled():Boolean + { + return k_enabled; + } + + + public static function set enabled(p_enabled:Boolean):void + { + k_enabled = p_enabled; + } + + + + public static function track(p_track:ITrack):void + { + if(!k_enabled) return; + + var tracker:Object; + + // send track payload to all trackers + for each(tracker in k_trackers) + { + ITracker(tracker).track(p_track); + } + } + + + public static function addTracker(p_ID:String, p_tracker:ITracker):void + { + k_trackers[p_ID] = p_tracker; + } + + + public static function getTracker(p_ID:String):ITracker + { + return k_trackers[p_ID] as ITracker; + } + + + public static function removeTracker(p_ID:String):void + { + delete(k_trackers[p_ID]); + } + } +} diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoader.as b/src/com/dreamsocket/analytics/TrackerModuleLoader.as new file mode 100644 index 0000000..a0c03a9 --- /dev/null +++ b/src/com/dreamsocket/analytics/TrackerModuleLoader.as @@ -0,0 +1 @@ +/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.analytics { import com.dreamsocket.analytics.ITracker; import com.dreamsocket.analytics.TrackerModuleParams; import com.dreamsocket.analytics.ITrackerModule; import com.dreamsocket.analytics.TrackerModuleLoaderParams; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import flash.display.Loader; import flash.display.Sprite; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TrackerModuleLoader extends Sprite { private var m_params:TrackerModuleLoaderParams; private var m_config:XML; private var m_module:ITrackerModule; private var m_configLoader:URLLoader; private var m_moduleLoader:Loader; public function TrackerModuleLoader() { } public function destroy():void { if(this.m_configLoader) { this.m_configLoader.removeEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_configLoader.close(); } catch(error:Error){} this.m_configLoader = null; } if(this.m_moduleLoader) { this.m_moduleLoader.contentLoaderInfo.removeEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.close(); } catch(error:Error){} try { this.m_moduleLoader.unload(); } catch(error:Error){} this.m_moduleLoader = null; } this.m_params = null; this.m_config = null; this.m_module = null; } public function load(p_resource:TrackerModuleLoaderParams):void { this.destroy(); this.m_params = p_resource; this.loadConfig(); } private function createModule():void { var params:TrackerModuleParams = new TrackerModuleParams(); params.stage = this.m_params.stage; params.config = this.m_config; try { var tracker:ITracker = this.m_module.getTracker(params); var loadParams:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_LOADED, loadParams, tracker)); } catch(error:Error) { trace("moduleLoaded:" + error) this.dispatchError(error.message); } } public function loadConfig():void { if(this.m_params.config is XML) { // this is XML load module this.m_config = this.m_params.config; this.loadModule(); trace("config XML") return; } this.m_configLoader = new URLLoader(); this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { trace("config URL " + this.m_params.config) this.m_configLoader.load(new URLRequest(this.m_params.config)); } catch(error:Error) { trace("loadConfig:" + error) this.dispatchError(error.message); } } private function loadModule():void { if(this.m_params.resource is ITrackerModule) { this.m_module = this.m_params.resource; this.createModule(); return; } // load the module this.m_moduleLoader = new Loader(); this.m_moduleLoader.contentLoaderInfo.addEventListener(Event.INIT, this.onModuleLoaded); this.m_moduleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_moduleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); try { this.m_moduleLoader.load(new URLRequest(this.m_params.resource)); } catch(error:Error) { trace("loadModule:" +error) this.dispatchError(error.message); } } private function dispatchError(p_message:String):void { trace("---" + p_message) var params:TrackerModuleLoaderParams = this.m_params; this.destroy(); this.dispatchEvent(new TrackerModuleLoaderEvent(TrackerModuleLoaderEvent.MODULE_FAILED, params)); } private function onErrorOccurred(p_event:ErrorEvent):void { trace(p_event) this.dispatchError(p_event.text); } private function onConfigLoaded(p_event:Event):void { trace("config loaded") try { this.m_config = new XML(this.m_configLoader.data); this.loadModule(); } catch(error:Error) { this.dispatchError(error.message); } } private function onModuleLoaded(p_event:Event):void { this.m_module = ITrackerModule(this.m_moduleLoader.content); this.createModule(); } } } \ No newline at end of file diff --git a/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as b/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as new file mode 100644 index 0000000..f035ebf --- /dev/null +++ b/src/com/dreamsocket/analytics/TrackerModuleLoaderQueue.as @@ -0,0 +1,101 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package com.dreamsocket.analytics +{ + import flash.events.Event; + import flash.events.EventDispatcher; + + import com.dreamsocket.analytics.TrackerModuleLoader; + import com.dreamsocket.analytics.TrackerModuleLoaderEvent; + import com.dreamsocket.analytics.TrackerModuleLoaderParams; + + + public class TrackerModuleLoaderQueue extends EventDispatcher + { + private var m_manifest:Array; + private var m_moduleLoader:TrackerModuleLoader; + + public function TrackerModuleLoaderQueue() + { + this.m_manifest = []; + this.m_moduleLoader = new TrackerModuleLoader(); + this.m_moduleLoader.addEventListener(TrackerModuleLoaderEvent.MODULE_LOADED, this.onModuleLoaded); + this.m_moduleLoader.addEventListener(TrackerModuleLoaderEvent.MODULE_FAILED, this.onModuleFailed); + } + + + public function set manifest(p_value:Array):void + { + this.m_manifest = p_value; + } + + + public function add(p_params:TrackerModuleLoaderParams):void + { + this.m_manifest.push(p_params); + } + + + public function destroy():void + { + this.m_moduleLoader.destroy(); + this.m_manifest.slice(); + } + + + public function load():void + { + var params:TrackerModuleLoaderParams = TrackerModuleLoaderParams(this.m_manifest.shift()); + + if(params) + { + this.m_moduleLoader.load(params); + } + else + { + trace("done") + this.dispatchEvent(new Event(Event.COMPLETE)); + } + } + + + private function onModuleFailed(p_event:TrackerModuleLoaderEvent):void + { + trace("failed") + this.load(); + } + + + private function onModuleLoaded(p_event:TrackerModuleLoaderEvent):void + { + trace("created" + p_event.tracker) + TrackerManager.addTracker(p_event.tracker.ID, p_event.tracker); + this.load(); + } + } +} diff --git a/src/com/dreamsocket/tracking/TrackingManager.as b/src/com/dreamsocket/analytics/TrackingManager.as similarity index 100% rename from src/com/dreamsocket/tracking/TrackingManager.as rename to src/com/dreamsocket/analytics/TrackingManager.as diff --git a/src/com/dreamsocket/analytics/google/GoogleSingleton.as b/src/com/dreamsocket/analytics/google/GoogleSingleton.as new file mode 100644 index 0000000..ec0ac7e --- /dev/null +++ b/src/com/dreamsocket/analytics/google/GoogleSingleton.as @@ -0,0 +1,71 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.google +{ + import flash.display.Stage; + + import com.google.analytics.GATracker; + + public class GoogleSingleton + { + protected static var k_stage:Stage; + protected static var k_instance:GATracker; + + public function GoogleSingleton() + { + } + + + public static function set stage(p_value:Stage):void + { + k_stage = p_value; + } + + + public static function create(p_account:String, p_trackingMode:String, p_visualDebug:Boolean, p_stage:Stage = null):GATracker + { + if(k_stage == null) + { + k_stage = p_stage; + } + if(k_instance == null) + { + k_instance = new GATracker(k_stage, p_account, p_trackingMode, p_visualDebug); + } + + return k_instance; + } + + + public static function get instance():GATracker + { + return k_instance; + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as b/src/com/dreamsocket/analytics/google/GoogleTrackEventParams.as similarity index 93% rename from src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as rename to src/com/dreamsocket/analytics/google/GoogleTrackEventParams.as index ea1542b..3a0101e 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as +++ b/src/com/dreamsocket/analytics/google/GoogleTrackEventParams.as @@ -1,58 +1,58 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.google +package com.dreamsocket.analytics.google { - public class GoogleTrackEventRequest + public class GoogleTrackEventParams { /** * specifies a string representing groups of events. */ public var category:String; /** * specifies a string that is paired with each category and is typically used to track activities */ public var action:String; /** * specifies an optional string that provides additional scoping to the category/action pairing */ public var label:String; /** * specifies an optional non negative integer for numerical data */ public var value:String; - public function GoogleTrackEventRequest() + public function GoogleTrackEventParams() { } } } diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as b/src/com/dreamsocket/analytics/google/GoogleTrackHandler.as similarity index 89% rename from src/com/dreamsocket/tracking/google/GoogleTrackHandler.as rename to src/com/dreamsocket/analytics/google/GoogleTrackHandler.as index f7bcb41..592c5f7 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as +++ b/src/com/dreamsocket/analytics/google/GoogleTrackHandler.as @@ -1,40 +1,41 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.google +package com.dreamsocket.analytics.google { public class GoogleTrackHandler { public var ID:String; - public var request:Object; // GoogleTrackPageViewRequest, GoogleTrackEventRequest + public var params:Object; // GoogleTrackPageViewRequest, GoogleTrackEventRequest + public var type:String; public function GoogleTrackHandler() { } } } diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as b/src/com/dreamsocket/analytics/google/GoogleTrackPageViewParams.as similarity index 90% rename from src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as rename to src/com/dreamsocket/analytics/google/GoogleTrackPageViewParams.as index 42312ed..e2af61a 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as +++ b/src/com/dreamsocket/analytics/google/GoogleTrackPageViewParams.as @@ -1,39 +1,39 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.google +package com.dreamsocket.analytics.google { - public class GoogleTrackPageViewRequest + public class GoogleTrackPageViewParams { public var URL:String; - public function GoogleTrackPageViewRequest() + public function GoogleTrackPageViewParams() { } } } diff --git a/src/com/dreamsocket/tracking/google/GoogleTracker.as b/src/com/dreamsocket/analytics/google/GoogleTracker.as similarity index 53% rename from src/com/dreamsocket/tracking/google/GoogleTracker.as rename to src/com/dreamsocket/analytics/google/GoogleTracker.as index 2efea8a..abe1f78 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTracker.as +++ b/src/com/dreamsocket/analytics/google/GoogleTracker.as @@ -1,172 +1,172 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.google +package com.dreamsocket.analytics.google { - import flash.display.DisplayObject; + import flash.display.Stage; import flash.utils.Dictionary; import com.dreamsocket.utils.PropertyStringUtil; - import com.dreamsocket.tracking.ITrack; - import com.dreamsocket.tracking.ITracker; - import com.dreamsocket.tracking.google.GoogleTrackerConfig; - import com.dreamsocket.tracking.google.GoogleTrackEventRequest; - import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; - import com.dreamsocket.tracking.google.GoogleTrackHandler; + import com.dreamsocket.analytics.ITrack; + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.google.GoogleSingleton; + import com.dreamsocket.analytics.google.GoogleTrackerConfig; + import com.dreamsocket.analytics.google.GoogleTrackHandler; import com.google.analytics.GATracker; public class GoogleTracker implements ITracker { - public static var display:DisplayObject; - public static const ID:String = "GoogleTracker"; protected var m_config:GoogleTrackerConfig; - protected var m_display:DisplayObject; protected var m_enabled:Boolean; protected var m_service:GATracker; - protected var m_trackHandlers:Dictionary; + protected var m_handlers:Dictionary; - public function GoogleTracker(p_display:DisplayObject = null) + public function GoogleTracker(p_stage:Stage = null) { super(); + GoogleSingleton.stage = p_stage; this.m_config = new GoogleTrackerConfig(); - this.m_display = p_display; this.m_enabled = true; - this.m_trackHandlers = new Dictionary(); + this.m_handlers = new Dictionary(); } public function get config():GoogleTrackerConfig { return this.m_config; } - + public function set config(p_value:GoogleTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; try { - this.m_service = new GATracker(this.m_display == null ? GoogleTracker.display : this.m_display, p_value.account, p_value.trackingMode, p_value.visualDebug); + this.m_service = GoogleSingleton.create(p_value.account, p_value.trackingMode, p_value.visualDebug); } catch(error:Error) { trace(error); } this.m_enabled = p_value.enabled; - this.m_trackHandlers = p_value.trackHandlers; + this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } + + public function get ID():String + { + return GoogleTracker.ID; + } + - public function addTrackHandler(p_ID:String, p_trackHandler:GoogleTrackHandler):void + public function addTrackHandler(p_ID:String, p_handler:GoogleTrackHandler):void { - this.m_trackHandlers[p_ID] = p_trackHandler; + this.m_handlers[p_ID] = p_handler; } public function destroy():void { } public function getTrackHandler(p_ID:String):GoogleTrackHandler { - return this.m_trackHandlers[p_ID] as GoogleTrackHandler; + return this.m_handlers[p_ID] as GoogleTrackHandler; } public function removeTrackHandler(p_ID:String):void { - delete(this.m_trackHandlers[p_ID]); + delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled || this.m_service == null) return; - var handler:GoogleTrackHandler = this.m_config.trackHandlers[p_track.type]; + var handler:GoogleTrackHandler = this.m_config.handlers[p_track.type]; if(handler != null) { // has a track handler // call correct track method - if(handler.request is GoogleTrackEventRequest) + switch(handler.type) { - var eventRequest:GoogleTrackEventRequest = GoogleTrackEventRequest(handler.request); - var category:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.category); - var action:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.action); - var label:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.label); - var value:Number = Number(PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.value)); + case GoogleTrackType.TRACK_EVENT: + var category:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.params.category); + var action:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.params.action); + var label:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.params.label); + var value:Number = Number(PropertyStringUtil.evalPropertyString(p_track.data, handler.params.value)); - try - { - this.m_service.trackEvent(category, action, label, value); - } - catch(error:Error) - { - trace(error); - } - } - else if(handler.request is GoogleTrackPageViewRequest) - { - var viewRequest:GoogleTrackPageViewRequest = GoogleTrackPageViewRequest(handler.request); - - try - { - this.m_service.trackPageview(PropertyStringUtil.evalPropertyString(p_track.data, viewRequest.URL)); - } - catch(error:Error) - { - trace(error); - } + try + { + this.m_service.trackEvent(category, action, label, value); + } + catch(error:Error) + { + trace(error); + } + break; + case GoogleTrackType.TRACK_PAGE_VIEW: + try + { + this.m_service.trackPageview(PropertyStringUtil.evalPropertyString(p_track.data, handler.params.URL)); + } + catch(error:Error) + { + trace(error); + } + break; } } } } } diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as b/src/com/dreamsocket/analytics/google/GoogleTrackerConfig.as similarity index 92% rename from src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as rename to src/com/dreamsocket/analytics/google/GoogleTrackerConfig.as index bcc3ebe..4431c59 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as +++ b/src/com/dreamsocket/analytics/google/GoogleTrackerConfig.as @@ -1,52 +1,52 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.google +package com.dreamsocket.analytics.google { import flash.utils.Dictionary; import com.google.analytics.core.TrackerMode; public class GoogleTrackerConfig { public var account:String; public var enabled:Boolean; public var trackingMode:String; public var visualDebug:Boolean; - public var trackHandlers:Dictionary; + public var handlers:Dictionary; public function GoogleTrackerConfig() { this.enabled = true; this.trackingMode = TrackerMode.AS3; - this.trackHandlers = new Dictionary(); + this.handlers = new Dictionary(); } } } diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as b/src/com/dreamsocket/analytics/google/GoogleTrackerConfigXMLDecoder.as similarity index 56% rename from src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as rename to src/com/dreamsocket/analytics/google/GoogleTrackerConfigXMLDecoder.as index b1a01db..8cc01d3 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/analytics/google/GoogleTrackerConfigXMLDecoder.as @@ -1,115 +1,98 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.google +package com.dreamsocket.analytics.google { import flash.utils.Dictionary; - import com.dreamsocket.tracking.google.GoogleTrackerConfig; - import com.dreamsocket.tracking.google.GoogleTrackHandler; - import com.dreamsocket.tracking.google.GoogleTrackEventRequest; - import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; + import com.dreamsocket.analytics.google.GoogleTrackerConfig; + import com.dreamsocket.analytics.google.GoogleTrackHandler; + import com.dreamsocket.analytics.google.GoogleTrackEventParamsXMLDecoder; + import com.dreamsocket.analytics.google.GoogleTrackPageViewParamsXMLDecoder; + import com.dreamsocket.analytics.google.GoogleTrackType; import com.google.analytics.core.TrackerMode; public class GoogleTrackerConfigXMLDecoder { + protected var m_decoders:Dictionary; + public function GoogleTrackerConfigXMLDecoder() { super(); + + this.m_decoders = new Dictionary(); + this.m_decoders[GoogleTrackType.TRACK_EVENT] = new GoogleTrackEventParamsXMLDecoder(); + this.m_decoders[GoogleTrackType.TRACK_PAGE_VIEW] = new GoogleTrackPageViewParamsXMLDecoder(); } - + public function decode(p_XML:XML):GoogleTrackerConfig { var config:GoogleTrackerConfig = new GoogleTrackerConfig(); if(p_XML.account.toString().length) config.account = p_XML.account.toString(); config.enabled = p_XML.enabled.toString() != "false"; config.trackingMode = p_XML.trackingMode.toString() == TrackerMode.AS3 ? TrackerMode.AS3 : TrackerMode.BRIDGE; config.visualDebug = p_XML.visualDebug.toString() != "false"; - this.setTrackHandlers(config.trackHandlers, p_XML.trackHandlers.trackHandler); + this.setTrackHandlers(config.handlers, p_XML.handlers.handler); return config; } public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void { var handler:GoogleTrackHandler; var handlerNode:XML; var ID:String; - var eventRequest:GoogleTrackEventRequest; - var pageViewRequest:GoogleTrackPageViewRequest; - var trackNode:XML; for each(handlerNode in p_handlerNodes) { ID = handlerNode.ID.toString(); if(ID.length > 0) { - if(handlerNode.trackEvent.toString().length) - { // decode trackPageView - handler = new GoogleTrackHandler(); - handler.ID = ID; - handler.request = eventRequest = new GoogleTrackEventRequest(); - trackNode = handlerNode.trackEvent[0]; - - if(trackNode.action.toString().length) - eventRequest.action = trackNode.action.toString(); - if(trackNode.category.toString().length) - eventRequest.category = trackNode.category.toString(); - if(trackNode.label.toString().length) - eventRequest.label = trackNode.label.toString(); - if(trackNode.value.toString().length) - eventRequest.value = trackNode.value.toString(); - - p_handlers[ID] = handler; + handler = new GoogleTrackHandler(); + handler.ID = ID; + handler.type = handlerNode.type.toString(); + + if(this.m_decoders[handler.type]) + { + handler.params = this.m_decoders[handler.type].decode(handlerNode.params[0]); + p_handlers[ID] = handler; } - else if(handlerNode.trackPageView.toString().length) - { // decode track - handler = new GoogleTrackHandler(); - handler.ID = ID; - handler.request = pageViewRequest = new GoogleTrackPageViewRequest(); - trackNode = handlerNode.trackPageView[0]; - - if(trackNode.URL.toString().length) - pageViewRequest.URL = trackNode.URL.toString(); - - p_handlers[ID] = handler; - } } } } } } diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as b/src/com/dreamsocket/analytics/google/GoogleTrackerParams.as similarity index 96% rename from src/com/dreamsocket/tracking/google/GoogleTrackerParams.as rename to src/com/dreamsocket/analytics/google/GoogleTrackerParams.as index beae71c..6c5505f 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as +++ b/src/com/dreamsocket/analytics/google/GoogleTrackerParams.as @@ -1,34 +1,34 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.google +package com.dreamsocket.analytics.google { public class GoogleTrackerParams { } } diff --git a/src/com/dreamsocket/tracking/js/JSMethodCall.as b/src/com/dreamsocket/analytics/js/JSMethodCall.as similarity index 100% rename from src/com/dreamsocket/tracking/js/JSMethodCall.as rename to src/com/dreamsocket/analytics/js/JSMethodCall.as diff --git a/src/com/dreamsocket/tracking/js/JSTrackHandler.as b/src/com/dreamsocket/analytics/js/JSTrackHandler.as similarity index 89% rename from src/com/dreamsocket/tracking/js/JSTrackHandler.as rename to src/com/dreamsocket/analytics/js/JSTrackHandler.as index d87c32d..8a6c70f 100644 --- a/src/com/dreamsocket/tracking/js/JSTrackHandler.as +++ b/src/com/dreamsocket/analytics/js/JSTrackHandler.as @@ -1,43 +1,43 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.js +package com.dreamsocket.analytics.js { public class JSTrackHandler { public var ID:String; - public var methodCalls:Array; + public var params:JSTrackParams; - public function JSTrackHandler(p_ID:String = null, p_methodCalls:Array = null) + public function JSTrackHandler(p_ID:String = null, p_methodCall:JSTrackParams = null) { this.ID = p_ID; - this.methodCalls = p_methodCalls == null ? [] : p_methodCalls; + this.params = p_methodCall; } } } diff --git a/src/com/dreamsocket/analytics/js/JSTrackParams.as b/src/com/dreamsocket/analytics/js/JSTrackParams.as new file mode 100644 index 0000000..8f6868c --- /dev/null +++ b/src/com/dreamsocket/analytics/js/JSTrackParams.as @@ -0,0 +1,42 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.js +{ + public class JSTrackParams + { + public var method:String; + public var arguments:Array; + + public function JSTrackParams(p_method:String = null, p_arguments:Array = null) + { + this.method = p_method; + this.arguments = p_arguments == null ? [] : p_arguments; + } + } +} diff --git a/src/com/dreamsocket/tracking/js/JSTracker.as b/src/com/dreamsocket/analytics/js/JSTracker.as similarity index 74% rename from src/com/dreamsocket/tracking/js/JSTracker.as rename to src/com/dreamsocket/analytics/js/JSTracker.as index 3593a72..24ca423 100644 --- a/src/com/dreamsocket/tracking/js/JSTracker.as +++ b/src/com/dreamsocket/analytics/js/JSTracker.as @@ -1,154 +1,151 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.js +package com.dreamsocket.analytics.js { import flash.external.ExternalInterface; import flash.utils.Dictionary; import com.dreamsocket.utils.PropertyStringUtil; - import com.dreamsocket.tracking.ITrack; - import com.dreamsocket.tracking.ITracker; - import com.dreamsocket.tracking.js.JSTrackerConfig; - import com.dreamsocket.tracking.js.JSTrackHandler; + import com.dreamsocket.analytics.ITrack; + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.js.JSTrackerConfig; + import com.dreamsocket.analytics.js.JSTrackHandler; public class JSTracker implements ITracker { public static const ID:String = "JSTracker"; protected var m_config:JSTrackerConfig; protected var m_enabled:Boolean; - protected var m_trackHandlers:Dictionary; + protected var m_handlers:Dictionary; public function JSTracker() { super(); this.m_config = new JSTrackerConfig(); this.m_enabled = true; - this.m_trackHandlers = new Dictionary(); + this.m_handlers = new Dictionary(); } public function get config():JSTrackerConfig { return this.m_config; } public function set config(p_value:JSTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; this.m_enabled = p_value.enabled; - this.m_trackHandlers = p_value.trackHandlers; + this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } - public function addTrackHandler(p_ID:String, p_trackHandler:JSTrackHandler):void + public function get ID():String + { + return JSTracker.ID; + } + + + public function addTrackHandler(p_ID:String, p_handler:JSTrackHandler):void { - this.m_trackHandlers[p_ID] = p_trackHandler; + this.m_handlers[p_ID] = p_handler; } public function getTrackHandler(p_ID:String):JSTrackHandler { - return this.m_trackHandlers[p_ID] as JSTrackHandler; + return this.m_handlers[p_ID] as JSTrackHandler; } public function removeTrackHandler(p_ID:String):void { - delete(this.m_trackHandlers[p_ID]); + delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled) return; - var handler:JSTrackHandler = this.m_trackHandlers[p_track.type]; + var handler:JSTrackHandler = this.m_handlers[p_track.type]; if(handler != null) { // has the track type - var methodCalls:Array = handler.methodCalls; - var i:int = 0; - var len:uint = methodCalls.length; - - while(i < len) - { - this.performJSCall(JSMethodCall(methodCalls[i]), p_track.data); - i++; - } + this.performJSCall(handler.params, p_track.data); } } - protected function performJSCall(p_methodCall:JSMethodCall, p_data:* = null):void + protected function performJSCall(p_methodCall:JSTrackParams, p_data:* = null):void { - ; if(ExternalInterface.available) { try { var args:Array = p_methodCall.arguments.concat(); var i:int = args.length; while(i--) { args[i] = PropertyStringUtil.evalPropertyString(p_data, args[i]); } args.unshift(p_methodCall.method); ExternalInterface.call.apply(ExternalInterface, args); } catch(error:Error) { // do nothing trace("JSTracker.track - " + error); } } } } } \ No newline at end of file diff --git a/src/com/dreamsocket/tracking/js/JSTrackerConfig.as b/src/com/dreamsocket/analytics/js/JSTrackerConfig.as similarity index 91% rename from src/com/dreamsocket/tracking/js/JSTrackerConfig.as rename to src/com/dreamsocket/analytics/js/JSTrackerConfig.as index 719673d..54a7e1d 100644 --- a/src/com/dreamsocket/tracking/js/JSTrackerConfig.as +++ b/src/com/dreamsocket/analytics/js/JSTrackerConfig.as @@ -1,45 +1,45 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.js +package com.dreamsocket.analytics.js { import flash.utils.Dictionary; public class JSTrackerConfig { public var enabled:Boolean; - public var trackHandlers:Dictionary; + public var handlers:Dictionary; public function JSTrackerConfig() { this.enabled = true; - this.trackHandlers = new Dictionary(); + this.handlers = new Dictionary(); } } } diff --git a/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as b/src/com/dreamsocket/analytics/js/JSTrackerConfigXMLDecoder.as similarity index 57% rename from src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as rename to src/com/dreamsocket/analytics/js/JSTrackerConfigXMLDecoder.as index ad0d68f..c629015 100644 --- a/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/analytics/js/JSTrackerConfigXMLDecoder.as @@ -1,97 +1,84 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.js +package com.dreamsocket.analytics.js { import flash.utils.Dictionary; - import com.dreamsocket.tracking.js.JSTrackerConfig; - import com.dreamsocket.tracking.js.JSTrackHandler; - + import com.dreamsocket.analytics.js.JSTrackerConfig; + import com.dreamsocket.analytics.js.JSTrackHandler; + import com.dreamsocket.analytics.js.JSTrackParamsXMLDecoder; public class JSTrackerConfigXMLDecoder { + protected var m_paramsDecoder:JSTrackParamsXMLDecoder; + public function JSTrackerConfigXMLDecoder() { + this.m_paramsDecoder = new JSTrackParamsXMLDecoder(); } - + public function decode(p_xml:XML):JSTrackerConfig { var config:JSTrackerConfig = new JSTrackerConfig(); - var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; - var trackHandlerNode:XML; - var trackHandlers:Dictionary = config.trackHandlers; + var handlerNodes:XMLList = p_xml.handlers.handler; + var handlerNode:XML; + var handlers:Dictionary = config.handlers; - // trackHandlers - for each(trackHandlerNode in trackHandlerNodes) + // handlers + for each(handlerNode in handlerNodes) { - this.addTrack(trackHandlers, trackHandlerNode); + this.addTrack(handlers, handlerNode); } // enabled config.enabled = p_xml.enabled.toString() != "false"; return config; } - protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void + protected function addTrack(p_handlers:Dictionary, p_handlerNode:XML):void { - var ID:String = p_trackHandlerNode.ID.toString(); - var methodCallNode:XML; + var ID:String = p_handlerNode.ID.toString(); var handler:JSTrackHandler; if(ID.length > 0) { handler = new JSTrackHandler(); - for each(methodCallNode in p_trackHandlerNode.methodCalls.methodCall) + handler.ID = ID; + + if(p_handlerNode.params[0] != null) { - handler.ID = ID; - handler.methodCalls.push(this.createMethodCall(methodCallNode[0])); + handler.params = (this.m_paramsDecoder.decode(p_handlerNode.params[0])); + p_handlers[ID] = handler; } - p_trackHandlers[ID] = handler; - } - } - - protected function createMethodCall(p_methodNode:XML):JSMethodCall - { - var methodCall:JSMethodCall = new JSMethodCall(p_methodNode.ID.toString()); - var argumentNodes:XMLList = p_methodNode.arguments.argument; - var argumentNode:XML; - - methodCall.method = p_methodNode.method.toString(); - - for each(argumentNode in argumentNodes) - { - methodCall.arguments.push(argumentNode); } - - return methodCall; } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParams.as new file mode 100644 index 0000000..694b831 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaCloseParams.as @@ -0,0 +1,44 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureParams; + + public class OmnitureMediaCloseParams + { + public var mediaName:String; + public var mediaOffset:String; + public var params:OmnitureParams; + + public function OmnitureMediaCloseParams() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParams.as new file mode 100644 index 0000000..387e926 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaOpenParams.as @@ -0,0 +1,46 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureParams; + + public class OmnitureMediaOpenParams + { + public var mediaName:String; + public var mediaLength:String; + public var mediaPlayerName:String; + public var params:OmnitureParams; + + public function OmnitureMediaOpenParams() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaParams.as new file mode 100644 index 0000000..ebdbd66 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaParams.as @@ -0,0 +1,45 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + public class OmnitureMediaParams + { + public var autoTrack:Boolean; + public var playerName:String; + public var trackVars:String; + public var trackEvents:String; + public var trackWhilePlaying:Boolean; + public var trackSeconds:Number; + public var trackMilestones:String; + + public function OmnitureMediaParams() + { + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaParamsMapper.as new file mode 100644 index 0000000..1453253 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaParamsMapper.as @@ -0,0 +1,56 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaParams; + import com.dreamsocket.utils.PropertyStringUtil; + + public class OmnitureMediaParamsMapper + { + public function OmnitureMediaParamsMapper() + { + } + + public function map(p_params:OmnitureMediaParams, p_data:*):OmnitureMediaParams + { + var mapped:OmnitureMediaParams = new OmnitureMediaParams(); + + if(p_params.playerName != null) + mapped.playerName = PropertyStringUtil.evalPropertyString(p_data, p_params.playerName); + if(p_params.trackVars != null) + mapped.trackVars = PropertyStringUtil.evalPropertyString(p_data, p_params.trackVars); + if(p_params.trackEvents != null) + mapped.trackEvents = PropertyStringUtil.evalPropertyString(p_data, p_params.trackEvents); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaParamsXMLDecoder.as new file mode 100644 index 0000000..b2fc835 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaParamsXMLDecoder.as @@ -0,0 +1,65 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureMediaParams; + + + public class OmnitureMediaParamsXMLDecoder + { + public function OmnitureMediaParamsXMLDecoder() + { + } + + + public function decode(p_paramNodes:XML):OmnitureMediaParams + { + var params:OmnitureMediaParams = new OmnitureMediaParams(); + + if(p_paramNodes == null) return params; + + if(p_paramNodes.autoTrack.toString().length) + params.autoTrack = p_paramNodes.autoTrack.toString() == "true"; + if(p_paramNodes.trackWhilePlaying.toString().length) + params.trackWhilePlaying = p_paramNodes.trackWhilePlaying.toString() == "true"; + if(p_paramNodes.playerName.toString().length) + params.playerName = p_paramNodes.playerName.toString(); + if(p_paramNodes.trackVars.toString().length) + params.trackVars = p_paramNodes.trackVars.toString(); + if(p_paramNodes.trackEvents.toString().length) + params.trackEvents = p_paramNodes.trackEvents.toString(); + if(p_paramNodes.trackMilestones.toString().length) + params.trackMilestones = p_paramNodes.trackMilestones.toString(); + if(p_paramNodes.trackSeconds.toString().length) + params.trackSeconds = Number(p_paramNodes.trackSeconds.toString()); + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParams.as new file mode 100644 index 0000000..f80d72e --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaPlayParams.as @@ -0,0 +1,44 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureParams; + + public class OmnitureMediaPlayParams + { + public var mediaName:String; + public var mediaOffset:String; + public var params:OmnitureParams; + + public function OmnitureMediaPlayParams() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParams.as new file mode 100644 index 0000000..c452862 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaStopParams.as @@ -0,0 +1,44 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureParams; + + public class OmnitureMediaStopParams + { + public var mediaName:String; + public var mediaOffset:String; + public var params:OmnitureParams; + + public function OmnitureMediaStopParams() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParams.as new file mode 100644 index 0000000..af98435 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureMediaTrackParams.as @@ -0,0 +1,43 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureParams; + + public class OmnitureMediaTrackParams + { + public var mediaName:String; + public var params:OmnitureParams; + + public function OmnitureMediaTrackParams() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureParams.as b/src/com/dreamsocket/analytics/omniture/OmnitureParams.as similarity index 91% rename from src/com/dreamsocket/tracking/omniture/OmnitureParams.as rename to src/com/dreamsocket/analytics/omniture/OmnitureParams.as index 559929b..201335a 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureParams.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureParams.as @@ -1,67 +1,71 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.omniture +package com.dreamsocket.analytics.omniture { - + import com.dreamsocket.analytics.omniture.OmnitureMediaParams; + public dynamic class OmnitureParams { // debug vars public var debugTracking:Boolean; public var trackLocal:Boolean; // required public var account:String; public var dc:String; public var pageName:String; public var pageURL:String; public var visitorNameSpace:String; // optional public var autoTrack:Boolean; public var charSet:String; public var cookieDomainPeriods:Number; public var cookieLifetime:String; public var currencyCode:String; public var delayTracking:Number; public var events:String; public var linkLeaveQueryString:Boolean; public var movieID:String; public var pageType:String; public var referrer:String; public var trackClickMap:Boolean; public var trackingServer:String; public var trackingServerBase:String; public var trackingServerSecure:String; public var vmk:String; + + public var Media:OmnitureMediaParams; public function OmnitureParams() - { + { + this.Media = new OmnitureMediaParams(); } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureParamsMapper.as b/src/com/dreamsocket/analytics/omniture/OmnitureParamsMapper.as new file mode 100644 index 0000000..c2d72b2 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureParamsMapper.as @@ -0,0 +1,75 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + + + +package com.dreamsocket.analytics.omniture +{ + import flash.utils.describeType; + + import com.dreamsocket.analytics.omniture.OmnitureParams; + import com.dreamsocket.analytics.omniture.OmnitureMediaParamsMapper; + import com.dreamsocket.utils.PropertyStringUtil; + + public class OmnitureParamsMapper + { + public function OmnitureParamsMapper() + { + } + + public function map(p_params:OmnitureParams, p_data:*):OmnitureParams + { + var mapped:OmnitureParams = new OmnitureParams(); + var desc:XML = describeType(p_params); + var propNode:XML; + var props:XMLList = desc..variable; + var prop:String; + var val:*; + + // instance props + for each(propNode in props) + { + prop = propNode.@name; + val = p_params[prop]; + if(val is String && val != null) + { + mapped[prop] = PropertyStringUtil.evalPropertyString(p_data, val); + } + } + // dynamic prop + for(prop in p_params) + { + mapped[prop] = PropertyStringUtil.evalPropertyString(p_data, p_params[prop]); + } + + mapped.Media = new OmnitureMediaParamsMapper().map(p_params.Media, p_data); + + return mapped; + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureParamsXMLDecoder.as similarity index 84% rename from src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as rename to src/com/dreamsocket/analytics/omniture/OmnitureParamsXMLDecoder.as index 0a25915..5b8462a 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureParamsXMLDecoder.as @@ -1,109 +1,113 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.omniture +package com.dreamsocket.analytics.omniture { - import com.dreamsocket.tracking.omniture.OmnitureParams; + import com.dreamsocket.analytics.omniture.OmnitureParams; public class OmnitureParamsXMLDecoder { - protected var m_params:OmnitureParams; - - public function OmnitureParamsXMLDecoder() { } public function decode(p_paramNodes:XML):OmnitureParams { var params:OmnitureParams = new OmnitureParams(); if(p_paramNodes == null) return params; + // debug if(p_paramNodes.debugTracking.toString().length) params.debugTracking = p_paramNodes.debugTracking.toString() == "true"; if(p_paramNodes.trackLocal.toString().length) params.trackLocal = p_paramNodes.trackLocal.toString() == "true"; // required if(p_paramNodes.account.toString().length) params.account = p_paramNodes.account.toString(); if(p_paramNodes.dc.toString().length) params.dc = p_paramNodes.dc.toString(); if(p_paramNodes.pageName.toString().length) params.pageName = p_paramNodes.pageName.toString(); if(p_paramNodes.pageURL.toString().length) params.pageURL = p_paramNodes.pageURL.toString(); if(p_paramNodes.visitorNameSpace.toString().length) params.visitorNameSpace = p_paramNodes.visitorNameSpace.toString(); // optional if(p_paramNodes.autoTrack.length()) params.autoTrack = p_paramNodes.autoTrack.toString() == "true"; if(p_paramNodes.charSet.length()) params.charSet = p_paramNodes.charSet.toString(); if(p_paramNodes.cookieDomainPeriods.length()) params.cookieDomainPeriods = int(p_paramNodes.cookieDomainPeriods.toString()); if(p_paramNodes.cookieLifetime.length()) params.cookieLifetime = p_paramNodes.cookieLifetime.toString(); if(p_paramNodes.currencyCode.length()) params.currencyCode = p_paramNodes.currencyCode.toString(); if(p_paramNodes.delayTracking.length()) params.delayTracking = Number(p_paramNodes.delayTracking.toString()); if(p_paramNodes.linkLeaveQueryString.length()) params.linkLeaveQueryString = p_paramNodes.linkLeaveQueryString.toString() == true; if(p_paramNodes.pageType.length()) params.pageType = p_paramNodes.pageType.toString(); if(p_paramNodes.referrer.length()) params.referrer = p_paramNodes.referrer.toString(); if(p_paramNodes.trackClickMap.length()) params.trackClickMap = p_paramNodes.trackClickMap.toString() == "true"; - if(p_paramNodes.trackingServer.length()) - params.trackingServer = p_paramNodes.trackingServer.toString(); - if(p_paramNodes.trackingServerBase.length()) - params.trackingServerBase = p_paramNodes.trackingServerBase.toString(); - if(p_paramNodes.trackingServerSecure.length()) - params.trackingServerSecure = p_paramNodes.trackingServerSecure.toString(); + if(p_paramNodes.analyticsServer.length()) + params.analyticsServer = p_paramNodes.analyticsServer.toString(); + if(p_paramNodes.analyticsServerBase.length()) + params.analyticsServerBase = p_paramNodes.analyticsServerBase.toString(); + if(p_paramNodes.analyticsServerSecure.length()) + params.analyticsServerSecure = p_paramNodes.analyticsServerSecure.toString(); if(p_paramNodes.vmk.length()) params.vmk = p_paramNodes.vmk.toString(); var paramNode:XML; for each(paramNode in p_paramNodes.*) { if(params[paramNode.name()] == undefined) { params[paramNode.name()] = paramNode.toString(); } } + // media params + var mediaNode:XML = p_paramNodes.Media[0]; + if(mediaNode != null) + { + params.Media = new OmnitureMediaParamsXMLDecoder().decode(mediaNode); + } return params; } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureService.as b/src/com/dreamsocket/analytics/omniture/OmnitureService.as new file mode 100644 index 0000000..7c94480 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureService.as @@ -0,0 +1,241 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import flash.display.Stage; + import flash.utils.describeType; + import flash.utils.Dictionary; + + import com.dreamsocket.analytics.omniture.OmnitureParams; + import com.dreamsocket.analytics.omniture.OmnitureSingleton; + import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParams; + import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParams; + import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParams; + import com.dreamsocket.analytics.omniture.OmnitureMediaStopParams; + import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParams; + import com.dreamsocket.analytics.omniture.OmnitureTrackParams; + import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParams; + import com.dreamsocket.analytics.omniture.OmnitureTrackType; + + import com.omniture.ActionSource; + + + public class OmnitureService + { + protected var m_config:OmnitureParams; + protected var m_enabled:Boolean; + protected var m_lastTrackParams:OmnitureParams; + protected var m_tracker:ActionSource; + protected var m_functions:Dictionary; + + + public function OmnitureService(p_stage:Stage = null) + { + this.m_tracker = OmnitureSingleton.create(p_stage); + this.m_enabled = true; + + this.m_functions = new Dictionary(); + this.m_functions[OmnitureTrackType.MEDIA_CLOSE] = this.trackMediaClose; + this.m_functions[OmnitureTrackType.MEDIA_OPEN] = this.trackMediaOpen; + this.m_functions[OmnitureTrackType.MEDIA_PLAY] = this.trackMediaPlay; + this.m_functions[OmnitureTrackType.MEDIA_STOP] = this.trackMediaStop; + this.m_functions[OmnitureTrackType.MEDIA_TRACK] = this.trackMedia; + this.m_functions[OmnitureTrackType.TRACK] = this.trackEvent; + this.m_functions[OmnitureTrackType.TRACK_LINK] = this.trackLink; + } + + + public function get config():OmnitureParams + { + return this.m_config; + } + + + public function set config(p_config:OmnitureParams):void + { + if(p_config != this.m_config) + { + this.mergeParams(p_config, this.m_tracker, this.m_config == null ? p_config : this.m_config); + this.mergeParams(p_config.Media, this.m_tracker.Media, this.m_config == null ? p_config.Media : this.m_config.Media); + this.m_config = p_config; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function destroy():void + { + this.m_tracker = null; + this.m_config = null; + this.m_lastTrackParams = null; + } + + + public function track(p_type:String, p_params:Object):void + { + if(!this.m_enabled) return; + + this.setParams(p_params.params); + + try + { + this.m_functions[p_type](p_params); + } + catch(error:Error) + { + trace(error); + } + + this.resetParams(); + } + + + protected function trackEvent(p_params:OmnitureTrackParams):void + { + this.m_tracker.track(); + } + + + protected function trackLink(p_params:OmnitureTrackLinkParams):void + { + this.m_tracker.trackLink(p_params.URL, p_params.type, p_params.name); + } + + + protected function trackMedia(p_params:OmnitureMediaTrackParams):void + { + this.m_tracker.Media.track(p_params.mediaName); + } + + + protected function trackMediaOpen(p_params:OmnitureMediaOpenParams):void + { + this.m_tracker.Media.open(p_params.mediaName, Number(p_params.mediaLength), p_params.mediaPlayerName); + } + + + protected function trackMediaClose(p_params:OmnitureMediaCloseParams):void + { + this.m_tracker.Media.stop(p_params.mediaName, Number(p_params.mediaOffset)); + this.m_tracker.Media.close(p_params.mediaName); + } + + + protected function trackMediaPlay(p_params:OmnitureMediaPlayParams):void + { + this.m_tracker.Media.play(p_params.mediaName, Number(p_params.mediaOffset)); + } + + + protected function trackMediaStop(p_params:OmnitureMediaStopParams):void + { + this.m_tracker.Media.stop(p_params.mediaName, Number(p_params.mediaOffset)); + } + + + protected function mergeParams(p_newValues:Object, p_destination:Object, p_oldValues:Object):void + { + var desc:XML = describeType(p_newValues); + var propNode:XML; + var props:XMLList = desc..variable; + var type:String; + var name:String; + var oldVal:*; + var newVal:*; + + // instance props + for each(propNode in props) + { + name = propNode.@name; + type = propNode.@type; + oldVal = p_oldValues[name]; + newVal = p_newValues[name]; + if(oldVal is String && oldVal != null) + { + p_destination[name] = newVal; + } + else if(oldVal is Number && !isNaN(oldVal)) + { + p_destination[name] = newVal; + } + else if(oldVal is Boolean && oldVal) + { + p_destination[name] = newVal; + } + } + + // dynamic props + for(name in p_oldValues) + { + oldVal = p_oldValues[name]; + newVal = p_newValues[name]; + if(oldVal is String && oldVal != null) + { + p_destination[name] = newVal; + } + else if(oldVal is Number && !isNaN(oldVal)) + { + p_destination[name] = newVal; + } + else if(oldVal is Boolean && oldVal) + { + p_destination[name] = newVal; + } + } + } + + + protected function resetParams():void + { + if(this.m_lastTrackParams == null) return; + + this.mergeParams(this.m_config, this.m_tracker, this.m_lastTrackParams); + this.mergeParams(this.m_config.Media, this.m_tracker.Media, this.m_lastTrackParams.Media); + } + + + protected function setParams(p_params:OmnitureParams):void + { + this.m_lastTrackParams = p_params; + this.mergeParams(p_params, this.m_tracker, p_params); + this.mergeParams(p_params.Media, this.m_tracker.Media, p_params.Media); + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackHandler.as similarity index 92% rename from src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as rename to src/com/dreamsocket/analytics/omniture/OmnitureTrackHandler.as index 8417246..9e3cad2 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackHandler.as @@ -1,41 +1,42 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.omniture +package com.dreamsocket.analytics.omniture { public class OmnitureTrackHandler { public var ID:String; - public var request:Object; + public var params:Object; + public var type:String; public function OmnitureTrackHandler() { } } } diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParams.as similarity index 91% rename from src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as rename to src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParams.as index d5330b8..4e02453 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParams.as @@ -1,43 +1,43 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.omniture +package com.dreamsocket.analytics.omniture { - public class OmnitureTrackLinkRequest + public class OmnitureTrackLinkParams { public var name:String; public var params:OmnitureParams; public var type:String; public var URL:String; - public function OmnitureTrackLinkRequest() + public function OmnitureTrackLinkParams() { this.params = new OmnitureParams(); } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParamsXMLDecoder.as new file mode 100644 index 0000000..a719529 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackLinkParamsXMLDecoder.as @@ -0,0 +1,53 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; + + public class OmnitureTrackLinkParamsXMLDecoder + { + + public function decode(p_XML:XML):OmnitureTrackLinkParams + { + var params:OmnitureTrackLinkParams = new OmnitureTrackLinkParams(); + + if(p_XML.name.toString().length) + params.name = p_XML.name.toString(); + if(p_XML.type.toString().length) + params.type = p_XML.type.toString(); + if(p_XML.URL.toString().length) + params.URL = p_XML.URL.toString(); + + params.params = new OmnitureParamsXMLDecoder().decode(p_XML.params[0]); + + return params; + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackParams.as similarity index 91% rename from src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as rename to src/com/dreamsocket/analytics/omniture/OmnitureTrackParams.as index 465a854..9299be9 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackParams.as @@ -1,40 +1,40 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.omniture +package com.dreamsocket.analytics.omniture { - public class OmnitureTrackRequest + public class OmnitureTrackParams { public var params:OmnitureParams; - public function OmnitureTrackRequest() + public function OmnitureTrackParams() { this.params = new OmnitureParams(); } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTrackParamsXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackParamsXMLDecoder.as new file mode 100644 index 0000000..654fa6f --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackParamsXMLDecoder.as @@ -0,0 +1,46 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import com.dreamsocket.analytics.omniture.OmnitureTrackParams; + import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; + + public class OmnitureTrackParamsXMLDecoder + { + + public function decode(p_XML:XML):OmnitureTrackParams + { + var params:OmnitureTrackParams = new OmnitureTrackParams(); + + params.params = new OmnitureParamsXMLDecoder().decode(p_XML.params[0]); + + return params; + } + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTrackType.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackType.as new file mode 100644 index 0000000..2b528fe --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackType.as @@ -0,0 +1,41 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + public class OmnitureTrackType + { + public static const TRACK:String = "track"; + public static const TRACK_LINK:String = "trackLink"; + public static const MEDIA_TRACK:String = "Media.track"; + public static const MEDIA_OPEN:String = "Media.open"; + public static const MEDIA_CLOSE:String = "Media.close"; + public static const MEDIA_PLAY:String = "Media.play"; + public static const MEDIA_STOP:String = "Media.stop"; + } +} diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as b/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as new file mode 100644 index 0000000..3956941 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTracker.as @@ -0,0 +1,145 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.analytics.omniture +{ + import flash.display.Stage; + import flash.utils.Dictionary; + + import com.dreamsocket.analytics.ITrack; + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.omniture.OmnitureService; + import com.dreamsocket.analytics.omniture.OmnitureTrackerConfig; + import com.dreamsocket.analytics.omniture.OmnitureTrackHandler; + import com.dreamsocket.analytics.omniture.OmnitureTrackType; + import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParamsMapper; + import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParamsMapper; + import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParamsMapper; + import com.dreamsocket.analytics.omniture.OmnitureMediaStopParamsMapper; + import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParamsMapper; + import com.dreamsocket.analytics.omniture.OmnitureTrackParamsMapper; + import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParamsMapper; + + public class OmnitureTracker implements ITracker + { + public static const ID:String = "OmnitureTracker"; + + protected var m_config:OmnitureTrackerConfig; + protected var m_enabled:Boolean; + protected var m_service:OmnitureService; + protected var m_handlers:Dictionary; + protected var m_paramMappers:Dictionary; + + public function OmnitureTracker(p_stage:Stage = null) + { + super(); + + this.m_config = new OmnitureTrackerConfig(); + this.m_enabled = true; + this.m_service = new OmnitureService(p_stage); + + this.m_handlers = new Dictionary(); + + this.m_paramMappers = new Dictionary(); + this.m_paramMappers[OmnitureTrackType.MEDIA_CLOSE] = new OmnitureMediaCloseParamsMapper(); + this.m_paramMappers[OmnitureTrackType.MEDIA_OPEN] = new OmnitureMediaOpenParamsMapper(); + this.m_paramMappers[OmnitureTrackType.MEDIA_PLAY] = new OmnitureMediaPlayParamsMapper(); + this.m_paramMappers[OmnitureTrackType.MEDIA_STOP] = new OmnitureMediaStopParamsMapper(); + this.m_paramMappers[OmnitureTrackType.MEDIA_TRACK] = new OmnitureMediaTrackParamsMapper(); + this.m_paramMappers[OmnitureTrackType.TRACK] = new OmnitureTrackParamsMapper(); + this.m_paramMappers[OmnitureTrackType.TRACK_LINK] = new OmnitureTrackLinkParamsMapper(); + } + + + public function get config():OmnitureTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:OmnitureTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + this.m_service.config = p_value.params; + this.m_enabled = p_value.enabled; + this.m_handlers = p_value.handlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function get ID():String + { + return OmnitureTracker.ID; + } + + + public function addTrackHandler(p_ID:String, p_handler:OmnitureTrackHandler):void + { + this.m_handlers[p_ID] = p_handler; + } + + + public function getTrackHandler(p_ID:String):OmnitureTrackHandler + { + return this.m_handlers[p_ID] as OmnitureTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_handlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled) return; + + var handler:OmnitureTrackHandler = this.m_config.handlers[p_track.type]; + + if(handler != null && handler.params != null && this.m_paramMappers[handler.type] != null) + { // has a track handler + this.m_service.track(handler.type, this.m_paramMappers[handler.type].map(handler.params, p_track.data)); + } + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfig.as similarity index 92% rename from src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as rename to src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfig.as index 27f0e53..b4e144d 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfig.as @@ -1,47 +1,47 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.omniture +package com.dreamsocket.analytics.omniture { import flash.utils.Dictionary; public class OmnitureTrackerConfig { public var enabled:Boolean; public var params:OmnitureParams; - public var trackHandlers:Dictionary; + public var handlers:Dictionary; public function OmnitureTrackerConfig() { this.enabled = true; this.params = new OmnitureParams(); - this.trackHandlers = new Dictionary(); + this.handlers = new Dictionary(); } } } diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfigXMLDecoder.as similarity index 50% rename from src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as rename to src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfigXMLDecoder.as index 6994a52..cccdb4d 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackerConfigXMLDecoder.as @@ -1,103 +1,98 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.omniture +package com.dreamsocket.analytics.omniture { import flash.utils.Dictionary; - import com.dreamsocket.tracking.omniture.OmnitureParamsXMLDecoder; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; - import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; - + import com.dreamsocket.analytics.omniture.OmnitureParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureTrackerConfig; + import com.dreamsocket.analytics.omniture.OmnitureTrackHandler; + import com.dreamsocket.analytics.omniture.OmnitureTrackType; + import com.dreamsocket.analytics.omniture.OmnitureTrackParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureTrackLinkParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaCloseParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaTrackParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaOpenParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaPlayParamsXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureMediaStopParamsXMLDecoder; + public class OmnitureTrackerConfigXMLDecoder { + protected var m_decoders:Dictionary; + public function OmnitureTrackerConfigXMLDecoder() { + this.m_decoders = new Dictionary(); + this.m_decoders[OmnitureTrackType.TRACK] = new OmnitureTrackParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.TRACK_LINK] = new OmnitureTrackLinkParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_TRACK] = new OmnitureMediaTrackParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_CLOSE] = new OmnitureMediaCloseParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_OPEN] = new OmnitureMediaOpenParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_PLAY] = new OmnitureMediaPlayParamsXMLDecoder(); + this.m_decoders[OmnitureTrackType.MEDIA_STOP] = new OmnitureMediaStopParamsXMLDecoder(); } public function decode(p_xml:XML):OmnitureTrackerConfig { var config:OmnitureTrackerConfig = new OmnitureTrackerConfig(); config.enabled = p_xml.enabled.toString() != "false"; config.params = new OmnitureParamsXMLDecoder().decode(p_xml.params[0]); - this.setTrackHandlers(config.trackHandlers, p_xml.trackHandlers.trackHandler); + this.setTrackHandlers(config.handlers, p_xml.handlers.handler); return config; } public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void { var handler:OmnitureTrackHandler; var handlerNode:XML; var ID:String; - var trackLinkRequest:OmnitureTrackLinkRequest; - var trackRequest:OmnitureTrackRequest; - var paramsDecoder:OmnitureParamsXMLDecoder = new OmnitureParamsXMLDecoder(); - var trackNode:XML; for each(handlerNode in p_handlerNodes) { ID = handlerNode.ID.toString(); if(ID.length > 0) { - if(handlerNode.trackLink.toString().length) - { // decode trackLink - handler = new OmnitureTrackHandler(); - handler.ID = ID; - handler.request = trackLinkRequest = new OmnitureTrackLinkRequest(); - trackNode = handlerNode.trackLink[0]; - - if(trackNode.name.toString().length) - trackLinkRequest.name = trackNode.name.toString(); - if(trackNode.type.toString().length) - trackLinkRequest.type = trackNode.type.toString(); - if(trackNode.URL.toString().length) - trackLinkRequest.URL = trackNode.URL.toString(); - - trackLinkRequest.params = paramsDecoder.decode(trackNode.params[0]); - - p_handlers[ID] = handler; + handler = new OmnitureTrackHandler(); + handler.ID = ID; + handler.type = handlerNode.type.toString(); + + if(this.m_decoders[handler.type]) + { + handler.params = this.m_decoders[handler.type].decode(handlerNode.params[0]); + p_handlers[ID] = handler; } - else if(handlerNode.track.toString().length) - { // decode track - handler = new OmnitureTrackHandler(); - handler.ID = ID; - handler.request = trackRequest = new OmnitureTrackRequest(); - trackNode = handlerNode.track[0]; - trackRequest.params = paramsDecoder.decode(trackNode.params[0]); - - p_handlers[ID] = handler; - } } } } } } diff --git a/src/com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as b/src/com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as new file mode 100644 index 0000000..02c0ae3 --- /dev/null +++ b/src/com/dreamsocket/analytics/omniture/OmnitureTrackerModule.as @@ -0,0 +1,54 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package com.dreamsocket.analytics.omniture +{ + import flash.display.Sprite; + + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.ITrackerModule; + import com.dreamsocket.analytics.TrackerModuleParams; + import com.dreamsocket.analytics.omniture.OmnitureTracker; + import com.dreamsocket.analytics.omniture.OmnitureTrackerConfigXMLDecoder; + + public class OmnitureTrackerModule extends Sprite implements ITrackerModule + { + public function OmnitureTrackerModule() + { + } + + + public function getTracker(p_params:TrackerModuleParams):ITracker + { + var tracker:OmnitureTracker = new OmnitureTracker(p_params.stage); + + tracker.config = new OmnitureTrackerConfigXMLDecoder().decode(p_params.config); + + return tracker; + } + } +} diff --git a/src/com/dreamsocket/tracking/url/URLTrackHandler.as b/src/com/dreamsocket/analytics/url/URLTrackHandler.as similarity index 92% rename from src/com/dreamsocket/tracking/url/URLTrackHandler.as rename to src/com/dreamsocket/analytics/url/URLTrackHandler.as index 49d22e3..39f3f7e 100644 --- a/src/com/dreamsocket/tracking/url/URLTrackHandler.as +++ b/src/com/dreamsocket/analytics/url/URLTrackHandler.as @@ -1,43 +1,43 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.url +package com.dreamsocket.analytics.url { public class URLTrackHandler { public var ID:String; - public var URLs:Array; + public var params:Array; public function URLTrackHandler(p_ID:String = null, p_URLs:Array = null) { this.ID = p_ID; - this.URLs = p_URLs == null ? [] : p_URLs; + this.params = p_URLs == null ? [] : p_URLs; } } } diff --git a/src/com/dreamsocket/tracking/url/URLTracker.as b/src/com/dreamsocket/analytics/url/URLTracker.as similarity index 77% rename from src/com/dreamsocket/tracking/url/URLTracker.as rename to src/com/dreamsocket/analytics/url/URLTracker.as index 1786284..7a0b08b 100644 --- a/src/com/dreamsocket/tracking/url/URLTracker.as +++ b/src/com/dreamsocket/analytics/url/URLTracker.as @@ -1,126 +1,132 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.url +package com.dreamsocket.analytics.url { import flash.utils.Dictionary; import com.dreamsocket.utils.PropertyStringUtil; - import com.dreamsocket.tracking.ITrack; - import com.dreamsocket.tracking.ITracker; - import com.dreamsocket.tracking.url.URLTrackerConfig; - import com.dreamsocket.tracking.url.URLTrackHandler; + import com.dreamsocket.analytics.ITrack; + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.url.URLTrackerConfig; + import com.dreamsocket.analytics.url.URLTrackHandler; import com.dreamsocket.utils.HTTPUtil; public class URLTracker implements ITracker { public static const ID:String = "URLTracker"; protected var m_config:URLTrackerConfig; protected var m_enabled:Boolean; - protected var m_trackHandlers:Dictionary; + protected var m_handlers:Dictionary; public function URLTracker() { super(); this.m_config = new URLTrackerConfig(); this.m_enabled = true; - this.m_trackHandlers = new Dictionary(); + this.m_handlers = new Dictionary(); } public function get config():URLTrackerConfig { return this.m_config; } public function set config(p_value:URLTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; this.m_enabled = p_value.enabled; - this.m_trackHandlers = p_value.trackHandlers; + this.m_handlers = p_value.handlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } - public function addTrackHandler(p_ID:String, p_trackHandler:URLTrackHandler):void + public function get ID():String + { + return URLTracker.ID; + } + + + public function addTrackHandler(p_ID:String, p_handler:URLTrackHandler):void { - this.m_trackHandlers[p_ID] = p_trackHandler; + this.m_handlers[p_ID] = p_handler; } public function getTrackHandler(p_ID:String):URLTrackHandler { - return this.m_trackHandlers[p_ID] as URLTrackHandler; + return this.m_handlers[p_ID] as URLTrackHandler; } public function removeTrackHandler(p_ID:String):void { - delete(this.m_trackHandlers[p_ID]); + delete(this.m_handlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled) return; - var handler:URLTrackHandler = this.m_trackHandlers[p_track.type]; + var handler:URLTrackHandler = this.m_handlers[p_track.type]; if(handler != null) { // has the track type - var URLs:Array = handler.URLs; + var URLs:Array = handler.params; var i:uint = URLs.length; while(i--) { HTTPUtil.pingURL(PropertyStringUtil.evalPropertyString(p_track.data, URLs[i])); } } } } } \ No newline at end of file diff --git a/src/com/dreamsocket/tracking/url/URLTrackerConfig.as b/src/com/dreamsocket/analytics/url/URLTrackerConfig.as similarity index 91% rename from src/com/dreamsocket/tracking/url/URLTrackerConfig.as rename to src/com/dreamsocket/analytics/url/URLTrackerConfig.as index 0302dc4..7fe0800 100644 --- a/src/com/dreamsocket/tracking/url/URLTrackerConfig.as +++ b/src/com/dreamsocket/analytics/url/URLTrackerConfig.as @@ -1,45 +1,45 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.url +package com.dreamsocket.analytics.url { import flash.utils.Dictionary; public class URLTrackerConfig { public var enabled:Boolean; - public var trackHandlers:Dictionary; + public var handlers:Dictionary; public function URLTrackerConfig() { this.enabled = true; - this.trackHandlers = new Dictionary(); + this.handlers = new Dictionary(); } } } diff --git a/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as b/src/com/dreamsocket/analytics/url/URLTrackerConfigXMLDecoder.as similarity index 70% rename from src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as rename to src/com/dreamsocket/analytics/url/URLTrackerConfigXMLDecoder.as index 935d705..2b00bec 100644 --- a/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/analytics/url/URLTrackerConfigXMLDecoder.as @@ -1,80 +1,81 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ -package com.dreamsocket.tracking.url +package com.dreamsocket.analytics.url { import flash.utils.Dictionary; - import com.dreamsocket.tracking.url.URLTrackerConfig; - import com.dreamsocket.tracking.url.URLTrackHandler; + import com.dreamsocket.analytics.url.URLTrackerConfig; + import com.dreamsocket.analytics.url.URLTrackHandler; public class URLTrackerConfigXMLDecoder { public function URLTrackerConfigXMLDecoder() { } public function decode(p_xml:XML):URLTrackerConfig { var config:URLTrackerConfig = new URLTrackerConfig(); - var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; - var trackHandlerNode:XML; - var trackHandlers:Dictionary = config.trackHandlers; + var handlerNodes:XMLList = p_xml.handlers.handler; + var handlerNode:XML; + var handlers:Dictionary = config.handlers; - // trackHandlers - for each(trackHandlerNode in trackHandlerNodes) + // handlers + for each(handlerNode in handlerNodes) { - this.addTrack(trackHandlers, trackHandlerNode); + this.addTrack(handlers, handlerNode); } // enabled config.enabled = p_xml.enabled.toString() != "false"; return config; } - protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void + protected function addTrack(p_handlers:Dictionary, p_handlerNode:XML):void { - var ID:String = p_trackHandlerNode.ID.toString(); + var ID:String = p_handlerNode.ID.toString(); var urlNode:XML; var handler:URLTrackHandler; if(ID.length > 0) { handler = new URLTrackHandler(); - for each(urlNode in p_trackHandlerNode.URLs.URL) + for each(urlNode in p_handlerNode.params.URL) { - handler.URLs.push(urlNode.toString()); + handler.params.push(urlNode.toString()); } - p_trackHandlers[ID] = handler; + handler.ID = ID; + p_handlers[ID] = handler; } } } } diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureService.as b/src/com/dreamsocket/tracking/omniture/OmnitureService.as deleted file mode 100644 index 1191668..0000000 --- a/src/com/dreamsocket/tracking/omniture/OmnitureService.as +++ /dev/null @@ -1,257 +0,0 @@ -/** -* Dreamsocket, Inc. -* http://dreamsocket.com -* Copyright 2010 Dreamsocket, Inc. -* -* 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. -**/ - - -package com.dreamsocket.tracking.omniture -{ - import flash.display.DisplayObjectContainer; - import flash.utils.describeType; - - import com.dreamsocket.tracking.omniture.OmnitureParams; - - import com.omniture.ActionSource; - - - public class OmnitureService - { - public static var display:DisplayObjectContainer; - - protected var m_config:OmnitureParams; - protected var m_display:DisplayObjectContainer; - protected var m_enabled:Boolean; - protected var m_lastTrackParams:OmnitureParams; - protected var m_tracker:ActionSource; - - - public function OmnitureService(p_display:DisplayObjectContainer = null) - { - this.m_display = p_display; - this.m_enabled = true; - } - - - public function get config():OmnitureParams - { - return this.m_config; - } - - - public function set config(p_config:OmnitureParams):void - { - if(p_config != this.m_config) - { - this.m_config = p_config; - this.reset(); - this.mergeParams(p_config, this.m_tracker); - } - } - - - public function get enabled():Boolean - { - return this.m_enabled; - } - - - public function set enabled(p_enabled:Boolean):void - { - this.m_enabled = p_enabled; - } - - - public function destroy():void - { - if(this.m_tracker != null && this.m_display != null && this.m_display.contains(this.m_tracker)) - { - this.m_display.removeChild(this.m_tracker); - } - this.m_tracker = null; - this.m_config = null; - this.m_display = null; - this.m_lastTrackParams = null; - OmnitureService.display = null; - } - - - public function track(p_params:OmnitureParams):void - { - if(!this.m_enabled) return; - - this.resetTrackParams(); - this.m_lastTrackParams = p_params; - this.mergeParams(p_params, this.m_tracker); - - try - { - this.m_tracker.track(); - } - catch(error:Error) - { - trace(error); - } - } - - - public function trackLink(p_params:OmnitureParams, p_URL:String, p_type:String, p_name:String):void - { - if(!this.m_enabled) return; - - this.resetTrackParams(); - this.m_lastTrackParams = p_params; - this.mergeParams(p_params, this.m_tracker); - - try - { - this.m_tracker.trackLink(p_URL, p_type, p_name); - } - catch(error:Error) - { - trace(error); - } - } - - - protected function mergeParams(p_params:OmnitureParams, p_destination:Object):void - { - var desc:XML = describeType(p_params); - var propNode:XML; - var props:XMLList = desc..variable; - var type:String; - var name:String; - var val:*; - - // instance props - for each(propNode in props) - { - name = propNode.@name; - type = propNode.@type; - val = p_params[name]; - if(val is String && val != null) - { - p_destination[name] = val; - } - else if(val is Number && !isNaN(val)) - { - p_destination[name] = val; - } - else if(val is Boolean && val) - { - p_destination[name] = val; - } - } - - // dynamic props - for(name in p_params) - { - val = p_params[name]; - if(val is String && val != null) - { - p_destination[name] = val; - } - else if(val is Number && !isNaN(val)) - { - p_destination[name] = val; - } - else if(val is Boolean && val) - { - p_destination[name] = val; - } - } - } - - - protected function reset():void - { - if(this.m_config == null) return; - - this.m_display = this.m_display == null ? OmnitureService.display : this.m_display; - - if(this.m_tracker != null && this.m_display != null && this.m_display.contains(this.m_tracker)) - { - this.m_display.removeChild(this.m_tracker); - } - this.m_tracker = new ActionSource(); - if(this.m_tracker != null && this.m_display != null) - { - this.m_display.addChild(this.m_tracker); - } - } - - - protected function resetTrackParams():void - { - if(this.m_lastTrackParams == null) return; - - var params:OmnitureParams = this.m_config; - var desc:XML = describeType(this.m_lastTrackParams); - var propNode:XML; - var props:XMLList = desc..variable; - var type:String; - var name:String; - var val:*; - - // instance props - for each(propNode in props) - { - name = propNode.@name; - type = propNode.@type; - - val = this.m_lastTrackParams[name]; - if(val is String && val != null) - { - this.m_tracker[name] = params[name]; - } - else if(val is Number && !isNaN(val)) - { - this.m_tracker[name] = params[name]; - } - else if(val is Boolean && val) - { - this.m_tracker[name] = params[name]; - } - } - - // dynamic props - for(name in this.m_lastTrackParams) - { - val = this.m_lastTrackParams[name]; - if(val is String && val != null) - { - this.m_tracker[name] = params[name]; - } - else if(val is Number && !isNaN(val)) - { - this.m_tracker[name] = params[name]; - } - else if(val is Boolean && val) - { - this.m_tracker[name] = params[name]; - } - } - } - } -} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as b/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as deleted file mode 100644 index 5d55cc4..0000000 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as +++ /dev/null @@ -1,170 +0,0 @@ -/** -* Dreamsocket, Inc. -* http://dreamsocket.com -* Copyright 2010 Dreamsocket, Inc. -* -* 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. -**/ - - -package com.dreamsocket.tracking.omniture -{ - import flash.display.DisplayObjectContainer; - import flash.utils.describeType; - import flash.utils.Dictionary; - - import com.dreamsocket.utils.PropertyStringUtil; - import com.dreamsocket.tracking.ITrack; - import com.dreamsocket.tracking.ITracker; - import com.dreamsocket.tracking.omniture.OmnitureService; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; - import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; - import com.dreamsocket.tracking.omniture.OmnitureTrackRequest; - import com.dreamsocket.tracking.omniture.OmnitureTrackLinkRequest; - - - public class OmnitureTracker implements ITracker - { - public static var display:DisplayObjectContainer; - public static const ID:String = "OmnitureTracker"; - - protected var m_config:OmnitureTrackerConfig; - protected var m_enabled:Boolean; - protected var m_service:OmnitureService; - protected var m_trackHandlers:Dictionary; - - public function OmnitureTracker(p_display:DisplayObjectContainer = null) - { - super(); - - this.m_config = new OmnitureTrackerConfig(); - this.m_enabled = true; - this.m_service = new OmnitureService(p_display == null ? OmnitureTracker.display : p_display); - this.m_trackHandlers = new Dictionary(); - } - - - public function get config():OmnitureTrackerConfig - { - return this.m_config; - } - - - public function set config(p_value:OmnitureTrackerConfig):void - { - if(p_value != this.m_config) - { - this.m_config = p_value; - this.m_service.config = p_value.params; - this.m_enabled = p_value.enabled; - this.m_trackHandlers = p_value.trackHandlers; - } - } - - - public function get enabled():Boolean - { - return this.m_enabled; - } - - - public function set enabled(p_enabled:Boolean):void - { - this.m_enabled = p_enabled; - } - - - public function addTrackHandler(p_ID:String, p_trackHandler:OmnitureTrackHandler):void - { - this.m_trackHandlers[p_ID] = p_trackHandler; - } - - - public function getTrackHandler(p_ID:String):OmnitureTrackHandler - { - return this.m_trackHandlers[p_ID] as OmnitureTrackHandler; - } - - - public function removeTrackHandler(p_ID:String):void - { - delete(this.m_trackHandlers[p_ID]); - } - - - public function track(p_track:ITrack):void - { - if(!this.m_enabled) return; - - var handler:OmnitureTrackHandler = this.m_config.trackHandlers[p_track.type]; - - - if(handler != null && handler.request != null) - { // has a track handler - var requestParams:OmnitureParams = new OmnitureParams(); - var handlerParams:OmnitureParams; - - if(handler.request.params != null && handler.request.params is OmnitureParams) - { - handlerParams = handler.request.params; - - var desc:XML = describeType(handlerParams); - var propNode:XML; - var props:XMLList = desc..variable; - var prop:String; - var val:*; - - // instance props - for each(propNode in props) - { - prop = propNode.@name; - val = handlerParams[prop]; - if(val is String && val != null) - { - requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, val); - } - } - // dynamic prop - for(prop in handlerParams) - { - requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, handlerParams[prop]); - } - } - - - // call correct track method - if(handler.request is OmnitureTrackLinkRequest) - { - var URL:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.URL); - var type:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.type); - var name:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.name); - - this.m_service.trackLink(requestParams, URL, type, name); - } - else if(handler.request is OmnitureTrackRequest) - { - this.m_service.track(requestParams); - } - } - } - } -} diff --git a/src/com/dreamsocket/utils/HTTPUtil.as b/src/com/dreamsocket/utils/HTTPUtil.as index b35f4fa..d14408f 100644 --- a/src/com/dreamsocket/utils/HTTPUtil.as +++ b/src/com/dreamsocket/utils/HTTPUtil.as @@ -1,120 +1,126 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.utils { import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; import flash.system.Security; import flash.utils.Dictionary; public class HTTPUtil { public static var allowLocalQueryStrings:Boolean = false; protected static var k_pings:Dictionary = new Dictionary(); public function HTTPUtil() { } public static function pingURL(p_URL:String, p_clearCache:Boolean = true, p_rateInSecsToCache:Number = 0):void { if(p_URL == null) return; var loader:URLLoader = new URLLoader(); var URL:String = p_URL; if(p_clearCache && (HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE)) { URL = HTTPUtil.resolveUniqueURL(p_URL, p_rateInSecsToCache); } loader.load(new URLRequest(URL)); loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); HTTPUtil.k_pings[loader] = true; } public static function addQueryParam(p_URL:String, p_name:String, p_val:String, p_delimeter:String = null):String { if(HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) { if(p_delimeter == null) p_URL += (p_URL.indexOf( "?" ) != -1 ) ? "&" + p_name + "=" : "?" + p_name + "="; else p_URL += p_delimeter + p_name + "="; p_URL += p_val != null ? escape(p_val) : ""; } return p_URL; } public static function resolveUniqueURL(p_URL:String, p_rateInSecsToCache:Number = 0):String { var request:String = p_URL; if((HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) && p_URL.indexOf( "&cacheID=" ) == -1 && p_URL.indexOf( "?cacheID=" ) == -1) { - var d:Date = new Date(); - var ID:String; - var secsPassed:Number = (60 * d.getUTCMinutes()) + d.getUTCSeconds(); - - if(p_rateInSecsToCache == 0) - { - ID = String(d.valueOf()); - } - else - { - ID = d.getUTCFullYear() + "" + d.getUTCMonth() + "" +d.getUTCDate() + "" +d.getUTCHours() + "-" + Math.floor(secsPassed/p_rateInSecsToCache); - } - - request = HTTPUtil.addQueryParam(p_URL, "cacheID", ID); + request = HTTPUtil.addQueryParam(p_URL, "cacheID", HTTPUtil.getUniqueCacheID(p_rateInSecsToCache)); } return request; } + + public static function getUniqueCacheID(p_rateInSecsToCache:Number = 0):String + { + var d:Date = new Date(); + var ID:String; + var secsPassed:Number = (60 * d.getUTCMinutes()) + d.getUTCSeconds(); + + if(p_rateInSecsToCache == 0) + { + ID = String(d.valueOf()); + } + else + { + ID = d.getUTCFullYear() + "" + d.getUTCMonth() + "" +d.getUTCDate() + "" +d.getUTCHours() + "-" + Math.floor(secsPassed/p_rateInSecsToCache); + } + + return ID; + } + protected static function onPingResult(p_event:Event):void { // NOTE: let errors be thrown or log them if you want to handle them URLLoader(p_event.target).removeEventListener(Event.COMPLETE, HTTPUtil.onPingResult); URLLoader(p_event.target).removeEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); URLLoader(p_event.target).removeEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); delete(HTTPUtil.k_pings[p_event.target]); } } } diff --git a/test/TestGoogleTracker.as b/test/TestGoogleTracker.as index 66e4282..caab7fb 100644 --- a/test/TestGoogleTracker.as +++ b/test/TestGoogleTracker.as @@ -1,76 +1,76 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package { - import com.dreamsocket.tracking.Track; - import com.dreamsocket.tracking.google.GoogleTrackerConfig; - import com.dreamsocket.tracking.google.GoogleTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.google.GoogleTracker; + import com.dreamsocket.analytics.Track; + import com.dreamsocket.analytics.google.GoogleTrackerConfig; + import com.dreamsocket.analytics.google.GoogleTrackerConfigXMLDecoder; + import com.dreamsocket.analytics.google.GoogleTracker; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TestGoogleTracker extends Sprite { private var m_loader:URLLoader; private var m_tracker:GoogleTracker; public function TestGoogleTracker() { this.m_loader = new URLLoader(); this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); this.m_loader.load(new URLRequest("test_tracking_google.xml")); } private function onErrorOccurred(p_event:Event):void { trace(p_event); } private function onXMLLoaded(p_event:Event):void { var config:GoogleTrackerConfig = new GoogleTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); - this.m_tracker = new GoogleTracker(this); + this.m_tracker = new GoogleTracker(this.stage); this.m_tracker.config = config; this.m_tracker.track(new Track("track1", "test string")); this.m_tracker.track(new Track("track2", {id:"testid"})); this.m_tracker.track(new Track("track3", "test string")); } } } diff --git a/test/TestJSTracker.as b/test/TestJSTracker.as index b511aae..5df3b73 100644 --- a/test/TestJSTracker.as +++ b/test/TestJSTracker.as @@ -1,93 +1,88 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package { - import flash.utils.Dictionary; - - import com.dreamsocket.tracking.Track; - import com.dreamsocket.tracking.js.JSTrackerConfig; - import com.dreamsocket.tracking.js.JSMethodCall; - import com.dreamsocket.tracking.js.JSTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.js.JSTracker; - import com.dreamsocket.tracking.js.JSTrackHandler; + import com.dreamsocket.analytics.Track; + import com.dreamsocket.analytics.js.JSTrackerConfigXMLDecoder; + import com.dreamsocket.analytics.js.JSTracker; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TestJSTracker extends Sprite { private var m_loader:URLLoader; private var m_tracker:JSTracker; public function TestJSTracker() { this.m_loader = new URLLoader(); this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); this.m_loader.load(new URLRequest("test_tracking_javascript.xml")); //var config:JSTrackerConfig = new JSTrackerConfig(); - //var trackHandler:JSTrackHandler; + //var handler:JSTrackHandler; //this.m_tracker = new JSTracker(); //this.m_tracker.config = config; - //trackHandler = new JSTrackHandler(); - //trackHandler.ID = "track3"; - //trackHandler.methodCalls = [new JSMethodCall("doJS", [1, 2, "3...${data.id}"])]; + //handler = new JSTrackHandler(); + //handler.ID = "track3"; + //handler.params = new JSMethodCall("doJS", [1, 2, "3...${data.id}"]); - //config.trackHandlers["track1"] = trackHandler; - //config.trackHandlers["track2"] = trackHandler; + //config.handlers["track1"] = handler; + //config.handlers["track2"] = handler; //this.m_tracker.track(new Track("track1", "test string1")); //this.m_tracker.track(new Track("track2", {id:"testid"})); //this.m_tracker.track(new Track("track3", "test string3")); } private function onErrorOccurred(p_event:Event):void { trace(p_event); } private function onXMLLoaded(p_event:Event):void { this.m_tracker = new JSTracker(); this.m_tracker.config = new JSTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); this.m_tracker.track(new Track("track1", "test string1")); this.m_tracker.track(new Track("track2", {id:"testid"})); this.m_tracker.track(new Track("track3", "test string3")); } } } diff --git a/test/TestOmnitureMediaTracking.fla b/test/TestOmnitureMediaTracking.fla new file mode 100644 index 0000000..edfcce3 Binary files /dev/null and b/test/TestOmnitureMediaTracking.fla differ diff --git a/test/TestOmnitureTracker.as b/test/TestOmnitureTracker.as index 1eb6991..e93681d 100644 --- a/test/TestOmnitureTracker.as +++ b/test/TestOmnitureTracker.as @@ -1,75 +1,75 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package { - import com.dreamsocket.tracking.Track; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.omniture.OmnitureTracker; + import com.dreamsocket.analytics.Track; + import com.dreamsocket.analytics.omniture.OmnitureTrackerConfig; + import com.dreamsocket.analytics.omniture.OmnitureTrackerConfigXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureTracker; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TestOmnitureTracker extends Sprite { private var m_loader:URLLoader; private var m_tracker:OmnitureTracker; public function TestOmnitureTracker() { this.m_loader = new URLLoader(); this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); this.m_loader.load(new URLRequest("test_tracking_omniture.xml")); } private function onErrorOccurred(p_event:Event):void { trace(p_event); } private function onXMLLoaded(p_event:Event):void { var config:OmnitureTrackerConfig = new OmnitureTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); this.m_tracker = new OmnitureTracker(); this.m_tracker.config = config; this.m_tracker.track(new Track("track1", "test string")); this.m_tracker.track(new Track("track2", {id:"testid"})); this.m_tracker.track(new Track("track3", "test string")); } } } diff --git a/test/TestTrackerModule.as b/test/TestTrackerModule.as new file mode 100644 index 0000000..ff36a1b --- /dev/null +++ b/test/TestTrackerModule.as @@ -0,0 +1,114 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package +{ + import com.dreamsocket.analytics.ITracker; + import com.dreamsocket.analytics.Track; + import com.dreamsocket.analytics.TrackerManager; + import com.dreamsocket.analytics.TrackerModuleParams; + import com.dreamsocket.analytics.ITrackerModule; + + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestTrackerModule extends Sprite + { + private var m_configURL:String; + private var m_configLoader:URLLoader; + private var m_moduleURL:String; + private var m_moduleLoader:Loader; + + public function TestTrackerModule() + { + this.m_configURL = "test_tracking_javascript.xml"; + this.m_moduleURL = "../bin/daf_javascript.swf"; + + this.loadConfig(); + } + + + private function loadConfig():void + { + this.m_configLoader = new URLLoader(); + this.m_configLoader.addEventListener(Event.COMPLETE, this.onConfigLoaded); + this.m_configLoader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_configLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_configLoader.load(new URLRequest(this.m_configURL)); + } + + + private function loadModule():void + { + this.m_moduleLoader = new Loader(); + this.m_moduleLoader.contentLoaderInfo.addEventListener(Event.INIT, this.onModuleLoaded); + this.m_moduleLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_moduleLoader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_moduleLoader.load(new URLRequest(this.m_moduleURL)); + } + + + private function runTest():void + { + var params:TrackerModuleParams = new TrackerModuleParams(); + + params.stage = this.stage; + params.config = new XML(this.m_configLoader.data); + + var module:ITracker = ITrackerModule(this.m_moduleLoader.content).getTracker(params); + + TrackerManager.addTracker("test", module); + + TrackerManager.track(new Track("track1", "test string")); + TrackerManager.track(new Track("track2", {id:"testid"})); + TrackerManager.track(new Track("track3", "test string")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onConfigLoaded(p_event:Event):void + { + this.loadModule(); + } + + + private function onModuleLoaded(p_event:Event):void + { + this.runTest(); + } + } +} diff --git a/test/TestTrackerModuleLoader.as b/test/TestTrackerModuleLoader.as new file mode 100644 index 0000000..85f373f --- /dev/null +++ b/test/TestTrackerModuleLoader.as @@ -0,0 +1 @@ +/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package { import com.dreamsocket.analytics.Track; import com.dreamsocket.analytics.TrackerManager; import com.dreamsocket.analytics.TrackerModuleLoader; import com.dreamsocket.analytics.TrackerModuleLoaderEvent; import com.dreamsocket.analytics.TrackerModuleLoaderParams; import com.dreamsocket.analytics.url.URLTrackerModule; import flash.display.Sprite; public class TestTrackerModuleLoader extends Sprite { private var m_loader:TrackerModuleLoader; public function TestTrackerModuleLoader() { var params:TrackerModuleLoaderParams = new TrackerModuleLoaderParams(); var data:XML = new XML("<URL><enabled>true</enabled><handlers><handler><ID>track1</ID><params><URL>http://foo.com/track1.gif</URL></params></handler><handler><ID>track2</ID><params><URL>http://foo.com/track2.gif?id=${data.id}</URL></params></handler><handler><ID>track3</ID><params><URL>http://foo.com/track3.gif?id=${data}</URL></params></handler></handlers></URL>"); params.config = "test_tracking_url.xml";//data; params.resource = "../bin/daf_url.swf";//new URLTrackerModule(); params.stage = this.stage; this.m_loader = new TrackerModuleLoader(); this.m_loader.addEventListener(TrackerModuleLoaderEvent.MODULE_FAILED, this.onModuleFailed); this.m_loader.addEventListener(TrackerModuleLoaderEvent.MODULE_LOADED, this.onModuleLoaded); this.m_loader.load(params); } private function onModuleLoaded(p_event:TrackerModuleLoaderEvent):void { TrackerManager.addTracker("test", p_event.tracker); TrackerManager.track(new Track("track1", "test string")); TrackerManager.track(new Track("track2", {id:"testid"})); TrackerManager.track(new Track("track3", "test string")); } private function onModuleFailed(p_event:TrackerModuleLoaderEvent):void { trace(p_event); } } } \ No newline at end of file diff --git a/test/TestTrackerModuleManifestLoader.as b/test/TestTrackerModuleManifestLoader.as new file mode 100644 index 0000000..b0cbf2c --- /dev/null +++ b/test/TestTrackerModuleManifestLoader.as @@ -0,0 +1 @@ +/** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package { import flash.display.Sprite; import flash.events.Event; import com.dreamsocket.analytics.Track; import com.dreamsocket.analytics.TrackerManager; import com.dreamsocket.analytics.TrackerModuleManifestLoader; //import com.dreamsocket.analytics.url.URLTrackerModule; public class TestTrackerModuleManifestLoader extends Sprite { private var m_loader:TrackerModuleManifestLoader; public function TestTrackerModuleManifestLoader() { this.m_loader = new TrackerModuleManifestLoader(); this.m_loader.addEventListener(Event.COMPLETE, this.onModuleLoaded); this.m_loader.stage = this.stage; //this.m_loader.addModuleDefinition("com.dreamsocket.analytics.url.URLTrackerModule", new URLTrackerModule()); this.m_loader.load("test_tracking_modules.xml"); } private function onModuleLoaded(p_event:Event):void { TrackerManager.track(new Track("track1", "test string")); TrackerManager.track(new Track("track2", {id:"testid"})); TrackerManager.track(new Track("track3", "test string")); } } } \ No newline at end of file diff --git a/test/TestTrackingManager.as b/test/TestTrackingManager.as index 2c70f25..1432f9e 100644 --- a/test/TestTrackingManager.as +++ b/test/TestTrackingManager.as @@ -1,90 +1,87 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package { - import com.dreamsocket.tracking.Track; - import com.dreamsocket.tracking.google.GoogleTracker; - import com.dreamsocket.tracking.google.GoogleTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.omniture.OmnitureTracker; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.url.URLTracker; - import com.dreamsocket.tracking.url.URLTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.TrackingManager; + import com.dreamsocket.analytics.Track; + import com.dreamsocket.analytics.google.GoogleTracker; + import com.dreamsocket.analytics.google.GoogleTrackerConfigXMLDecoder; + import com.dreamsocket.analytics.omniture.OmnitureTracker; + import com.dreamsocket.analytics.omniture.OmnitureTrackerConfigXMLDecoder; + import com.dreamsocket.analytics.url.URLTracker; + import com.dreamsocket.analytics.url.URLTrackerConfigXMLDecoder; + import com.dreamsocket.analytics.TrackerManager; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TestTrackingManager extends Sprite { private var m_loader:URLLoader; public function TestTrackingManager() { this.m_loader = new URLLoader(); this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); this.m_loader.load(new URLRequest("test_tracking_multiple.xml")); } private function onErrorOccurred(p_event:Event):void { trace(p_event); } private function onXMLLoaded(p_event:Event):void { var data:XML = new XML(this.m_loader.data); - GoogleTracker.display = this; - OmnitureTracker.display = this; - // create all trackers - TrackingManager.addTracker(GoogleTracker.ID, new GoogleTracker()); - TrackingManager.addTracker(OmnitureTracker.ID, new OmnitureTracker()); - TrackingManager.addTracker(URLTracker.ID, new URLTracker()); + TrackerManager.addTracker(GoogleTracker.ID, new GoogleTracker(this.stage)); + TrackerManager.addTracker(OmnitureTracker.ID, new OmnitureTracker(this.stage)); + TrackerManager.addTracker(URLTracker.ID, new URLTracker()); // configure all trackers - OmnitureTracker(TrackingManager.getTracker(OmnitureTracker.ID)).config = new OmnitureTrackerConfigXMLDecoder().decode(data.omniture[0]); - GoogleTracker(TrackingManager.getTracker(GoogleTracker.ID)).config = new GoogleTrackerConfigXMLDecoder().decode(data.google[0]); - URLTracker(TrackingManager.getTracker(URLTracker.ID)).config = new URLTrackerConfigXMLDecoder().decode(data.URL[0]); + OmnitureTracker(TrackerManager.getTracker(OmnitureTracker.ID)).config = new OmnitureTrackerConfigXMLDecoder().decode(data.omniture[0]); + GoogleTracker(TrackerManager.getTracker(GoogleTracker.ID)).config = new GoogleTrackerConfigXMLDecoder().decode(data.google[0]); + URLTracker(TrackerManager.getTracker(URLTracker.ID)).config = new URLTrackerConfigXMLDecoder().decode(data.URL[0]); // perform tracks - TrackingManager.track(new Track("track1", "test string")); - TrackingManager.track(new Track("track2", {id:"testid"})); - TrackingManager.track(new Track("track3", "test string")); + TrackerManager.track(new Track("track1", "test string")); + TrackerManager.track(new Track("track2", {id:"testid"})); + TrackerManager.track(new Track("track3", "test string")); } } } diff --git a/test/TestURLTracker.as b/test/TestURLTracker.as new file mode 100644 index 0000000..592260c --- /dev/null +++ b/test/TestURLTracker.as @@ -0,0 +1,75 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package +{ + import com.dreamsocket.analytics.Track; + import com.dreamsocket.analytics.url.URLTrackerConfig; + import com.dreamsocket.analytics.url.URLTrackerConfigXMLDecoder; + import com.dreamsocket.analytics.url.URLTracker; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestURLTracker extends Sprite + { + private var m_loader:URLLoader; + private var m_tracker:URLTracker; + + public function TestURLTracker() + { + this.m_loader = new URLLoader(); + this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_loader.load(new URLRequest("test_tracking_url.xml")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onXMLLoaded(p_event:Event):void + { + var config:URLTrackerConfig = new URLTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); + + this.m_tracker = new URLTracker(); + this.m_tracker.config = config; + + this.m_tracker.track(new Track("track1", "test string")); + this.m_tracker.track(new Track("track2", {id:"testid"})); + this.m_tracker.track(new Track("track3", "test string")); + } + } +} diff --git a/test/test_omniture_media.xml b/test/test_omniture_media.xml new file mode 100644 index 0000000..4a32e13 --- /dev/null +++ b/test/test_omniture_media.xml @@ -0,0 +1,99 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- tracking: OMNITURE --> +<omniture> +<!-- enabled: specifies whether Omniture tracking will be sent --> + <enabled>true</enabled> + <!-- params: + allows you to generically assign values to all omniture values + NOTE: params set will be sent for every track + This can be use to set special props like <eVar23>pga_mosaic_player_09</eVar23> + --> + <params> + <account>foodotcom</account> + <dc>122</dc> + <delayTracking>2</delayTracking> + <trackingServer>stats.foo.com</trackingServer> + <visitorNameSpace>foo</visitorNameSpace> + <trackLocal>true</trackLocal> + + <eVar1>test evar1</eVar1> + <eVar25>test evar25</eVar25> + <Media> + <playerName>livePlayer</playerName> + <trackEvents>event2</trackEvents> + <!--<trackMilestones>20,40,60,80</trackMilestones>--> + <trackSeconds>5</trackSeconds> + <!--<trackVars></trackVars>--> + <trackWhilePlaying>true</trackWhilePlaying> + </Media> + </params> + <handlers> + <handler> + <ID>mediaRequested</ID> + <type>Media.open</type> + <params> + <mediaName>${data.title}</mediaName> + <mediaLength>${data.duration}</mediaLength> + <mediaPlayerName>livePlayer</mediaPlayerName> + <params> + <Media> + <trackEvents>event2</trackEvents> + <trackVars>eVar1,eVar25</trackVars> + </Media> + </params> + </params> + </handler> + + <handler> + <ID>mediaClosed</ID> + <type>Media.close</type> + <params> + <mediaName>${data.title}</mediaName> + <mediaOffset>${data.position}</mediaOffset> + </params> + </handler> + + <handler> + <ID>mediaStarted</ID> + <type>Media.play</type> + <params> + <mediaName>${data.title}</mediaName> + <mediaOffset>${data.position}</mediaOffset> + </params> + </handler> + + <handler> + <ID>mediaPlaying</ID> + <type>Media.play</type> + <params> + <mediaName>${data.title}</mediaName> + <mediaOffset>${data.position}</mediaOffset> + </params> + </handler> + + + <handler> + <ID>mediaPaused</ID> + <type>Media.stop</type> + <params> + <mediaName>${data.title}</mediaName> + <mediaOffset>${data.position}</mediaOffset> + </params> + </handler> + + + <handler> + <ID>mediaPaused</ID> + <type>Media.track</type> + <params> + <mediaName>${data.title}</mediaName> + <params> + <Media> + <trackVars>eVar7</trackVars> + </Media> + <eVar7>evar7- Leaderboard Link</eVar7> + </params> + </params> + </handler> + </handlers> +</omniture> \ No newline at end of file diff --git a/test/test_tracking_google.xml b/test/test_tracking_google.xml index 519e87b..e2c4233 100644 --- a/test/test_tracking_google.xml +++ b/test/test_tracking_google.xml @@ -1,39 +1,42 @@ <?xml version="1.0" encoding="utf-8"?> <!-- tracking: GOOGLE --> <google> <!-- enabled: specifies whether GOOGLE tracking will be sent --> <enabled>true</enabled> <account>UA-5555555-5</account> <visualDebug>false</visualDebug> <trackingMode>AS3</trackingMode> - <trackHandlers> - <trackHandler> + <handlers> + <handler> <ID>track1</ID> - <trackPageView> + <type>trackPageView</type> + <params> <URL>${data} Scorecard Nav</URL> - </trackPageView> - </trackHandler> + </params> + </handler> - <trackHandler> + <handler> <ID>track2</ID> - <trackEvent> + <type>trackEvent</type> + <params> <category>LiveAt_videoevent1</category> <action>o1</action> <label>Mosiac Live Stream1</label> <value>1</value> - </trackEvent> - </trackHandler> + </params> + </handler> - <trackHandler> + <handler> <ID>track3</ID> - <trackEvent> + <type>trackEvent</type> + <params> <category>LiveAt_videoevent2</category> <action>o2</action> - </trackEvent> - </trackHandler> + </params> + </handler> - </trackHandlers> + </handlers> </google> \ No newline at end of file diff --git a/test/test_tracking_javascript.xml b/test/test_tracking_javascript.xml index 6a8185a..a266a6a 100644 --- a/test/test_tracking_javascript.xml +++ b/test/test_tracking_javascript.xml @@ -1,25 +1,23 @@ <?xml version="1.0" encoding="utf-8"?> <!-- url TRACKING defines a tracker that can ping URLs for a specific track request --> <JavaScript> <!-- enabled: specifies whether url tracking will be sent --> <enabled>true</enabled> - <trackHandlers> - <trackHandler> + <handlers> + <handler> <ID>track1</ID> - <methodCalls> - <methodCall> - <method>doJS</method> - <arguments> - <argument>${data} a</argument> - <argument>b</argument> - <argument>c</argument> - </arguments> - </methodCall> - </methodCalls> - </trackHandler> + <params> + <method>doJS</method> + <arguments> + <argument>${data} a</argument> + <argument>b</argument> + <argument>c</argument> + </arguments> + </params> + </handler> - </trackHandlers> + </handlers> </JavaScript> \ No newline at end of file diff --git a/test/test_tracking_modules.xml b/test/test_tracking_modules.xml new file mode 100644 index 0000000..a8a979d --- /dev/null +++ b/test/test_tracking_modules.xml @@ -0,0 +1,108 @@ +<?xml version="1.0" encoding="utf-8"?> + <modules> + <!-- + <module> + <resource>com.dreamsocket.analytics.url.URLTrackerModule</resource> + <config>test_tracking_url.xml</config> + </module> + --> + <module> + <resource>../bin/daf_google.swf</resource> + <config> + <enabled>true</enabled> + + <account>UA-5555555-5</account> + <visualDebug>false</visualDebug> + <trackingMode>AS3</trackingMode> + + <handlers> + <handler> + <ID>track1</ID> + <type>trackPageView</type> + <params> + <URL>${data} Scorecard Nav</URL> + </params> + </handler> + + <handler> + <ID>track2</ID> + <type>trackEvent</type> + <params> + <category>LiveAt_videoevent1</category> + <action>o1</action> + <label>Mosiac Live Stream1</label> + <value>1</value> + </params> + </handler> + + <handler> + <ID>track3</ID> + <type>trackEvent</type> + <params> + <category>LiveAt_videoevent2</category> + <action>o2</action> + </params> + </handler> + + + </handlers> + </config> + </module> + + <module> + <resource>../bin/daf_omniture.swf</resource> + <config> + <enabled>true</enabled> + <params> + <account>foodotcom</account> + <dc>122</dc> + <delayTracking>2</delayTracking> + <trackingServer>stats.foo.com</trackingServer> + <visitorNameSpace>foo</visitorNameSpace> + <trackLocal>true</trackLocal> + </params> + <handlers> + <handler> + <ID>track1</ID> + <type>trackLink</type> + <params> + <URL>LiveAt_videoevent</URL> + <type>o</type> + <name>Mosiac Live Stream</name> + <params> + <prop7>${data} Leaderboard Link</prop7> + <eVar7>${data} Leaderboard Link</eVar7> + </params> + </params> + </handler> + + <handler> + <ID>track2</ID> + <type>trackLink</type> + <params> + <URL>LiveAt_videoevent</URL> + <type>o</type> + <name>Mosiac Live Stream</name> + <params> + <prop6>${data.id} Scorecard Search</prop6> + <eVar7>${data.id} Scorecard Search</eVar7> + <events>event14</events> + <eVar8>foo</eVar8> + </params> + </params> + </handler> + + <handler> + <ID>track3</ID> + <type>track</type> + <params> + <params> + <eVar8>foo</eVar8> + <events>event17</events> + </params> + </params> + </handler> + </handlers> + </config> + </module> + </modules> \ No newline at end of file diff --git a/test/test_tracking_multiple.xml b/test/test_tracking_multiple.xml index a367289..8aaf873 100644 --- a/test/test_tracking_multiple.xml +++ b/test/test_tracking_multiple.xml @@ -1,140 +1,140 @@ <?xml version="1.0" encoding="utf-8"?> <tracking> <!-- tracking: OMNITURE --> <omniture> <!-- enabled: specifies whether Omniture tracking will be sent --> <enabled>true</enabled> <!-- params: allows you to generically assign values to all omniture values NOTE: params set will be sent for every track This can be use to set special props like <eVar23>pga_mosaic_player_09</eVar23> --> <params> <account>foodotcom</account> <dc>122</dc> <delayTracking>2</delayTracking> <trackingServer>stats.foo.com</trackingServer> <visitorNameSpace>foo</visitorNameSpace> <trackLocal>true</trackLocal> </params> - <trackHandlers> - <trackHandler> + <handlers> + <handler> <ID>track1</ID> <trackLink> <URL>LiveAt_videoevent</URL> <type>o</type> <name>Mosiac Live Stream</name> <params> <prop7>${data} Leaderboard Link</prop7> <eVar7>${data} Leaderboard Link</eVar7> </params> </trackLink> - </trackHandler> + </handler> - <trackHandler> + <handler> <ID>track2</ID> <trackLink> <URL>LiveAt_videoevent</URL> <type>o</type> <name>Mosiac Live Stream</name> <params> <prop7>${data.id} Scorecard Search</prop7> <eVar7>${data.id} Scorecard Search</eVar7> <events>event14</events> <eVar8>foo</eVar8> </params> </trackLink> - </trackHandler> + </handler> - <trackHandler> + <handler> <ID>track3</ID> <track> <params> <eVar8>foo</eVar8> <events>event17</events> </params> </track> - </trackHandler> - </trackHandlers> + </handler> + </handlers> </omniture> !-- tracking: GOOGLE --> <google> <!-- enabled: specifies whether GOOGLE tracking will be sent --> <enabled>true</enabled> <account>UA-5555555-5</account> <visualDebug>false</visualDebug> <trackingMode>AS3</trackingMode> - <trackHandlers> - <trackHandler> + <handlers> + <handler> <ID>track1</ID> <trackPageView> <URL>${data} Scorecard Nav</URL> </trackPageView> - </trackHandler> + </handler> - <trackHandler> + <handler> <ID>track2</ID> <trackEvent> <category>LiveAt_videoevent1</category> <action>o1</action> <label>Mosiac Live Stream1</label> <value>1</value> </trackEvent> - </trackHandler> + </handler> - <trackHandler> + <handler> <ID>track3</ID> <trackEvent> <category>LiveAt_videoevent2</category> <action>o2</action> </trackEvent> - </trackHandler> + </handler> - </trackHandlers> + </handlers> </google> <!-- url TRACKING defines a tracker that can ping URLs for a specific track request --> <URL> <!-- enabled: specifies whether url tracking will be sent --> <enabled>true</enabled> <!-- URL track handlers specify a way to respond to a specifically name track request ID - specifies the specific named track request URLs - specifies a list of URLs to ping for that specific track request each URL is actually a template. Therefore the URL can opt to use data which is specific to that named request. This is done using a wrapper notation {data}, specifying the value be replaced by dynamic data. For example: a mediaStarted request may be sent a media object. This media object is represented by {data} in the template. Thus a template of http://foo.com?{data.id} would replace {data.id} with the media's ID like http://foo.com?1234 --> - <trackHandlers> - <trackHandler> + <handlers> + <handler> <ID>track1</ID> <URLs> <URL>http://foo.com/track1.gif</URL> </URLs> - </trackHandler> + </handler> - <trackHandler> + <handler> <ID>track2</ID> <URLs> <URL>http://foo.com/track2.gif?id=${data.id}</URL> </URLs> - </trackHandler> + </handler> - <trackHandler> + <handler> <ID>track3</ID> <URLs> <URL>http://foo.com/track3.gif?id=${data}</URL> </URLs> - </trackHandler> - </trackHandlers> + </handler> + </handlers> </URL> </tracking> \ No newline at end of file diff --git a/test/test_tracking_omniture.xml b/test/test_tracking_omniture.xml index 48a7ab6..9472f62 100644 --- a/test/test_tracking_omniture.xml +++ b/test/test_tracking_omniture.xml @@ -1,58 +1,61 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- tracking: OMNITURE --> -<omniture> -<!-- enabled: specifies whether Omniture tracking will be sent --> - <enabled>true</enabled> - <!-- params: - allows you to generically assign values to all omniture values - NOTE: params set will be sent for every track - This can be use to set special props like <eVar23>pga_mosaic_player_09</eVar23> - --> - <params> - <account>foodotcom</account> - <dc>122</dc> - <delayTracking>2</delayTracking> - <trackingServer>stats.foo.com</trackingServer> - <visitorNameSpace>foo</visitorNameSpace> - <trackLocal>true</trackLocal> - </params> - <trackHandlers> - <trackHandler> - <ID>track1</ID> - <trackLink> - <URL>LiveAt_videoevent</URL> - <type>o</type> - <name>Mosiac Live Stream</name> - <params> - <prop7>${data} Leaderboard Link</prop7> - <eVar7>${data} Leaderboard Link</eVar7> - </params> - </trackLink> - </trackHandler> - - <trackHandler> - <ID>track2</ID> - <trackLink> - <URL>LiveAt_videoevent</URL> - <type>o</type> - <name>Mosiac Live Stream</name> - <params> - <prop7>${data.id} Scorecard Search</prop7> - <eVar7>${data.id} Scorecard Search</eVar7> - <events>event14</events> - <eVar8>foo</eVar8> - </params> - </trackLink> - </trackHandler> - - <trackHandler> - <ID>track3</ID> - <track> - <params> - <eVar8>foo</eVar8> - <events>event17</events> - </params> - </track> - </trackHandler> - </trackHandlers> +<?xml version="1.0" encoding="utf-8"?> +<!-- tracking: OMNITURE --> +<omniture> +<!-- enabled: specifies whether Omniture tracking will be sent --> + <enabled>true</enabled> + <!-- params: + allows you to generically assign values to all omniture values + NOTE: params set will be sent for every track + This can be use to set special props like <eVar23>pga_mosaic_player_09</eVar23> + --> + <params> + <account>foodotcom</account> + <dc>122</dc> + <delayTracking>2</delayTracking> + <trackingServer>stats.foo.com</trackingServer> + <visitorNameSpace>foo</visitorNameSpace> + <trackLocal>true</trackLocal> + </params> + <handlers> + <handler> + <ID>track1</ID> + <type>trackLink</type> + <params> + <URL>LiveAt_videoevent</URL> + <type>o</type> + <name>Mosiac Live Stream</name> + <params> + <prop7>${data} Leaderboard Link</prop7> + <eVar7>${data} Leaderboard Link</eVar7> + </params> + </params> + </handler> + + <handler> + <ID>track2</ID> + <type>trackLink</type> + <params> + <URL>LiveAt_videoevent</URL> + <type>o</type> + <name>Mosiac Live Stream</name> + <params> + <prop6>${data.id} Scorecard Search</prop6> + <eVar7>${data.id} Scorecard Search</eVar7> + <events>event14</events> + <eVar8>foo</eVar8> + </params> + </params> + </handler> + + <handler> + <ID>track3</ID> + <type>track</type> + <params> + <params> + <eVar8>foo</eVar8> + <events>event17</events> + </params> + </params> + </handler> + </handlers> </omniture> \ No newline at end of file diff --git a/test/test_tracking_url.xml b/test/test_tracking_url.xml index b220456..42ceaed 100644 --- a/test/test_tracking_url.xml +++ b/test/test_tracking_url.xml @@ -1,42 +1,42 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- url TRACKING - defines a tracker that can ping URLs for a specific track request ---> -<URL> - <!-- enabled: specifies whether url tracking will be sent --> - <enabled>true</enabled> - - <!-- URL track handlers specify a way to respond to a specifically name track request - ID - specifies the specific named track request - URLs - specifies a list of URLs to ping for that specific track request - each URL is actually a template. - Therefore the URL can opt to use data which is specific to that named request. - This is done using a wrapper notation {data}, specifying the value be replaced by dynamic data. - For example: a mediaStarted request may be sent a media object. - This media object is represented by {data} in the template. - Thus a template of http://foo.com?{data.id} would replace {data.id} with the media's ID like http://foo.com?1234 - - --> - <trackHandlers> - <trackHandler> - <ID>track1</ID> - <URLs> - <URL>http://foo.com/track1.gif</URL> - </URLs> - </trackHandler> - - <trackHandler> - <ID>track2</ID> - <URLs> - <URL>http://foo.com/track2.gif?id=${data.id}</URL> - </URLs> - </trackHandler> - - <trackHandler> - <ID>track3</ID> - <URLs> - <URL>http://foo.com/track3.gif?id=${data}</URL> - </URLs> - </trackHandler> - </trackHandlers> +<?xml version="1.0" encoding="utf-8"?> +<!-- url TRACKING + defines a tracker that can ping URLs for a specific track request +--> +<URL> + <!-- enabled: specifies whether url tracking will be sent --> + <enabled>true</enabled> + + <!-- URL track handlers specify a way to respond to a specifically name track request + ID - specifies the specific named track request + URLs - specifies a list of URLs to ping for that specific track request + each URL is actually a template. + Therefore the URL can opt to use data which is specific to that named request. + This is done using a wrapper notation {data}, specifying the value be replaced by dynamic data. + For example: a mediaStarted request may be sent a media object. + This media object is represented by {data} in the template. + Thus a template of http://foo.com?{data.id} would replace {data.id} with the media's ID like http://foo.com?1234 + + --> + <handlers> + <handler> + <ID>track1</ID> + <params> + <URL>http://foo.com/track1.gif</URL> + </params> + </handler> + + <handler> + <ID>track2</ID> + <params> + <URL>http://foo.com/track2.gif?id=${data.id}</URL> + </params> + </handler> + + <handler> + <ID>track3</ID> + <params> + <URL>http://foo.com/track3.gif?id=${data}</URL> + </params> + </handler> + </handlers> </URL> \ No newline at end of file
dreamsocket/actionscript-analytics-framework
caec51b9274d396353c88adf23df654f961b94b7
[FIX] corrected issue with OmnitureTracker and GoogleTracker not having a default config
diff --git a/src/com/dreamsocket/tracking/google/GoogleTracker.as b/src/com/dreamsocket/tracking/google/GoogleTracker.as index 41aeeec..2efea8a 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTracker.as +++ b/src/com/dreamsocket/tracking/google/GoogleTracker.as @@ -1,171 +1,172 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.tracking.google { import flash.display.DisplayObject; import flash.utils.Dictionary; import com.dreamsocket.utils.PropertyStringUtil; import com.dreamsocket.tracking.ITrack; import com.dreamsocket.tracking.ITracker; import com.dreamsocket.tracking.google.GoogleTrackerConfig; import com.dreamsocket.tracking.google.GoogleTrackEventRequest; import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; import com.dreamsocket.tracking.google.GoogleTrackHandler; import com.google.analytics.GATracker; public class GoogleTracker implements ITracker { public static var display:DisplayObject; public static const ID:String = "GoogleTracker"; protected var m_config:GoogleTrackerConfig; protected var m_display:DisplayObject; protected var m_enabled:Boolean; protected var m_service:GATracker; protected var m_trackHandlers:Dictionary; public function GoogleTracker(p_display:DisplayObject = null) { super(); + this.m_config = new GoogleTrackerConfig(); this.m_display = p_display; this.m_enabled = true; this.m_trackHandlers = new Dictionary(); } public function get config():GoogleTrackerConfig { return this.m_config; } public function set config(p_value:GoogleTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; try { this.m_service = new GATracker(this.m_display == null ? GoogleTracker.display : this.m_display, p_value.account, p_value.trackingMode, p_value.visualDebug); } catch(error:Error) { trace(error); } this.m_enabled = p_value.enabled; this.m_trackHandlers = p_value.trackHandlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function addTrackHandler(p_ID:String, p_trackHandler:GoogleTrackHandler):void { this.m_trackHandlers[p_ID] = p_trackHandler; } public function destroy():void { } public function getTrackHandler(p_ID:String):GoogleTrackHandler { return this.m_trackHandlers[p_ID] as GoogleTrackHandler; } public function removeTrackHandler(p_ID:String):void { delete(this.m_trackHandlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled || this.m_service == null) return; var handler:GoogleTrackHandler = this.m_config.trackHandlers[p_track.type]; if(handler != null) { // has a track handler // call correct track method if(handler.request is GoogleTrackEventRequest) { var eventRequest:GoogleTrackEventRequest = GoogleTrackEventRequest(handler.request); var category:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.category); var action:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.action); var label:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.label); var value:Number = Number(PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.value)); try { this.m_service.trackEvent(category, action, label, value); } catch(error:Error) { trace(error); } } else if(handler.request is GoogleTrackPageViewRequest) { var viewRequest:GoogleTrackPageViewRequest = GoogleTrackPageViewRequest(handler.request); try { this.m_service.trackPageview(PropertyStringUtil.evalPropertyString(p_track.data, viewRequest.URL)); } catch(error:Error) { trace(error); } } } } } } diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as b/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as index 35f6826..5d55cc4 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as @@ -1,169 +1,170 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.tracking.omniture { import flash.display.DisplayObjectContainer; import flash.utils.describeType; import flash.utils.Dictionary; import com.dreamsocket.utils.PropertyStringUtil; import com.dreamsocket.tracking.ITrack; import com.dreamsocket.tracking.ITracker; import com.dreamsocket.tracking.omniture.OmnitureService; import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; import com.dreamsocket.tracking.omniture.OmnitureTrackRequest; import com.dreamsocket.tracking.omniture.OmnitureTrackLinkRequest; public class OmnitureTracker implements ITracker { public static var display:DisplayObjectContainer; public static const ID:String = "OmnitureTracker"; protected var m_config:OmnitureTrackerConfig; protected var m_enabled:Boolean; protected var m_service:OmnitureService; protected var m_trackHandlers:Dictionary; public function OmnitureTracker(p_display:DisplayObjectContainer = null) { super(); + this.m_config = new OmnitureTrackerConfig(); this.m_enabled = true; this.m_service = new OmnitureService(p_display == null ? OmnitureTracker.display : p_display); this.m_trackHandlers = new Dictionary(); } public function get config():OmnitureTrackerConfig { return this.m_config; } public function set config(p_value:OmnitureTrackerConfig):void { if(p_value != this.m_config) { this.m_config = p_value; this.m_service.config = p_value.params; this.m_enabled = p_value.enabled; this.m_trackHandlers = p_value.trackHandlers; } } public function get enabled():Boolean { return this.m_enabled; } public function set enabled(p_enabled:Boolean):void { this.m_enabled = p_enabled; } public function addTrackHandler(p_ID:String, p_trackHandler:OmnitureTrackHandler):void { this.m_trackHandlers[p_ID] = p_trackHandler; } public function getTrackHandler(p_ID:String):OmnitureTrackHandler { return this.m_trackHandlers[p_ID] as OmnitureTrackHandler; } public function removeTrackHandler(p_ID:String):void { delete(this.m_trackHandlers[p_ID]); } public function track(p_track:ITrack):void { if(!this.m_enabled) return; var handler:OmnitureTrackHandler = this.m_config.trackHandlers[p_track.type]; if(handler != null && handler.request != null) { // has a track handler var requestParams:OmnitureParams = new OmnitureParams(); var handlerParams:OmnitureParams; if(handler.request.params != null && handler.request.params is OmnitureParams) { handlerParams = handler.request.params; var desc:XML = describeType(handlerParams); var propNode:XML; var props:XMLList = desc..variable; var prop:String; var val:*; // instance props for each(propNode in props) { prop = propNode.@name; val = handlerParams[prop]; if(val is String && val != null) { requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, val); } } // dynamic prop for(prop in handlerParams) { requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, handlerParams[prop]); } } // call correct track method if(handler.request is OmnitureTrackLinkRequest) { var URL:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.URL); var type:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.type); var name:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.name); this.m_service.trackLink(requestParams, URL, type, name); } else if(handler.request is OmnitureTrackRequest) { this.m_service.track(requestParams); } } } } }
dreamsocket/actionscript-analytics-framework
b592fc86efdce7e0322ac8c49730c18fc73aba92
[NEW] added test for TrackingManager tracking across multiple systems
diff --git a/test/TestTrackingManager.as b/test/TestTrackingManager.as new file mode 100644 index 0000000..2c70f25 --- /dev/null +++ b/test/TestTrackingManager.as @@ -0,0 +1,90 @@ +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package +{ + import com.dreamsocket.tracking.Track; + import com.dreamsocket.tracking.google.GoogleTracker; + import com.dreamsocket.tracking.google.GoogleTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.omniture.OmnitureTracker; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.url.URLTracker; + import com.dreamsocket.tracking.url.URLTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.TrackingManager; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestTrackingManager extends Sprite + { + private var m_loader:URLLoader; + + + public function TestTrackingManager() + { + this.m_loader = new URLLoader(); + this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_loader.load(new URLRequest("test_tracking_multiple.xml")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onXMLLoaded(p_event:Event):void + { + var data:XML = new XML(this.m_loader.data); + + GoogleTracker.display = this; + OmnitureTracker.display = this; + + // create all trackers + TrackingManager.addTracker(GoogleTracker.ID, new GoogleTracker()); + TrackingManager.addTracker(OmnitureTracker.ID, new OmnitureTracker()); + TrackingManager.addTracker(URLTracker.ID, new URLTracker()); + + // configure all trackers + OmnitureTracker(TrackingManager.getTracker(OmnitureTracker.ID)).config = new OmnitureTrackerConfigXMLDecoder().decode(data.omniture[0]); + GoogleTracker(TrackingManager.getTracker(GoogleTracker.ID)).config = new GoogleTrackerConfigXMLDecoder().decode(data.google[0]); + URLTracker(TrackingManager.getTracker(URLTracker.ID)).config = new URLTrackerConfigXMLDecoder().decode(data.URL[0]); + + // perform tracks + TrackingManager.track(new Track("track1", "test string")); + TrackingManager.track(new Track("track2", {id:"testid"})); + TrackingManager.track(new Track("track3", "test string")); + } + } +} diff --git a/test/test_tracking_google.xml b/test/test_tracking_google.xml index c1afc46..519e87b 100644 --- a/test/test_tracking_google.xml +++ b/test/test_tracking_google.xml @@ -1,39 +1,39 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- tracking: GOOGLE --> -<google> -<!-- enabled: specifies whether GOOGLE tracking will be sent --> - <enabled>true</enabled> - - <account>UA-7275490-5</account> - <visualDebug>false</visualDebug> - <trackingMode>AS3</trackingMode> - - <trackHandlers> - <trackHandler> - <ID>track1</ID> - <trackPageView> - <URL>${data} Scorecard Nav</URL> - </trackPageView> - </trackHandler> - - <trackHandler> - <ID>track2</ID> - <trackEvent> - <category>LiveAt_videoevent1</category> - <action>o1</action> - <label>Mosiac Live Stream1</label> - <value>1</value> - </trackEvent> - </trackHandler> - - <trackHandler> - <ID>track3</ID> - <trackEvent> - <category>LiveAt_videoevent2</category> - <action>o2</action> - </trackEvent> - </trackHandler> - - - </trackHandlers> +<?xml version="1.0" encoding="utf-8"?> +<!-- tracking: GOOGLE --> +<google> +<!-- enabled: specifies whether GOOGLE tracking will be sent --> + <enabled>true</enabled> + + <account>UA-5555555-5</account> + <visualDebug>false</visualDebug> + <trackingMode>AS3</trackingMode> + + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <trackPageView> + <URL>${data} Scorecard Nav</URL> + </trackPageView> + </trackHandler> + + <trackHandler> + <ID>track2</ID> + <trackEvent> + <category>LiveAt_videoevent1</category> + <action>o1</action> + <label>Mosiac Live Stream1</label> + <value>1</value> + </trackEvent> + </trackHandler> + + <trackHandler> + <ID>track3</ID> + <trackEvent> + <category>LiveAt_videoevent2</category> + <action>o2</action> + </trackEvent> + </trackHandler> + + + </trackHandlers> </google> \ No newline at end of file diff --git a/test/test_tracking_multiple.xml b/test/test_tracking_multiple.xml new file mode 100644 index 0000000..a367289 --- /dev/null +++ b/test/test_tracking_multiple.xml @@ -0,0 +1,140 @@ +<?xml version="1.0" encoding="utf-8"?> +<tracking> + <!-- tracking: OMNITURE --> + <omniture> + <!-- enabled: specifies whether Omniture tracking will be sent --> + <enabled>true</enabled> + <!-- params: + allows you to generically assign values to all omniture values + NOTE: params set will be sent for every track + This can be use to set special props like <eVar23>pga_mosaic_player_09</eVar23> + --> + <params> + <account>foodotcom</account> + <dc>122</dc> + <delayTracking>2</delayTracking> + <trackingServer>stats.foo.com</trackingServer> + <visitorNameSpace>foo</visitorNameSpace> + <trackLocal>true</trackLocal> + </params> + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <trackLink> + <URL>LiveAt_videoevent</URL> + <type>o</type> + <name>Mosiac Live Stream</name> + <params> + <prop7>${data} Leaderboard Link</prop7> + <eVar7>${data} Leaderboard Link</eVar7> + </params> + </trackLink> + </trackHandler> + + <trackHandler> + <ID>track2</ID> + <trackLink> + <URL>LiveAt_videoevent</URL> + <type>o</type> + <name>Mosiac Live Stream</name> + <params> + <prop7>${data.id} Scorecard Search</prop7> + <eVar7>${data.id} Scorecard Search</eVar7> + <events>event14</events> + <eVar8>foo</eVar8> + </params> + </trackLink> + </trackHandler> + + <trackHandler> + <ID>track3</ID> + <track> + <params> + <eVar8>foo</eVar8> + <events>event17</events> + </params> + </track> + </trackHandler> + </trackHandlers> + </omniture> + !-- tracking: GOOGLE --> + <google> + <!-- enabled: specifies whether GOOGLE tracking will be sent --> + <enabled>true</enabled> + + <account>UA-5555555-5</account> + <visualDebug>false</visualDebug> + <trackingMode>AS3</trackingMode> + + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <trackPageView> + <URL>${data} Scorecard Nav</URL> + </trackPageView> + </trackHandler> + + <trackHandler> + <ID>track2</ID> + <trackEvent> + <category>LiveAt_videoevent1</category> + <action>o1</action> + <label>Mosiac Live Stream1</label> + <value>1</value> + </trackEvent> + </trackHandler> + + <trackHandler> + <ID>track3</ID> + <trackEvent> + <category>LiveAt_videoevent2</category> + <action>o2</action> + </trackEvent> + </trackHandler> + + + </trackHandlers> + </google> + +<!-- url TRACKING + defines a tracker that can ping URLs for a specific track request +--> + <URL> + <!-- enabled: specifies whether url tracking will be sent --> + <enabled>true</enabled> + + <!-- URL track handlers specify a way to respond to a specifically name track request + ID - specifies the specific named track request + URLs - specifies a list of URLs to ping for that specific track request + each URL is actually a template. + Therefore the URL can opt to use data which is specific to that named request. + This is done using a wrapper notation {data}, specifying the value be replaced by dynamic data. + For example: a mediaStarted request may be sent a media object. + This media object is represented by {data} in the template. + Thus a template of http://foo.com?{data.id} would replace {data.id} with the media's ID like http://foo.com?1234 + + --> + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <URLs> + <URL>http://foo.com/track1.gif</URL> + </URLs> + </trackHandler> + + <trackHandler> + <ID>track2</ID> + <URLs> + <URL>http://foo.com/track2.gif?id=${data.id}</URL> + </URLs> + </trackHandler> + + <trackHandler> + <ID>track3</ID> + <URLs> + <URL>http://foo.com/track3.gif?id=${data}</URL> + </URLs> + </trackHandler> + </trackHandlers> + </URL> +</tracking> \ No newline at end of file
dreamsocket/actionscript-analytics-framework
8e2db6d22c52bb6cbd62845c1e7943647d9d7b0a
[FIX] corrected JS config parser and used XML in TestJSTracker
diff --git a/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as index f2c026f..ad0d68f 100644 --- a/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as @@ -1,89 +1,97 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package com.dreamsocket.tracking.js { import flash.utils.Dictionary; import com.dreamsocket.tracking.js.JSTrackerConfig; import com.dreamsocket.tracking.js.JSTrackHandler; public class JSTrackerConfigXMLDecoder { public function JSTrackerConfigXMLDecoder() { } public function decode(p_xml:XML):JSTrackerConfig { var config:JSTrackerConfig = new JSTrackerConfig(); var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; var trackHandlerNode:XML; var trackHandlers:Dictionary = config.trackHandlers; // trackHandlers for each(trackHandlerNode in trackHandlerNodes) { this.addTrack(trackHandlers, trackHandlerNode); } // enabled config.enabled = p_xml.enabled.toString() != "false"; return config; } protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void { var ID:String = p_trackHandlerNode.ID.toString(); var methodCallNode:XML; var handler:JSTrackHandler; if(ID.length > 0) { handler = new JSTrackHandler(); for each(methodCallNode in p_trackHandlerNode.methodCalls.methodCall) { + handler.ID = ID; handler.methodCalls.push(this.createMethodCall(methodCallNode[0])); } p_trackHandlers[ID] = handler; } } protected function createMethodCall(p_methodNode:XML):JSMethodCall { var methodCall:JSMethodCall = new JSMethodCall(p_methodNode.ID.toString()); - var arguments:Array = p_methodNode.arguments.argument; - var argumentNode - for each() - methodCall.arguments + var argumentNodes:XMLList = p_methodNode.arguments.argument; + var argumentNode:XML; + + methodCall.method = p_methodNode.method.toString(); + + for each(argumentNode in argumentNodes) + { + methodCall.arguments.push(argumentNode); + } + + return methodCall; } } } diff --git a/test/TestJSTracker.as b/test/TestJSTracker.as index 68364b4..b511aae 100644 --- a/test/TestJSTracker.as +++ b/test/TestJSTracker.as @@ -1,90 +1,93 @@ /** * Dreamsocket, Inc. * http://dreamsocket.com * Copyright 2010 Dreamsocket, Inc. * * 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. **/ package { import flash.utils.Dictionary; import com.dreamsocket.tracking.Track; import com.dreamsocket.tracking.js.JSTrackerConfig; import com.dreamsocket.tracking.js.JSMethodCall; import com.dreamsocket.tracking.js.JSTrackerConfigXMLDecoder; import com.dreamsocket.tracking.js.JSTracker; import com.dreamsocket.tracking.js.JSTrackHandler; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.URLRequest; import flash.net.URLLoader; public class TestJSTracker extends Sprite { private var m_loader:URLLoader; private var m_tracker:JSTracker; public function TestJSTracker() { - //this.m_loader = new URLLoader(); - //this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); - //this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); - //this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); - //this.m_loader.load(new URLRequest("test_tracking_omniture.xml")); - - var config:JSTrackerConfig = new JSTrackerConfig(); - var trackHandler:JSTrackHandler; - - this.m_tracker = new JSTracker(); - this.m_tracker.config = config; - - trackHandler = new JSTrackHandler(); - trackHandler.ID = "track3"; - trackHandler.methodCalls = [new JSMethodCall("doRandomThing", [1, 2, "3...{data.id}"])]; - - config.trackHandlers["track2"] = trackHandler; + this.m_loader = new URLLoader(); + this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_loader.load(new URLRequest("test_tracking_javascript.xml")); + //var config:JSTrackerConfig = new JSTrackerConfig(); + //var trackHandler:JSTrackHandler; + //this.m_tracker = new JSTracker(); + //this.m_tracker.config = config; + //trackHandler = new JSTrackHandler(); + //trackHandler.ID = "track3"; + //trackHandler.methodCalls = [new JSMethodCall("doJS", [1, 2, "3...${data.id}"])]; - this.m_tracker.track(new Track("track1", "test string1")); - this.m_tracker.track(new Track("track2", {id:"testid"})); - this.m_tracker.track(new Track("track3", "test string3")); + //config.trackHandlers["track1"] = trackHandler; + //config.trackHandlers["track2"] = trackHandler; + + //this.m_tracker.track(new Track("track1", "test string1")); + //this.m_tracker.track(new Track("track2", {id:"testid"})); + //this.m_tracker.track(new Track("track3", "test string3")); } private function onErrorOccurred(p_event:Event):void { trace(p_event); } private function onXMLLoaded(p_event:Event):void { - + this.m_tracker = new JSTracker(); + this.m_tracker.config = new JSTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); + + this.m_tracker.track(new Track("track1", "test string1")); + this.m_tracker.track(new Track("track2", {id:"testid"})); + this.m_tracker.track(new Track("track3", "test string3")); } } } diff --git a/test/TestJSTracker.html b/test/TestJSTracker.html index 61d7891..2d481e5 100644 --- a/test/TestJSTracker.html +++ b/test/TestJSTracker.html @@ -1,20 +1,20 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -<html> - <head> - <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> - <title>TestJSTracker</title> - <script language="JavaScript1.2" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" type="text/javascript"></script> - - </head> - <body> - <div id="test_swf"></div> - <script> - function doRandomThing(p_arg1, p_arg2, p_arg3) - { - alert(p_arg1 + "-" + p_arg2 + "-" + p_arg3); - } - - swfobject.embedSWF("TestJSTracker.swf", "test_swf", 500, 400, "9.0.0", "TestJSTracker.swf", {}, {allowScriptAccess:"always"}); - </script> - </body> -</html> +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> + <title>TestJSTracker</title> + <script language="JavaScript1.2" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" type="text/javascript"></script> + + </head> + <body> + <div id="test_swf"></div> + <script> + function doJS(p_arg1, p_arg2, p_arg3) + { + alert(p_arg1 + "-" + p_arg2 + "-" + p_arg3); + } + + swfobject.embedSWF("TestJSTracker.swf", "test_swf", 500, 400, "9.0.0", "TestJSTracker.swf", {}, {allowScriptAccess:"always"}); + </script> + </body> +</html> diff --git a/test/test_tracking_javascript.xml b/test/test_tracking_javascript.xml index b70bcea..6a8185a 100644 --- a/test/test_tracking_javascript.xml +++ b/test/test_tracking_javascript.xml @@ -1,25 +1,25 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- url TRACKING - defines a tracker that can ping URLs for a specific track request ---> -<JavaScript> - <!-- enabled: specifies whether url tracking will be sent --> - <enabled>true</enabled> - - <trackHandlers> - <trackHandler> - <ID>track1</ID> - <methodCalls> - <methodCall> - <method>doJS</method> - <arguments> - <argument>1</argument> - <argument>2</argument> - <argument>3</argument> - </arguments> - </methodCall> - </methodCalls> - </trackHandler> - - </trackHandlers> +<?xml version="1.0" encoding="utf-8"?> +<!-- url TRACKING + defines a tracker that can ping URLs for a specific track request +--> +<JavaScript> + <!-- enabled: specifies whether url tracking will be sent --> + <enabled>true</enabled> + + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <methodCalls> + <methodCall> + <method>doJS</method> + <arguments> + <argument>${data} a</argument> + <argument>b</argument> + <argument>c</argument> + </arguments> + </methodCall> + </methodCalls> + </trackHandler> + + </trackHandlers> </JavaScript> \ No newline at end of file
dreamsocket/actionscript-analytics-framework
f70a1b7b31cfe829f31e0fc2c2bf1c3fdbeec40d
[CHG] updated legal header to open source
diff --git a/test/TestGoogleTracker.as b/test/TestGoogleTracker.as index 16a0a96..66e4282 100644 --- a/test/TestGoogleTracker.as +++ b/test/TestGoogleTracker.as @@ -1,68 +1,76 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package -{ - import com.dreamsocket.tracking.Track; - import com.dreamsocket.tracking.google.GoogleTrackerConfig; - import com.dreamsocket.tracking.google.GoogleTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.google.GoogleTracker; - - import flash.display.Sprite; - import flash.events.Event; - import flash.events.IOErrorEvent; - import flash.events.SecurityErrorEvent; - import flash.net.URLRequest; - import flash.net.URLLoader; - - public class TestGoogleTracker extends Sprite - { - private var m_loader:URLLoader; - private var m_tracker:GoogleTracker; - - public function TestGoogleTracker() - { - this.m_loader = new URLLoader(); - this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); - this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); - this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); - this.m_loader.load(new URLRequest("test_tracking_google.xml")); - } - - - private function onErrorOccurred(p_event:Event):void - { - trace(p_event); - } - - - private function onXMLLoaded(p_event:Event):void - { - var config:GoogleTrackerConfig = new GoogleTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); - - this.m_tracker = new GoogleTracker(this); - this.m_tracker.config = config; - - this.m_tracker.track(new Track("track1", "test string")); - this.m_tracker.track(new Track("track2", {id:"testid"})); - this.m_tracker.track(new Track("track3", "test string")); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package +{ + import com.dreamsocket.tracking.Track; + import com.dreamsocket.tracking.google.GoogleTrackerConfig; + import com.dreamsocket.tracking.google.GoogleTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.google.GoogleTracker; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestGoogleTracker extends Sprite + { + private var m_loader:URLLoader; + private var m_tracker:GoogleTracker; + + public function TestGoogleTracker() + { + this.m_loader = new URLLoader(); + this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_loader.load(new URLRequest("test_tracking_google.xml")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onXMLLoaded(p_event:Event):void + { + var config:GoogleTrackerConfig = new GoogleTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); + + this.m_tracker = new GoogleTracker(this); + this.m_tracker.config = config; + + this.m_tracker.track(new Track("track1", "test string")); + this.m_tracker.track(new Track("track2", {id:"testid"})); + this.m_tracker.track(new Track("track3", "test string")); + } + } +} diff --git a/test/TestJSTracker.as b/test/TestJSTracker.as index 7a268d1..68364b4 100644 --- a/test/TestJSTracker.as +++ b/test/TestJSTracker.as @@ -1,82 +1,90 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package -{ - import flash.utils.Dictionary; - - import com.dreamsocket.tracking.Track; - import com.dreamsocket.tracking.js.JSTrackerConfig; - import com.dreamsocket.tracking.js.JSMethodCall; - import com.dreamsocket.tracking.js.JSTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.js.JSTracker; - import com.dreamsocket.tracking.js.JSTrackHandler; - - import flash.display.Sprite; - import flash.events.Event; - import flash.events.IOErrorEvent; - import flash.events.SecurityErrorEvent; - import flash.net.URLRequest; - import flash.net.URLLoader; - - public class TestJSTracker extends Sprite - { - private var m_loader:URLLoader; - private var m_tracker:JSTracker; - - public function TestJSTracker() - { - //this.m_loader = new URLLoader(); - //this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); - //this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); - //this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); - //this.m_loader.load(new URLRequest("test_tracking_omniture.xml")); - - var config:JSTrackerConfig = new JSTrackerConfig(); - var trackHandler:JSTrackHandler; - - this.m_tracker = new JSTracker(); - this.m_tracker.config = config; - - trackHandler = new JSTrackHandler(); - trackHandler.ID = "track3"; - trackHandler.methodCalls = [new JSMethodCall("doRandomThing", [1, 2, "3...{data.id}"])]; - - config.trackHandlers["track2"] = trackHandler; - - - this.m_tracker.track(new Track("track1", "test string1")); - this.m_tracker.track(new Track("track2", {id:"testid"})); - this.m_tracker.track(new Track("track3", "test string3")); - } - - - private function onErrorOccurred(p_event:Event):void - { - trace(p_event); - } - - - private function onXMLLoaded(p_event:Event):void - { - - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.Track; + import com.dreamsocket.tracking.js.JSTrackerConfig; + import com.dreamsocket.tracking.js.JSMethodCall; + import com.dreamsocket.tracking.js.JSTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.js.JSTracker; + import com.dreamsocket.tracking.js.JSTrackHandler; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestJSTracker extends Sprite + { + private var m_loader:URLLoader; + private var m_tracker:JSTracker; + + public function TestJSTracker() + { + //this.m_loader = new URLLoader(); + //this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + //this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + //this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + //this.m_loader.load(new URLRequest("test_tracking_omniture.xml")); + + var config:JSTrackerConfig = new JSTrackerConfig(); + var trackHandler:JSTrackHandler; + + this.m_tracker = new JSTracker(); + this.m_tracker.config = config; + + trackHandler = new JSTrackHandler(); + trackHandler.ID = "track3"; + trackHandler.methodCalls = [new JSMethodCall("doRandomThing", [1, 2, "3...{data.id}"])]; + + config.trackHandlers["track2"] = trackHandler; + + + this.m_tracker.track(new Track("track1", "test string1")); + this.m_tracker.track(new Track("track2", {id:"testid"})); + this.m_tracker.track(new Track("track3", "test string3")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onXMLLoaded(p_event:Event):void + { + + } + } +} diff --git a/test/TestOmnitureTracker.as b/test/TestOmnitureTracker.as index 804df84..1eb6991 100644 --- a/test/TestOmnitureTracker.as +++ b/test/TestOmnitureTracker.as @@ -1,68 +1,75 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package -{ - import com.dreamsocket.tracking.Track; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfigXMLDecoder; - import com.dreamsocket.tracking.omniture.OmnitureTracker; - - import flash.display.Sprite; - import flash.events.Event; - import flash.events.IOErrorEvent; - import flash.events.SecurityErrorEvent; - import flash.net.URLRequest; - import flash.net.URLLoader; - - public class TestOmnitureTracker extends Sprite - { - private var m_loader:URLLoader; - private var m_tracker:OmnitureTracker; - - public function TestOmnitureTracker() - { - this.m_loader = new URLLoader(); - this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); - this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); - this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); - this.m_loader.load(new URLRequest("test_tracking_omniture.xml")); - } - - - private function onErrorOccurred(p_event:Event):void - { - trace(p_event); - } - - - private function onXMLLoaded(p_event:Event):void - { - var config:OmnitureTrackerConfig = new OmnitureTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); - - this.m_tracker = new OmnitureTracker(); - this.m_tracker.config = config; - - this.m_tracker.track(new Track("track1", "test string")); - this.m_tracker.track(new Track("track2", {id:"testid"})); - this.m_tracker.track(new Track("track3", "test string")); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + +package +{ + import com.dreamsocket.tracking.Track; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.omniture.OmnitureTracker; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestOmnitureTracker extends Sprite + { + private var m_loader:URLLoader; + private var m_tracker:OmnitureTracker; + + public function TestOmnitureTracker() + { + this.m_loader = new URLLoader(); + this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_loader.load(new URLRequest("test_tracking_omniture.xml")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onXMLLoaded(p_event:Event):void + { + var config:OmnitureTrackerConfig = new OmnitureTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); + + this.m_tracker = new OmnitureTracker(); + this.m_tracker.config = config; + + this.m_tracker.track(new Track("track1", "test string")); + this.m_tracker.track(new Track("track2", {id:"testid"})); + this.m_tracker.track(new Track("track3", "test string")); + } + } +}
dreamsocket/actionscript-analytics-framework
c29dbd9b0edc4dfcd56ccea3edb7f336138b80de
[CHG] updated legal header to open source
diff --git a/src/com/dreamsocket/tracking/ITrack.as b/src/com/dreamsocket/tracking/ITrack.as index d35bd13..17b0b47 100644 --- a/src/com/dreamsocket/tracking/ITrack.as +++ b/src/com/dreamsocket/tracking/ITrack.as @@ -1,28 +1,37 @@ -/** - * Dreamsocket, Inc. - * - * Copyright 2009 Dreamsocket, Inc.. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket, Inc.. - * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under - * applicable law. - * - */ - - -package com.dreamsocket.tracking -{ - - public interface ITrack - { - function get data():*; - function get type():String; - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking +{ + + public interface ITrack + { + function get data():*; + function get type():String; + } +} diff --git a/src/com/dreamsocket/tracking/ITracker.as b/src/com/dreamsocket/tracking/ITracker.as index 61b7166..f9267bd 100644 --- a/src/com/dreamsocket/tracking/ITracker.as +++ b/src/com/dreamsocket/tracking/ITracker.as @@ -1,29 +1,38 @@ -/** - * Dreamsocket, Inc. - * - * Copyright 2009 Dreamsocket, Inc.. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket, Inc.. - * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under - * applicable law. - * - */ - - -package com.dreamsocket.tracking -{ - import com.dreamsocket.tracking.ITrack; - - - public interface ITracker - { - function track(p_track:ITrack):void - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking +{ + import com.dreamsocket.tracking.ITrack; + + + public interface ITracker + { + function track(p_track:ITrack):void + } +} diff --git a/src/com/dreamsocket/tracking/Track.as b/src/com/dreamsocket/tracking/Track.as index 744fa1e..5acf52b 100644 --- a/src/com/dreamsocket/tracking/Track.as +++ b/src/com/dreamsocket/tracking/Track.as @@ -1,48 +1,56 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking -{ - import com.dreamsocket.tracking.ITrack; - - public class Track implements ITrack - { - protected var m_data:*; - protected var m_type:String; - - public function Track(p_type:String, p_data:* = null) - { - this.m_type = p_type; - this.m_data = p_data; - } - - - public function get data():* - { - return this.m_data; - } - - - public function get type():String - { - return this.m_type; - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking +{ + import com.dreamsocket.tracking.ITrack; + + public class Track implements ITrack + { + protected var m_data:*; + protected var m_type:String; + + public function Track(p_type:String, p_data:* = null) + { + this.m_type = p_type; + this.m_data = p_data; + } + + + public function get data():* + { + return this.m_data; + } + + + public function get type():String + { + return this.m_type; + } + } +} diff --git a/src/com/dreamsocket/tracking/TrackingManager.as b/src/com/dreamsocket/tracking/TrackingManager.as index 0e0902d..431ce50 100644 --- a/src/com/dreamsocket/tracking/TrackingManager.as +++ b/src/com/dreamsocket/tracking/TrackingManager.as @@ -1,79 +1,88 @@ -/** - * Dreamsocket, Inc. - * - * Copyright 2009 Dreamsocket, Inc.. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket, Inc.. - * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under - * applicable law. - * - */ - - -package com.dreamsocket.tracking -{ - import flash.utils.Dictionary; - - public class TrackingManager - { - protected static var k_enabled:Boolean = true; - protected static var k_trackers:Dictionary = new Dictionary(); - - - public function TrackingManager() - { - } - - - public static function get enabled():Boolean - { - return k_enabled; - } - - - public static function set enabled(p_enabled:Boolean):void - { - k_enabled = p_enabled; - } - - - - public static function track(p_track:ITrack):void - { - if(!k_enabled) return; - - var tracker:Object; - - // send track payload to all trackers - for each(tracker in k_trackers) - { - ITracker(tracker).track(p_track); - } - } - - - public static function addTracker(p_ID:String, p_tracker:ITracker):void - { - k_trackers[p_ID] = p_tracker; - } - - - public static function getTracker(p_ID:String):ITracker - { - return k_trackers[p_ID] as ITracker; - } - - - public static function removeTracker(p_ID:String):void - { - delete(k_trackers[p_ID]); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking +{ + import flash.utils.Dictionary; + + public class TrackingManager + { + protected static var k_enabled:Boolean = true; + protected static var k_trackers:Dictionary = new Dictionary(); + + + public function TrackingManager() + { + } + + + public static function get enabled():Boolean + { + return k_enabled; + } + + + public static function set enabled(p_enabled:Boolean):void + { + k_enabled = p_enabled; + } + + + + public static function track(p_track:ITrack):void + { + if(!k_enabled) return; + + var tracker:Object; + + // send track payload to all trackers + for each(tracker in k_trackers) + { + ITracker(tracker).track(p_track); + } + } + + + public static function addTracker(p_ID:String, p_tracker:ITracker):void + { + k_trackers[p_ID] = p_tracker; + } + + + public static function getTracker(p_ID:String):ITracker + { + return k_trackers[p_ID] as ITracker; + } + + + public static function removeTracker(p_ID:String):void + { + delete(k_trackers[p_ID]); + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as b/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as index 9106c67..ea1542b 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as +++ b/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as @@ -1,50 +1,58 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.google -{ - public class GoogleTrackEventRequest - { - /** - * specifies a string representing groups of events. - */ - public var category:String; - - /** - * specifies a string that is paired with each category and is typically used to track activities - */ - public var action:String; - - /** - * specifies an optional string that provides additional scoping to the category/action pairing - */ - public var label:String; - - /** - * specifies an optional non negative integer for numerical data - */ - public var value:String; - - - public function GoogleTrackEventRequest() - { - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.google +{ + public class GoogleTrackEventRequest + { + /** + * specifies a string representing groups of events. + */ + public var category:String; + + /** + * specifies a string that is paired with each category and is typically used to track activities + */ + public var action:String; + + /** + * specifies an optional string that provides additional scoping to the category/action pairing + */ + public var label:String; + + /** + * specifies an optional non negative integer for numerical data + */ + public var value:String; + + + public function GoogleTrackEventRequest() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as b/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as index daf0892..f7bcb41 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as +++ b/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as @@ -1,32 +1,40 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.google -{ - public class GoogleTrackHandler - { - public var ID:String; - public var request:Object; // GoogleTrackPageViewRequest, GoogleTrackEventRequest - - public function GoogleTrackHandler() - { - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.google +{ + public class GoogleTrackHandler + { + public var ID:String; + public var request:Object; // GoogleTrackPageViewRequest, GoogleTrackEventRequest + + public function GoogleTrackHandler() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as b/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as index 5dd4563..42312ed 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as +++ b/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as @@ -1,31 +1,39 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.google -{ - public class GoogleTrackPageViewRequest - { - public var URL:String; - - public function GoogleTrackPageViewRequest() - { - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.google +{ + public class GoogleTrackPageViewRequest + { + public var URL:String; + + public function GoogleTrackPageViewRequest() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTracker.as b/src/com/dreamsocket/tracking/google/GoogleTracker.as index 786424f..41aeeec 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTracker.as +++ b/src/com/dreamsocket/tracking/google/GoogleTracker.as @@ -1,163 +1,171 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.google -{ - import flash.display.DisplayObject; - import flash.utils.Dictionary; - - import com.dreamsocket.utils.PropertyStringUtil; - import com.dreamsocket.tracking.ITrack; - import com.dreamsocket.tracking.ITracker; - import com.dreamsocket.tracking.google.GoogleTrackerConfig; - import com.dreamsocket.tracking.google.GoogleTrackEventRequest; - import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; - import com.dreamsocket.tracking.google.GoogleTrackHandler; - - import com.google.analytics.GATracker; - - - public class GoogleTracker implements ITracker - { - public static var display:DisplayObject; - - public static const ID:String = "GoogleTracker"; - - protected var m_config:GoogleTrackerConfig; - protected var m_display:DisplayObject; - protected var m_enabled:Boolean; - protected var m_service:GATracker; - protected var m_trackHandlers:Dictionary; - - public function GoogleTracker(p_display:DisplayObject = null) - { - super(); - - this.m_display = p_display; - this.m_enabled = true; - this.m_trackHandlers = new Dictionary(); - } - - - public function get config():GoogleTrackerConfig - { - return this.m_config; - } - - - public function set config(p_value:GoogleTrackerConfig):void - { - if(p_value != this.m_config) - { - this.m_config = p_value; - - try - { - this.m_service = new GATracker(this.m_display == null ? GoogleTracker.display : this.m_display, p_value.account, p_value.trackingMode, p_value.visualDebug); - } - catch(error:Error) - { - trace(error); - } - this.m_enabled = p_value.enabled; - this.m_trackHandlers = p_value.trackHandlers; - } - } - - - public function get enabled():Boolean - { - return this.m_enabled; - } - - - public function set enabled(p_enabled:Boolean):void - { - this.m_enabled = p_enabled; - } - - - public function addTrackHandler(p_ID:String, p_trackHandler:GoogleTrackHandler):void - { - this.m_trackHandlers[p_ID] = p_trackHandler; - } - - - public function destroy():void - { - } - - - public function getTrackHandler(p_ID:String):GoogleTrackHandler - { - return this.m_trackHandlers[p_ID] as GoogleTrackHandler; - } - - - public function removeTrackHandler(p_ID:String):void - { - delete(this.m_trackHandlers[p_ID]); - } - - - public function track(p_track:ITrack):void - { - if(!this.m_enabled || this.m_service == null) return; - - var handler:GoogleTrackHandler = this.m_config.trackHandlers[p_track.type]; - - - if(handler != null) - { // has a track handler - // call correct track method - if(handler.request is GoogleTrackEventRequest) - { - var eventRequest:GoogleTrackEventRequest = GoogleTrackEventRequest(handler.request); - var category:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.category); - var action:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.action); - var label:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.label); - var value:Number = Number(PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.value)); - - try - { - this.m_service.trackEvent(category, action, label, value); - } - catch(error:Error) - { - trace(error); - } - } - else if(handler.request is GoogleTrackPageViewRequest) - { - var viewRequest:GoogleTrackPageViewRequest = GoogleTrackPageViewRequest(handler.request); - - try - { - this.m_service.trackPageview(PropertyStringUtil.evalPropertyString(p_track.data, viewRequest.URL)); - } - catch(error:Error) - { - trace(error); - } - } - } - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.google +{ + import flash.display.DisplayObject; + import flash.utils.Dictionary; + + import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.tracking.ITracker; + import com.dreamsocket.tracking.google.GoogleTrackerConfig; + import com.dreamsocket.tracking.google.GoogleTrackEventRequest; + import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; + import com.dreamsocket.tracking.google.GoogleTrackHandler; + + import com.google.analytics.GATracker; + + + public class GoogleTracker implements ITracker + { + public static var display:DisplayObject; + + public static const ID:String = "GoogleTracker"; + + protected var m_config:GoogleTrackerConfig; + protected var m_display:DisplayObject; + protected var m_enabled:Boolean; + protected var m_service:GATracker; + protected var m_trackHandlers:Dictionary; + + public function GoogleTracker(p_display:DisplayObject = null) + { + super(); + + this.m_display = p_display; + this.m_enabled = true; + this.m_trackHandlers = new Dictionary(); + } + + + public function get config():GoogleTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:GoogleTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + + try + { + this.m_service = new GATracker(this.m_display == null ? GoogleTracker.display : this.m_display, p_value.account, p_value.trackingMode, p_value.visualDebug); + } + catch(error:Error) + { + trace(error); + } + this.m_enabled = p_value.enabled; + this.m_trackHandlers = p_value.trackHandlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function addTrackHandler(p_ID:String, p_trackHandler:GoogleTrackHandler):void + { + this.m_trackHandlers[p_ID] = p_trackHandler; + } + + + public function destroy():void + { + } + + + public function getTrackHandler(p_ID:String):GoogleTrackHandler + { + return this.m_trackHandlers[p_ID] as GoogleTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_trackHandlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled || this.m_service == null) return; + + var handler:GoogleTrackHandler = this.m_config.trackHandlers[p_track.type]; + + + if(handler != null) + { // has a track handler + // call correct track method + if(handler.request is GoogleTrackEventRequest) + { + var eventRequest:GoogleTrackEventRequest = GoogleTrackEventRequest(handler.request); + var category:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.category); + var action:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.action); + var label:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.label); + var value:Number = Number(PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.value)); + + try + { + this.m_service.trackEvent(category, action, label, value); + } + catch(error:Error) + { + trace(error); + } + } + else if(handler.request is GoogleTrackPageViewRequest) + { + var viewRequest:GoogleTrackPageViewRequest = GoogleTrackPageViewRequest(handler.request); + + try + { + this.m_service.trackPageview(PropertyStringUtil.evalPropertyString(p_track.data, viewRequest.URL)); + } + catch(error:Error) + { + trace(error); + } + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as b/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as index b2a32d6..bcc3ebe 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as +++ b/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as @@ -1,44 +1,52 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.google -{ - import flash.utils.Dictionary; - - import com.google.analytics.core.TrackerMode; - - - public class GoogleTrackerConfig - { - public var account:String; - public var enabled:Boolean; - public var trackingMode:String; - public var visualDebug:Boolean; - public var trackHandlers:Dictionary; - - - public function GoogleTrackerConfig() - { - this.enabled = true; - this.trackingMode = TrackerMode.AS3; - this.trackHandlers = new Dictionary(); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.google +{ + import flash.utils.Dictionary; + + import com.google.analytics.core.TrackerMode; + + + public class GoogleTrackerConfig + { + public var account:String; + public var enabled:Boolean; + public var trackingMode:String; + public var visualDebug:Boolean; + public var trackHandlers:Dictionary; + + + public function GoogleTrackerConfig() + { + this.enabled = true; + this.trackingMode = TrackerMode.AS3; + this.trackHandlers = new Dictionary(); + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as index cf4ffc0..b1a01db 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as @@ -1,107 +1,115 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.google -{ - import flash.utils.Dictionary; - - import com.dreamsocket.tracking.google.GoogleTrackerConfig; - import com.dreamsocket.tracking.google.GoogleTrackHandler; - import com.dreamsocket.tracking.google.GoogleTrackEventRequest; - import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; - - import com.google.analytics.core.TrackerMode; - - - - public class GoogleTrackerConfigXMLDecoder - { - public function GoogleTrackerConfigXMLDecoder() - { - super(); - } - - - public function decode(p_XML:XML):GoogleTrackerConfig - { - var config:GoogleTrackerConfig = new GoogleTrackerConfig(); - - if(p_XML.account.toString().length) - config.account = p_XML.account.toString(); - - config.enabled = p_XML.enabled.toString() != "false"; - config.trackingMode = p_XML.trackingMode.toString() == TrackerMode.AS3 ? TrackerMode.AS3 : TrackerMode.BRIDGE; - config.visualDebug = p_XML.visualDebug.toString() != "false"; - - this.setTrackHandlers(config.trackHandlers, p_XML.trackHandlers.trackHandler); - - return config; - } - - - public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void - { - var handler:GoogleTrackHandler; - var handlerNode:XML; - var ID:String; - var eventRequest:GoogleTrackEventRequest; - var pageViewRequest:GoogleTrackPageViewRequest; - var trackNode:XML; - - for each(handlerNode in p_handlerNodes) - { - ID = handlerNode.ID.toString(); - if(ID.length > 0) - { - if(handlerNode.trackEvent.toString().length) - { // decode trackPageView - handler = new GoogleTrackHandler(); - handler.ID = ID; - handler.request = eventRequest = new GoogleTrackEventRequest(); - trackNode = handlerNode.trackEvent[0]; - - if(trackNode.action.toString().length) - eventRequest.action = trackNode.action.toString(); - if(trackNode.category.toString().length) - eventRequest.category = trackNode.category.toString(); - if(trackNode.label.toString().length) - eventRequest.label = trackNode.label.toString(); - if(trackNode.value.toString().length) - eventRequest.value = trackNode.value.toString(); - - p_handlers[ID] = handler; - } - else if(handlerNode.trackPageView.toString().length) - { // decode track - handler = new GoogleTrackHandler(); - handler.ID = ID; - handler.request = pageViewRequest = new GoogleTrackPageViewRequest(); - trackNode = handlerNode.trackPageView[0]; - - if(trackNode.URL.toString().length) - pageViewRequest.URL = trackNode.URL.toString(); - - p_handlers[ID] = handler; - } - } - } - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.google +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.google.GoogleTrackerConfig; + import com.dreamsocket.tracking.google.GoogleTrackHandler; + import com.dreamsocket.tracking.google.GoogleTrackEventRequest; + import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; + + import com.google.analytics.core.TrackerMode; + + + + public class GoogleTrackerConfigXMLDecoder + { + public function GoogleTrackerConfigXMLDecoder() + { + super(); + } + + + public function decode(p_XML:XML):GoogleTrackerConfig + { + var config:GoogleTrackerConfig = new GoogleTrackerConfig(); + + if(p_XML.account.toString().length) + config.account = p_XML.account.toString(); + + config.enabled = p_XML.enabled.toString() != "false"; + config.trackingMode = p_XML.trackingMode.toString() == TrackerMode.AS3 ? TrackerMode.AS3 : TrackerMode.BRIDGE; + config.visualDebug = p_XML.visualDebug.toString() != "false"; + + this.setTrackHandlers(config.trackHandlers, p_XML.trackHandlers.trackHandler); + + return config; + } + + + public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void + { + var handler:GoogleTrackHandler; + var handlerNode:XML; + var ID:String; + var eventRequest:GoogleTrackEventRequest; + var pageViewRequest:GoogleTrackPageViewRequest; + var trackNode:XML; + + for each(handlerNode in p_handlerNodes) + { + ID = handlerNode.ID.toString(); + if(ID.length > 0) + { + if(handlerNode.trackEvent.toString().length) + { // decode trackPageView + handler = new GoogleTrackHandler(); + handler.ID = ID; + handler.request = eventRequest = new GoogleTrackEventRequest(); + trackNode = handlerNode.trackEvent[0]; + + if(trackNode.action.toString().length) + eventRequest.action = trackNode.action.toString(); + if(trackNode.category.toString().length) + eventRequest.category = trackNode.category.toString(); + if(trackNode.label.toString().length) + eventRequest.label = trackNode.label.toString(); + if(trackNode.value.toString().length) + eventRequest.value = trackNode.value.toString(); + + p_handlers[ID] = handler; + } + else if(handlerNode.trackPageView.toString().length) + { // decode track + handler = new GoogleTrackHandler(); + handler.ID = ID; + handler.request = pageViewRequest = new GoogleTrackPageViewRequest(); + trackNode = handlerNode.trackPageView[0]; + + if(trackNode.URL.toString().length) + pageViewRequest.URL = trackNode.URL.toString(); + + p_handlers[ID] = handler; + } + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as b/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as index f8995cb..beae71c 100644 --- a/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as +++ b/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as @@ -1,26 +1,34 @@ -/** - * Dreamsocket - * - * Copyright 2010 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.google -{ - public class GoogleTrackerParams - { - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.google +{ + public class GoogleTrackerParams + { + } +} diff --git a/src/com/dreamsocket/tracking/js/JSMethodCall.as b/src/com/dreamsocket/tracking/js/JSMethodCall.as index 8f97612..a4507d2 100644 --- a/src/com/dreamsocket/tracking/js/JSMethodCall.as +++ b/src/com/dreamsocket/tracking/js/JSMethodCall.as @@ -1,34 +1,42 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.js -{ - public class JSMethodCall - { - public var method:String; - public var arguments:Array; - - public function JSMethodCall(p_method:String = null, p_arguments:Array = null) - { - this.method = p_method; - this.arguments = p_arguments == null ? [] : p_arguments; - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.js +{ + public class JSMethodCall + { + public var method:String; + public var arguments:Array; + + public function JSMethodCall(p_method:String = null, p_arguments:Array = null) + { + this.method = p_method; + this.arguments = p_arguments == null ? [] : p_arguments; + } + } +} diff --git a/src/com/dreamsocket/tracking/js/JSTrackHandler.as b/src/com/dreamsocket/tracking/js/JSTrackHandler.as index a893795..d87c32d 100644 --- a/src/com/dreamsocket/tracking/js/JSTrackHandler.as +++ b/src/com/dreamsocket/tracking/js/JSTrackHandler.as @@ -1,35 +1,43 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.js -{ - - public class JSTrackHandler - { - public var ID:String; - public var methodCalls:Array; - - public function JSTrackHandler(p_ID:String = null, p_methodCalls:Array = null) - { - this.ID = p_ID; - this.methodCalls = p_methodCalls == null ? [] : p_methodCalls; - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.js +{ + + public class JSTrackHandler + { + public var ID:String; + public var methodCalls:Array; + + public function JSTrackHandler(p_ID:String = null, p_methodCalls:Array = null) + { + this.ID = p_ID; + this.methodCalls = p_methodCalls == null ? [] : p_methodCalls; + } + } +} diff --git a/src/com/dreamsocket/tracking/js/JSTracker.as b/src/com/dreamsocket/tracking/js/JSTracker.as index cc9ee25..3593a72 100644 --- a/src/com/dreamsocket/tracking/js/JSTracker.as +++ b/src/com/dreamsocket/tracking/js/JSTracker.as @@ -1,146 +1,154 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.js -{ - import flash.external.ExternalInterface; - import flash.utils.Dictionary; - - import com.dreamsocket.utils.PropertyStringUtil; - import com.dreamsocket.tracking.ITrack; - import com.dreamsocket.tracking.ITracker; - import com.dreamsocket.tracking.js.JSTrackerConfig; - import com.dreamsocket.tracking.js.JSTrackHandler; - - - public class JSTracker implements ITracker - { - public static const ID:String = "JSTracker"; - - - protected var m_config:JSTrackerConfig; - protected var m_enabled:Boolean; - protected var m_trackHandlers:Dictionary; - - - public function JSTracker() - { - super(); - - this.m_config = new JSTrackerConfig(); - this.m_enabled = true; - this.m_trackHandlers = new Dictionary(); - } - - - public function get config():JSTrackerConfig - { - return this.m_config; - } - - - public function set config(p_value:JSTrackerConfig):void - { - if(p_value != this.m_config) - { - this.m_config = p_value; - this.m_enabled = p_value.enabled; - this.m_trackHandlers = p_value.trackHandlers; - } - } - - - public function get enabled():Boolean - { - return this.m_enabled; - } - - - public function set enabled(p_enabled:Boolean):void - { - this.m_enabled = p_enabled; - } - - - public function addTrackHandler(p_ID:String, p_trackHandler:JSTrackHandler):void - { - this.m_trackHandlers[p_ID] = p_trackHandler; - } - - - public function getTrackHandler(p_ID:String):JSTrackHandler - { - return this.m_trackHandlers[p_ID] as JSTrackHandler; - } - - - public function removeTrackHandler(p_ID:String):void - { - delete(this.m_trackHandlers[p_ID]); - } - - - public function track(p_track:ITrack):void - { - if(!this.m_enabled) return; - - var handler:JSTrackHandler = this.m_trackHandlers[p_track.type]; - - if(handler != null) - { // has the track type - var methodCalls:Array = handler.methodCalls; - var i:int = 0; - var len:uint = methodCalls.length; - - while(i < len) - { - this.performJSCall(JSMethodCall(methodCalls[i]), p_track.data); - i++; - } - } - } - - protected function performJSCall(p_methodCall:JSMethodCall, p_data:* = null):void - { - ; - if(ExternalInterface.available) - { - try - { - var args:Array = p_methodCall.arguments.concat(); - var i:int = args.length; - - while(i--) - { - args[i] = PropertyStringUtil.evalPropertyString(p_data, args[i]); - } - - args.unshift(p_methodCall.method); - - ExternalInterface.call.apply(ExternalInterface, args); - } - catch(error:Error) - { // do nothing - trace("JSTracker.track - " + error); - } - } - } - } +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.js +{ + import flash.external.ExternalInterface; + import flash.utils.Dictionary; + + import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.tracking.ITracker; + import com.dreamsocket.tracking.js.JSTrackerConfig; + import com.dreamsocket.tracking.js.JSTrackHandler; + + + public class JSTracker implements ITracker + { + public static const ID:String = "JSTracker"; + + + protected var m_config:JSTrackerConfig; + protected var m_enabled:Boolean; + protected var m_trackHandlers:Dictionary; + + + public function JSTracker() + { + super(); + + this.m_config = new JSTrackerConfig(); + this.m_enabled = true; + this.m_trackHandlers = new Dictionary(); + } + + + public function get config():JSTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:JSTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + this.m_enabled = p_value.enabled; + this.m_trackHandlers = p_value.trackHandlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function addTrackHandler(p_ID:String, p_trackHandler:JSTrackHandler):void + { + this.m_trackHandlers[p_ID] = p_trackHandler; + } + + + public function getTrackHandler(p_ID:String):JSTrackHandler + { + return this.m_trackHandlers[p_ID] as JSTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_trackHandlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled) return; + + var handler:JSTrackHandler = this.m_trackHandlers[p_track.type]; + + if(handler != null) + { // has the track type + var methodCalls:Array = handler.methodCalls; + var i:int = 0; + var len:uint = methodCalls.length; + + while(i < len) + { + this.performJSCall(JSMethodCall(methodCalls[i]), p_track.data); + i++; + } + } + } + + protected function performJSCall(p_methodCall:JSMethodCall, p_data:* = null):void + { + ; + if(ExternalInterface.available) + { + try + { + var args:Array = p_methodCall.arguments.concat(); + var i:int = args.length; + + while(i--) + { + args[i] = PropertyStringUtil.evalPropertyString(p_data, args[i]); + } + + args.unshift(p_methodCall.method); + + ExternalInterface.call.apply(ExternalInterface, args); + } + catch(error:Error) + { // do nothing + trace("JSTracker.track - " + error); + } + } + } + } } \ No newline at end of file diff --git a/src/com/dreamsocket/tracking/js/JSTrackerConfig.as b/src/com/dreamsocket/tracking/js/JSTrackerConfig.as index 815d54a..719673d 100644 --- a/src/com/dreamsocket/tracking/js/JSTrackerConfig.as +++ b/src/com/dreamsocket/tracking/js/JSTrackerConfig.as @@ -1,37 +1,45 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.js -{ - import flash.utils.Dictionary; - - - public class JSTrackerConfig - { - public var enabled:Boolean; - public var trackHandlers:Dictionary; - - public function JSTrackerConfig() - { - this.enabled = true; - this.trackHandlers = new Dictionary(); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.js +{ + import flash.utils.Dictionary; + + + public class JSTrackerConfig + { + public var enabled:Boolean; + public var trackHandlers:Dictionary; + + public function JSTrackerConfig() + { + this.enabled = true; + this.trackHandlers = new Dictionary(); + } + } +} diff --git a/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as index 01c26d9..f2c026f 100644 --- a/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as @@ -1,81 +1,89 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.js -{ - import flash.utils.Dictionary; - - import com.dreamsocket.tracking.js.JSTrackerConfig; - import com.dreamsocket.tracking.js.JSTrackHandler; - - - public class JSTrackerConfigXMLDecoder - { - public function JSTrackerConfigXMLDecoder() - { - } - - - public function decode(p_xml:XML):JSTrackerConfig - { - var config:JSTrackerConfig = new JSTrackerConfig(); - var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; - var trackHandlerNode:XML; - var trackHandlers:Dictionary = config.trackHandlers; - - // trackHandlers - for each(trackHandlerNode in trackHandlerNodes) - { - this.addTrack(trackHandlers, trackHandlerNode); - } - // enabled - config.enabled = p_xml.enabled.toString() != "false"; - - return config; - } - - - protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void - { - var ID:String = p_trackHandlerNode.ID.toString(); - var methodCallNode:XML; - var handler:JSTrackHandler; - - if(ID.length > 0) - { - handler = new JSTrackHandler(); - for each(methodCallNode in p_trackHandlerNode.methodCalls.methodCall) - { - handler.methodCalls.push(this.createMethodCall(methodCallNode[0])); - } - p_trackHandlers[ID] = handler; - } - } - - protected function createMethodCall(p_methodNode:XML):JSMethodCall - { - var methodCall:JSMethodCall = new JSMethodCall(p_methodNode.ID.toString()); - var arguments:Array = p_methodNode.arguments.argument; - var argumentNode - for each() - methodCall.arguments - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.js +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.js.JSTrackerConfig; + import com.dreamsocket.tracking.js.JSTrackHandler; + + + public class JSTrackerConfigXMLDecoder + { + public function JSTrackerConfigXMLDecoder() + { + } + + + public function decode(p_xml:XML):JSTrackerConfig + { + var config:JSTrackerConfig = new JSTrackerConfig(); + var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; + var trackHandlerNode:XML; + var trackHandlers:Dictionary = config.trackHandlers; + + // trackHandlers + for each(trackHandlerNode in trackHandlerNodes) + { + this.addTrack(trackHandlers, trackHandlerNode); + } + // enabled + config.enabled = p_xml.enabled.toString() != "false"; + + return config; + } + + + protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void + { + var ID:String = p_trackHandlerNode.ID.toString(); + var methodCallNode:XML; + var handler:JSTrackHandler; + + if(ID.length > 0) + { + handler = new JSTrackHandler(); + for each(methodCallNode in p_trackHandlerNode.methodCalls.methodCall) + { + handler.methodCalls.push(this.createMethodCall(methodCallNode[0])); + } + p_trackHandlers[ID] = handler; + } + } + + protected function createMethodCall(p_methodNode:XML):JSMethodCall + { + var methodCall:JSMethodCall = new JSMethodCall(p_methodNode.ID.toString()); + var arguments:Array = p_methodNode.arguments.argument; + var argumentNode + for each() + methodCall.arguments + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureParams.as b/src/com/dreamsocket/tracking/omniture/OmnitureParams.as index d857433..559929b 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureParams.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureParams.as @@ -1,58 +1,67 @@ -/** - * Dreamsocket, Inc. - * - * Copyright 2009 Dreamsocket, Inc.. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket, Inc.. - * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under - * applicable law. - * - */ - - -package com.dreamsocket.tracking.omniture -{ - - public dynamic class OmnitureParams - { - // debug vars - public var debugTracking:Boolean; - public var trackLocal:Boolean; - - // required - public var account:String; - public var dc:String; - public var pageName:String; - public var pageURL:String; - public var visitorNameSpace:String; - - // optional - public var autoTrack:Boolean; - public var charSet:String; - public var cookieDomainPeriods:Number; - public var cookieLifetime:String; - public var currencyCode:String; - public var delayTracking:Number; - public var events:String; - public var linkLeaveQueryString:Boolean; - public var movieID:String; - public var pageType:String; - public var referrer:String; - public var trackClickMap:Boolean; - public var trackingServer:String; - public var trackingServerBase:String; - public var trackingServerSecure:String; - public var vmk:String; - - public function OmnitureParams() - { - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + + public dynamic class OmnitureParams + { + // debug vars + public var debugTracking:Boolean; + public var trackLocal:Boolean; + + // required + public var account:String; + public var dc:String; + public var pageName:String; + public var pageURL:String; + public var visitorNameSpace:String; + + // optional + public var autoTrack:Boolean; + public var charSet:String; + public var cookieDomainPeriods:Number; + public var cookieLifetime:String; + public var currencyCode:String; + public var delayTracking:Number; + public var events:String; + public var linkLeaveQueryString:Boolean; + public var movieID:String; + public var pageType:String; + public var referrer:String; + public var trackClickMap:Boolean; + public var trackingServer:String; + public var trackingServerBase:String; + public var trackingServerSecure:String; + public var vmk:String; + + public function OmnitureParams() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as b/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as index 66b3bf4..0a25915 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as @@ -1,101 +1,109 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.omniture -{ - import com.dreamsocket.tracking.omniture.OmnitureParams; - - - public class OmnitureParamsXMLDecoder - { - protected var m_params:OmnitureParams; - - - public function OmnitureParamsXMLDecoder() - { - } - - - public function decode(p_paramNodes:XML):OmnitureParams - { - var params:OmnitureParams = new OmnitureParams(); - - if(p_paramNodes == null) return params; - // debug - if(p_paramNodes.debugTracking.toString().length) - params.debugTracking = p_paramNodes.debugTracking.toString() == "true"; - if(p_paramNodes.trackLocal.toString().length) - params.trackLocal = p_paramNodes.trackLocal.toString() == "true"; - - // required - if(p_paramNodes.account.toString().length) - params.account = p_paramNodes.account.toString(); - if(p_paramNodes.dc.toString().length) - params.dc = p_paramNodes.dc.toString(); - if(p_paramNodes.pageName.toString().length) - params.pageName = p_paramNodes.pageName.toString(); - if(p_paramNodes.pageURL.toString().length) - params.pageURL = p_paramNodes.pageURL.toString(); - if(p_paramNodes.visitorNameSpace.toString().length) - params.visitorNameSpace = p_paramNodes.visitorNameSpace.toString(); - - // optional - if(p_paramNodes.autoTrack.length()) - params.autoTrack = p_paramNodes.autoTrack.toString() == "true"; - if(p_paramNodes.charSet.length()) - params.charSet = p_paramNodes.charSet.toString(); - if(p_paramNodes.cookieDomainPeriods.length()) - params.cookieDomainPeriods = int(p_paramNodes.cookieDomainPeriods.toString()); - if(p_paramNodes.cookieLifetime.length()) - params.cookieLifetime = p_paramNodes.cookieLifetime.toString(); - if(p_paramNodes.currencyCode.length()) - params.currencyCode = p_paramNodes.currencyCode.toString(); - if(p_paramNodes.delayTracking.length()) - params.delayTracking = Number(p_paramNodes.delayTracking.toString()); - if(p_paramNodes.linkLeaveQueryString.length()) - params.linkLeaveQueryString = p_paramNodes.linkLeaveQueryString.toString() == true; - if(p_paramNodes.pageType.length()) - params.pageType = p_paramNodes.pageType.toString(); - if(p_paramNodes.referrer.length()) - params.referrer = p_paramNodes.referrer.toString(); - if(p_paramNodes.trackClickMap.length()) - params.trackClickMap = p_paramNodes.trackClickMap.toString() == "true"; - if(p_paramNodes.trackingServer.length()) - params.trackingServer = p_paramNodes.trackingServer.toString(); - if(p_paramNodes.trackingServerBase.length()) - params.trackingServerBase = p_paramNodes.trackingServerBase.toString(); - if(p_paramNodes.trackingServerSecure.length()) - params.trackingServerSecure = p_paramNodes.trackingServerSecure.toString(); - if(p_paramNodes.vmk.length()) - params.vmk = p_paramNodes.vmk.toString(); - - var paramNode:XML; - for each(paramNode in p_paramNodes.*) - { - if(params[paramNode.name()] == undefined) - { - params[paramNode.name()] = paramNode.toString(); - } - } - - return params; - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + import com.dreamsocket.tracking.omniture.OmnitureParams; + + + public class OmnitureParamsXMLDecoder + { + protected var m_params:OmnitureParams; + + + public function OmnitureParamsXMLDecoder() + { + } + + + public function decode(p_paramNodes:XML):OmnitureParams + { + var params:OmnitureParams = new OmnitureParams(); + + if(p_paramNodes == null) return params; + // debug + if(p_paramNodes.debugTracking.toString().length) + params.debugTracking = p_paramNodes.debugTracking.toString() == "true"; + if(p_paramNodes.trackLocal.toString().length) + params.trackLocal = p_paramNodes.trackLocal.toString() == "true"; + + // required + if(p_paramNodes.account.toString().length) + params.account = p_paramNodes.account.toString(); + if(p_paramNodes.dc.toString().length) + params.dc = p_paramNodes.dc.toString(); + if(p_paramNodes.pageName.toString().length) + params.pageName = p_paramNodes.pageName.toString(); + if(p_paramNodes.pageURL.toString().length) + params.pageURL = p_paramNodes.pageURL.toString(); + if(p_paramNodes.visitorNameSpace.toString().length) + params.visitorNameSpace = p_paramNodes.visitorNameSpace.toString(); + + // optional + if(p_paramNodes.autoTrack.length()) + params.autoTrack = p_paramNodes.autoTrack.toString() == "true"; + if(p_paramNodes.charSet.length()) + params.charSet = p_paramNodes.charSet.toString(); + if(p_paramNodes.cookieDomainPeriods.length()) + params.cookieDomainPeriods = int(p_paramNodes.cookieDomainPeriods.toString()); + if(p_paramNodes.cookieLifetime.length()) + params.cookieLifetime = p_paramNodes.cookieLifetime.toString(); + if(p_paramNodes.currencyCode.length()) + params.currencyCode = p_paramNodes.currencyCode.toString(); + if(p_paramNodes.delayTracking.length()) + params.delayTracking = Number(p_paramNodes.delayTracking.toString()); + if(p_paramNodes.linkLeaveQueryString.length()) + params.linkLeaveQueryString = p_paramNodes.linkLeaveQueryString.toString() == true; + if(p_paramNodes.pageType.length()) + params.pageType = p_paramNodes.pageType.toString(); + if(p_paramNodes.referrer.length()) + params.referrer = p_paramNodes.referrer.toString(); + if(p_paramNodes.trackClickMap.length()) + params.trackClickMap = p_paramNodes.trackClickMap.toString() == "true"; + if(p_paramNodes.trackingServer.length()) + params.trackingServer = p_paramNodes.trackingServer.toString(); + if(p_paramNodes.trackingServerBase.length()) + params.trackingServerBase = p_paramNodes.trackingServerBase.toString(); + if(p_paramNodes.trackingServerSecure.length()) + params.trackingServerSecure = p_paramNodes.trackingServerSecure.toString(); + if(p_paramNodes.vmk.length()) + params.vmk = p_paramNodes.vmk.toString(); + + var paramNode:XML; + for each(paramNode in p_paramNodes.*) + { + if(params[paramNode.name()] == undefined) + { + params[paramNode.name()] = paramNode.toString(); + } + } + + return params; + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureService.as b/src/com/dreamsocket/tracking/omniture/OmnitureService.as index 1854941..1191668 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureService.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureService.as @@ -1,248 +1,257 @@ -/** - * Dreamsocket, Inc. - * - * Copyright 2009 Dreamsocket, Inc.. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket, Inc.. - * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under - * applicable law. - * - */ - - -package com.dreamsocket.tracking.omniture -{ - import flash.display.DisplayObjectContainer; - import flash.utils.describeType; - - import com.dreamsocket.tracking.omniture.OmnitureParams; - - import com.omniture.ActionSource; - - - public class OmnitureService - { - public static var display:DisplayObjectContainer; - - protected var m_config:OmnitureParams; - protected var m_display:DisplayObjectContainer; - protected var m_enabled:Boolean; - protected var m_lastTrackParams:OmnitureParams; - protected var m_tracker:ActionSource; - - - public function OmnitureService(p_display:DisplayObjectContainer = null) - { - this.m_display = p_display; - this.m_enabled = true; - } - - - public function get config():OmnitureParams - { - return this.m_config; - } - - - public function set config(p_config:OmnitureParams):void - { - if(p_config != this.m_config) - { - this.m_config = p_config; - this.reset(); - this.mergeParams(p_config, this.m_tracker); - } - } - - - public function get enabled():Boolean - { - return this.m_enabled; - } - - - public function set enabled(p_enabled:Boolean):void - { - this.m_enabled = p_enabled; - } - - - public function destroy():void - { - if(this.m_tracker != null && this.m_display != null && this.m_display.contains(this.m_tracker)) - { - this.m_display.removeChild(this.m_tracker); - } - this.m_tracker = null; - this.m_config = null; - this.m_display = null; - this.m_lastTrackParams = null; - OmnitureService.display = null; - } - - - public function track(p_params:OmnitureParams):void - { - if(!this.m_enabled) return; - - this.resetTrackParams(); - this.m_lastTrackParams = p_params; - this.mergeParams(p_params, this.m_tracker); - - try - { - this.m_tracker.track(); - } - catch(error:Error) - { - trace(error); - } - } - - - public function trackLink(p_params:OmnitureParams, p_URL:String, p_type:String, p_name:String):void - { - if(!this.m_enabled) return; - - this.resetTrackParams(); - this.m_lastTrackParams = p_params; - this.mergeParams(p_params, this.m_tracker); - - try - { - this.m_tracker.trackLink(p_URL, p_type, p_name); - } - catch(error:Error) - { - trace(error); - } - } - - - protected function mergeParams(p_params:OmnitureParams, p_destination:Object):void - { - var desc:XML = describeType(p_params); - var propNode:XML; - var props:XMLList = desc..variable; - var type:String; - var name:String; - var val:*; - - // instance props - for each(propNode in props) - { - name = propNode.@name; - type = propNode.@type; - val = p_params[name]; - if(val is String && val != null) - { - p_destination[name] = val; - } - else if(val is Number && !isNaN(val)) - { - p_destination[name] = val; - } - else if(val is Boolean && val) - { - p_destination[name] = val; - } - } - - // dynamic props - for(name in p_params) - { - val = p_params[name]; - if(val is String && val != null) - { - p_destination[name] = val; - } - else if(val is Number && !isNaN(val)) - { - p_destination[name] = val; - } - else if(val is Boolean && val) - { - p_destination[name] = val; - } - } - } - - - protected function reset():void - { - if(this.m_config == null) return; - - this.m_display = this.m_display == null ? OmnitureService.display : this.m_display; - - if(this.m_tracker != null && this.m_display != null && this.m_display.contains(this.m_tracker)) - { - this.m_display.removeChild(this.m_tracker); - } - this.m_tracker = new ActionSource(); - if(this.m_tracker != null && this.m_display != null) - { - this.m_display.addChild(this.m_tracker); - } - } - - - protected function resetTrackParams():void - { - if(this.m_lastTrackParams == null) return; - - var params:OmnitureParams = this.m_config; - var desc:XML = describeType(this.m_lastTrackParams); - var propNode:XML; - var props:XMLList = desc..variable; - var type:String; - var name:String; - var val:*; - - // instance props - for each(propNode in props) - { - name = propNode.@name; - type = propNode.@type; - - val = this.m_lastTrackParams[name]; - if(val is String && val != null) - { - this.m_tracker[name] = params[name]; - } - else if(val is Number && !isNaN(val)) - { - this.m_tracker[name] = params[name]; - } - else if(val is Boolean && val) - { - this.m_tracker[name] = params[name]; - } - } - - // dynamic props - for(name in this.m_lastTrackParams) - { - val = this.m_lastTrackParams[name]; - if(val is String && val != null) - { - this.m_tracker[name] = params[name]; - } - else if(val is Number && !isNaN(val)) - { - this.m_tracker[name] = params[name]; - } - else if(val is Boolean && val) - { - this.m_tracker[name] = params[name]; - } - } - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + import flash.display.DisplayObjectContainer; + import flash.utils.describeType; + + import com.dreamsocket.tracking.omniture.OmnitureParams; + + import com.omniture.ActionSource; + + + public class OmnitureService + { + public static var display:DisplayObjectContainer; + + protected var m_config:OmnitureParams; + protected var m_display:DisplayObjectContainer; + protected var m_enabled:Boolean; + protected var m_lastTrackParams:OmnitureParams; + protected var m_tracker:ActionSource; + + + public function OmnitureService(p_display:DisplayObjectContainer = null) + { + this.m_display = p_display; + this.m_enabled = true; + } + + + public function get config():OmnitureParams + { + return this.m_config; + } + + + public function set config(p_config:OmnitureParams):void + { + if(p_config != this.m_config) + { + this.m_config = p_config; + this.reset(); + this.mergeParams(p_config, this.m_tracker); + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function destroy():void + { + if(this.m_tracker != null && this.m_display != null && this.m_display.contains(this.m_tracker)) + { + this.m_display.removeChild(this.m_tracker); + } + this.m_tracker = null; + this.m_config = null; + this.m_display = null; + this.m_lastTrackParams = null; + OmnitureService.display = null; + } + + + public function track(p_params:OmnitureParams):void + { + if(!this.m_enabled) return; + + this.resetTrackParams(); + this.m_lastTrackParams = p_params; + this.mergeParams(p_params, this.m_tracker); + + try + { + this.m_tracker.track(); + } + catch(error:Error) + { + trace(error); + } + } + + + public function trackLink(p_params:OmnitureParams, p_URL:String, p_type:String, p_name:String):void + { + if(!this.m_enabled) return; + + this.resetTrackParams(); + this.m_lastTrackParams = p_params; + this.mergeParams(p_params, this.m_tracker); + + try + { + this.m_tracker.trackLink(p_URL, p_type, p_name); + } + catch(error:Error) + { + trace(error); + } + } + + + protected function mergeParams(p_params:OmnitureParams, p_destination:Object):void + { + var desc:XML = describeType(p_params); + var propNode:XML; + var props:XMLList = desc..variable; + var type:String; + var name:String; + var val:*; + + // instance props + for each(propNode in props) + { + name = propNode.@name; + type = propNode.@type; + val = p_params[name]; + if(val is String && val != null) + { + p_destination[name] = val; + } + else if(val is Number && !isNaN(val)) + { + p_destination[name] = val; + } + else if(val is Boolean && val) + { + p_destination[name] = val; + } + } + + // dynamic props + for(name in p_params) + { + val = p_params[name]; + if(val is String && val != null) + { + p_destination[name] = val; + } + else if(val is Number && !isNaN(val)) + { + p_destination[name] = val; + } + else if(val is Boolean && val) + { + p_destination[name] = val; + } + } + } + + + protected function reset():void + { + if(this.m_config == null) return; + + this.m_display = this.m_display == null ? OmnitureService.display : this.m_display; + + if(this.m_tracker != null && this.m_display != null && this.m_display.contains(this.m_tracker)) + { + this.m_display.removeChild(this.m_tracker); + } + this.m_tracker = new ActionSource(); + if(this.m_tracker != null && this.m_display != null) + { + this.m_display.addChild(this.m_tracker); + } + } + + + protected function resetTrackParams():void + { + if(this.m_lastTrackParams == null) return; + + var params:OmnitureParams = this.m_config; + var desc:XML = describeType(this.m_lastTrackParams); + var propNode:XML; + var props:XMLList = desc..variable; + var type:String; + var name:String; + var val:*; + + // instance props + for each(propNode in props) + { + name = propNode.@name; + type = propNode.@type; + + val = this.m_lastTrackParams[name]; + if(val is String && val != null) + { + this.m_tracker[name] = params[name]; + } + else if(val is Number && !isNaN(val)) + { + this.m_tracker[name] = params[name]; + } + else if(val is Boolean && val) + { + this.m_tracker[name] = params[name]; + } + } + + // dynamic props + for(name in this.m_lastTrackParams) + { + val = this.m_lastTrackParams[name]; + if(val is String && val != null) + { + this.m_tracker[name] = params[name]; + } + else if(val is Number && !isNaN(val)) + { + this.m_tracker[name] = params[name]; + } + else if(val is Boolean && val) + { + this.m_tracker[name] = params[name]; + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as index 28cf867..8417246 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as @@ -1,33 +1,41 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.omniture -{ - - public class OmnitureTrackHandler - { - public var ID:String; - public var request:Object; - - public function OmnitureTrackHandler() - { - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + + public class OmnitureTrackHandler + { + public var ID:String; + public var request:Object; + + public function OmnitureTrackHandler() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as index debc3fa..d5330b8 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as @@ -1,35 +1,43 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.omniture -{ - public class OmnitureTrackLinkRequest - { - public var name:String; - public var params:OmnitureParams; - public var type:String; - public var URL:String; - - public function OmnitureTrackLinkRequest() - { - this.params = new OmnitureParams(); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + public class OmnitureTrackLinkRequest + { + public var name:String; + public var params:OmnitureParams; + public var type:String; + public var URL:String; + + public function OmnitureTrackLinkRequest() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as index 8b336b8..465a854 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as @@ -1,32 +1,40 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.omniture -{ - public class OmnitureTrackRequest - { - public var params:OmnitureParams; - - public function OmnitureTrackRequest() - { - this.params = new OmnitureParams(); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + public class OmnitureTrackRequest + { + public var params:OmnitureParams; + + public function OmnitureTrackRequest() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as b/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as index 29a1bab..35f6826 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as @@ -1,161 +1,169 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.omniture -{ - import flash.display.DisplayObjectContainer; - import flash.utils.describeType; - import flash.utils.Dictionary; - - import com.dreamsocket.utils.PropertyStringUtil; - import com.dreamsocket.tracking.ITrack; - import com.dreamsocket.tracking.ITracker; - import com.dreamsocket.tracking.omniture.OmnitureService; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; - import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; - import com.dreamsocket.tracking.omniture.OmnitureTrackRequest; - import com.dreamsocket.tracking.omniture.OmnitureTrackLinkRequest; - - - public class OmnitureTracker implements ITracker - { - public static var display:DisplayObjectContainer; - public static const ID:String = "OmnitureTracker"; - - protected var m_config:OmnitureTrackerConfig; - protected var m_enabled:Boolean; - protected var m_service:OmnitureService; - protected var m_trackHandlers:Dictionary; - - public function OmnitureTracker(p_display:DisplayObjectContainer = null) - { - super(); - - this.m_enabled = true; - this.m_service = new OmnitureService(p_display == null ? OmnitureTracker.display : p_display); - this.m_trackHandlers = new Dictionary(); - } - - - public function get config():OmnitureTrackerConfig - { - return this.m_config; - } - - - public function set config(p_value:OmnitureTrackerConfig):void - { - if(p_value != this.m_config) - { - this.m_config = p_value; - this.m_service.config = p_value.params; - this.m_enabled = p_value.enabled; - this.m_trackHandlers = p_value.trackHandlers; - } - } - - - public function get enabled():Boolean - { - return this.m_enabled; - } - - - public function set enabled(p_enabled:Boolean):void - { - this.m_enabled = p_enabled; - } - - - public function addTrackHandler(p_ID:String, p_trackHandler:OmnitureTrackHandler):void - { - this.m_trackHandlers[p_ID] = p_trackHandler; - } - - - public function getTrackHandler(p_ID:String):OmnitureTrackHandler - { - return this.m_trackHandlers[p_ID] as OmnitureTrackHandler; - } - - - public function removeTrackHandler(p_ID:String):void - { - delete(this.m_trackHandlers[p_ID]); - } - - - public function track(p_track:ITrack):void - { - if(!this.m_enabled) return; - - var handler:OmnitureTrackHandler = this.m_config.trackHandlers[p_track.type]; - - - if(handler != null && handler.request != null) - { // has a track handler - var requestParams:OmnitureParams = new OmnitureParams(); - var handlerParams:OmnitureParams; - - if(handler.request.params != null && handler.request.params is OmnitureParams) - { - handlerParams = handler.request.params; - - var desc:XML = describeType(handlerParams); - var propNode:XML; - var props:XMLList = desc..variable; - var prop:String; - var val:*; - - // instance props - for each(propNode in props) - { - prop = propNode.@name; - val = handlerParams[prop]; - if(val is String && val != null) - { - requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, val); - } - } - // dynamic prop - for(prop in handlerParams) - { - requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, handlerParams[prop]); - } - } - - - // call correct track method - if(handler.request is OmnitureTrackLinkRequest) - { - var URL:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.URL); - var type:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.type); - var name:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.name); - - this.m_service.trackLink(requestParams, URL, type, name); - } - else if(handler.request is OmnitureTrackRequest) - { - this.m_service.track(requestParams); - } - } - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + import flash.display.DisplayObjectContainer; + import flash.utils.describeType; + import flash.utils.Dictionary; + + import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.tracking.ITracker; + import com.dreamsocket.tracking.omniture.OmnitureService; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; + import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; + import com.dreamsocket.tracking.omniture.OmnitureTrackRequest; + import com.dreamsocket.tracking.omniture.OmnitureTrackLinkRequest; + + + public class OmnitureTracker implements ITracker + { + public static var display:DisplayObjectContainer; + public static const ID:String = "OmnitureTracker"; + + protected var m_config:OmnitureTrackerConfig; + protected var m_enabled:Boolean; + protected var m_service:OmnitureService; + protected var m_trackHandlers:Dictionary; + + public function OmnitureTracker(p_display:DisplayObjectContainer = null) + { + super(); + + this.m_enabled = true; + this.m_service = new OmnitureService(p_display == null ? OmnitureTracker.display : p_display); + this.m_trackHandlers = new Dictionary(); + } + + + public function get config():OmnitureTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:OmnitureTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + this.m_service.config = p_value.params; + this.m_enabled = p_value.enabled; + this.m_trackHandlers = p_value.trackHandlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function addTrackHandler(p_ID:String, p_trackHandler:OmnitureTrackHandler):void + { + this.m_trackHandlers[p_ID] = p_trackHandler; + } + + + public function getTrackHandler(p_ID:String):OmnitureTrackHandler + { + return this.m_trackHandlers[p_ID] as OmnitureTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_trackHandlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled) return; + + var handler:OmnitureTrackHandler = this.m_config.trackHandlers[p_track.type]; + + + if(handler != null && handler.request != null) + { // has a track handler + var requestParams:OmnitureParams = new OmnitureParams(); + var handlerParams:OmnitureParams; + + if(handler.request.params != null && handler.request.params is OmnitureParams) + { + handlerParams = handler.request.params; + + var desc:XML = describeType(handlerParams); + var propNode:XML; + var props:XMLList = desc..variable; + var prop:String; + var val:*; + + // instance props + for each(propNode in props) + { + prop = propNode.@name; + val = handlerParams[prop]; + if(val is String && val != null) + { + requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, val); + } + } + // dynamic prop + for(prop in handlerParams) + { + requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, handlerParams[prop]); + } + } + + + // call correct track method + if(handler.request is OmnitureTrackLinkRequest) + { + var URL:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.URL); + var type:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.type); + var name:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.name); + + this.m_service.trackLink(requestParams, URL, type, name); + } + else if(handler.request is OmnitureTrackRequest) + { + this.m_service.track(requestParams); + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as index 348c05b..27f0e53 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as @@ -1,38 +1,47 @@ -/** - * Dreamsocket, Inc. - * - * Copyright 2009 Dreamsocket, Inc.. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket, Inc.. - * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under - * applicable law. - * - */ - - -package com.dreamsocket.tracking.omniture -{ - import flash.utils.Dictionary; - - - public class OmnitureTrackerConfig - { - public var enabled:Boolean; - public var params:OmnitureParams; - public var trackHandlers:Dictionary; - - public function OmnitureTrackerConfig() - { - this.enabled = true; - this.params = new OmnitureParams(); - this.trackHandlers = new Dictionary(); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + import flash.utils.Dictionary; + + + public class OmnitureTrackerConfig + { + public var enabled:Boolean; + public var params:OmnitureParams; + public var trackHandlers:Dictionary; + + public function OmnitureTrackerConfig() + { + this.enabled = true; + this.params = new OmnitureParams(); + this.trackHandlers = new Dictionary(); + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as index 9984541..6994a52 100644 --- a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as @@ -1,94 +1,103 @@ -/** - * Dreamsocket, Inc. - * - * Copyright 2009 Dreamsocket, Inc.. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket, Inc.. - * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under - * applicable law. - * - */ - - -package com.dreamsocket.tracking.omniture -{ - import flash.utils.Dictionary; - - import com.dreamsocket.tracking.omniture.OmnitureParamsXMLDecoder; - import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; - import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; - - - public class OmnitureTrackerConfigXMLDecoder - { - public function OmnitureTrackerConfigXMLDecoder() - { - } - - - public function decode(p_xml:XML):OmnitureTrackerConfig - { - var config:OmnitureTrackerConfig = new OmnitureTrackerConfig(); - - config.enabled = p_xml.enabled.toString() != "false"; - config.params = new OmnitureParamsXMLDecoder().decode(p_xml.params[0]); - this.setTrackHandlers(config.trackHandlers, p_xml.trackHandlers.trackHandler); - - return config; - } - - - public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void - { - var handler:OmnitureTrackHandler; - var handlerNode:XML; - var ID:String; - var trackLinkRequest:OmnitureTrackLinkRequest; - var trackRequest:OmnitureTrackRequest; - var paramsDecoder:OmnitureParamsXMLDecoder = new OmnitureParamsXMLDecoder(); - var trackNode:XML; - for each(handlerNode in p_handlerNodes) - { - ID = handlerNode.ID.toString(); - if(ID.length > 0) - { - if(handlerNode.trackLink.toString().length) - { // decode trackLink - handler = new OmnitureTrackHandler(); - handler.ID = ID; - handler.request = trackLinkRequest = new OmnitureTrackLinkRequest(); - trackNode = handlerNode.trackLink[0]; - - if(trackNode.name.toString().length) - trackLinkRequest.name = trackNode.name.toString(); - if(trackNode.type.toString().length) - trackLinkRequest.type = trackNode.type.toString(); - if(trackNode.URL.toString().length) - trackLinkRequest.URL = trackNode.URL.toString(); - - trackLinkRequest.params = paramsDecoder.decode(trackNode.params[0]); - - p_handlers[ID] = handler; - } - else if(handlerNode.track.toString().length) - { // decode track - handler = new OmnitureTrackHandler(); - handler.ID = ID; - handler.request = trackRequest = new OmnitureTrackRequest(); - trackNode = handlerNode.track[0]; - trackRequest.params = paramsDecoder.decode(trackNode.params[0]); - - p_handlers[ID] = handler; - } - } - } - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.omniture +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.omniture.OmnitureParamsXMLDecoder; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; + import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; + + + public class OmnitureTrackerConfigXMLDecoder + { + public function OmnitureTrackerConfigXMLDecoder() + { + } + + + public function decode(p_xml:XML):OmnitureTrackerConfig + { + var config:OmnitureTrackerConfig = new OmnitureTrackerConfig(); + + config.enabled = p_xml.enabled.toString() != "false"; + config.params = new OmnitureParamsXMLDecoder().decode(p_xml.params[0]); + this.setTrackHandlers(config.trackHandlers, p_xml.trackHandlers.trackHandler); + + return config; + } + + + public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void + { + var handler:OmnitureTrackHandler; + var handlerNode:XML; + var ID:String; + var trackLinkRequest:OmnitureTrackLinkRequest; + var trackRequest:OmnitureTrackRequest; + var paramsDecoder:OmnitureParamsXMLDecoder = new OmnitureParamsXMLDecoder(); + var trackNode:XML; + for each(handlerNode in p_handlerNodes) + { + ID = handlerNode.ID.toString(); + if(ID.length > 0) + { + if(handlerNode.trackLink.toString().length) + { // decode trackLink + handler = new OmnitureTrackHandler(); + handler.ID = ID; + handler.request = trackLinkRequest = new OmnitureTrackLinkRequest(); + trackNode = handlerNode.trackLink[0]; + + if(trackNode.name.toString().length) + trackLinkRequest.name = trackNode.name.toString(); + if(trackNode.type.toString().length) + trackLinkRequest.type = trackNode.type.toString(); + if(trackNode.URL.toString().length) + trackLinkRequest.URL = trackNode.URL.toString(); + + trackLinkRequest.params = paramsDecoder.decode(trackNode.params[0]); + + p_handlers[ID] = handler; + } + else if(handlerNode.track.toString().length) + { // decode track + handler = new OmnitureTrackHandler(); + handler.ID = ID; + handler.request = trackRequest = new OmnitureTrackRequest(); + trackNode = handlerNode.track[0]; + trackRequest.params = paramsDecoder.decode(trackNode.params[0]); + + p_handlers[ID] = handler; + } + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/url/URLTrackHandler.as b/src/com/dreamsocket/tracking/url/URLTrackHandler.as index 73ad9b2..49d22e3 100644 --- a/src/com/dreamsocket/tracking/url/URLTrackHandler.as +++ b/src/com/dreamsocket/tracking/url/URLTrackHandler.as @@ -1,35 +1,43 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.url -{ - - public class URLTrackHandler - { - public var ID:String; - public var URLs:Array; - - public function URLTrackHandler(p_ID:String = null, p_URLs:Array = null) - { - this.ID = p_ID; - this.URLs = p_URLs == null ? [] : p_URLs; - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.url +{ + + public class URLTrackHandler + { + public var ID:String; + public var URLs:Array; + + public function URLTrackHandler(p_ID:String = null, p_URLs:Array = null) + { + this.ID = p_ID; + this.URLs = p_URLs == null ? [] : p_URLs; + } + } +} diff --git a/src/com/dreamsocket/tracking/url/URLTracker.as b/src/com/dreamsocket/tracking/url/URLTracker.as index ed8f5c0..1786284 100644 --- a/src/com/dreamsocket/tracking/url/URLTracker.as +++ b/src/com/dreamsocket/tracking/url/URLTracker.as @@ -1,118 +1,126 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.url -{ - import flash.utils.Dictionary; - - import com.dreamsocket.utils.PropertyStringUtil; - import com.dreamsocket.tracking.ITrack; - import com.dreamsocket.tracking.ITracker; - import com.dreamsocket.tracking.url.URLTrackerConfig; - import com.dreamsocket.tracking.url.URLTrackHandler; - import com.dreamsocket.utils.HTTPUtil; - - - public class URLTracker implements ITracker - { - public static const ID:String = "URLTracker"; - - - protected var m_config:URLTrackerConfig; - protected var m_enabled:Boolean; - protected var m_trackHandlers:Dictionary; - - - public function URLTracker() - { - super(); - - this.m_config = new URLTrackerConfig(); - this.m_enabled = true; - this.m_trackHandlers = new Dictionary(); - } - - - public function get config():URLTrackerConfig - { - return this.m_config; - } - - - public function set config(p_value:URLTrackerConfig):void - { - if(p_value != this.m_config) - { - this.m_config = p_value; - this.m_enabled = p_value.enabled; - this.m_trackHandlers = p_value.trackHandlers; - } - } - - - public function get enabled():Boolean - { - return this.m_enabled; - } - - - public function set enabled(p_enabled:Boolean):void - { - this.m_enabled = p_enabled; - } - - - public function addTrackHandler(p_ID:String, p_trackHandler:URLTrackHandler):void - { - this.m_trackHandlers[p_ID] = p_trackHandler; - } - - - public function getTrackHandler(p_ID:String):URLTrackHandler - { - return this.m_trackHandlers[p_ID] as URLTrackHandler; - } - - - public function removeTrackHandler(p_ID:String):void - { - delete(this.m_trackHandlers[p_ID]); - } - - - public function track(p_track:ITrack):void - { - if(!this.m_enabled) return; - - var handler:URLTrackHandler = this.m_trackHandlers[p_track.type]; - - if(handler != null) - { // has the track type - var URLs:Array = handler.URLs; - var i:uint = URLs.length; - - while(i--) - { - HTTPUtil.pingURL(PropertyStringUtil.evalPropertyString(p_track.data, URLs[i])); - } - } - } - } +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.url +{ + import flash.utils.Dictionary; + + import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.tracking.ITracker; + import com.dreamsocket.tracking.url.URLTrackerConfig; + import com.dreamsocket.tracking.url.URLTrackHandler; + import com.dreamsocket.utils.HTTPUtil; + + + public class URLTracker implements ITracker + { + public static const ID:String = "URLTracker"; + + + protected var m_config:URLTrackerConfig; + protected var m_enabled:Boolean; + protected var m_trackHandlers:Dictionary; + + + public function URLTracker() + { + super(); + + this.m_config = new URLTrackerConfig(); + this.m_enabled = true; + this.m_trackHandlers = new Dictionary(); + } + + + public function get config():URLTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:URLTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + this.m_enabled = p_value.enabled; + this.m_trackHandlers = p_value.trackHandlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function addTrackHandler(p_ID:String, p_trackHandler:URLTrackHandler):void + { + this.m_trackHandlers[p_ID] = p_trackHandler; + } + + + public function getTrackHandler(p_ID:String):URLTrackHandler + { + return this.m_trackHandlers[p_ID] as URLTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_trackHandlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled) return; + + var handler:URLTrackHandler = this.m_trackHandlers[p_track.type]; + + if(handler != null) + { // has the track type + var URLs:Array = handler.URLs; + var i:uint = URLs.length; + + while(i--) + { + HTTPUtil.pingURL(PropertyStringUtil.evalPropertyString(p_track.data, URLs[i])); + } + } + } + } } \ No newline at end of file diff --git a/src/com/dreamsocket/tracking/url/URLTrackerConfig.as b/src/com/dreamsocket/tracking/url/URLTrackerConfig.as index e001bc6..0302dc4 100644 --- a/src/com/dreamsocket/tracking/url/URLTrackerConfig.as +++ b/src/com/dreamsocket/tracking/url/URLTrackerConfig.as @@ -1,37 +1,45 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.url -{ - import flash.utils.Dictionary; - - - public class URLTrackerConfig - { - public var enabled:Boolean; - public var trackHandlers:Dictionary; - - public function URLTrackerConfig() - { - this.enabled = true; - this.trackHandlers = new Dictionary(); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.url +{ + import flash.utils.Dictionary; + + + public class URLTrackerConfig + { + public var enabled:Boolean; + public var trackHandlers:Dictionary; + + public function URLTrackerConfig() + { + this.enabled = true; + this.trackHandlers = new Dictionary(); + } + } +} diff --git a/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as index e39207d..935d705 100644 --- a/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as +++ b/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as @@ -1,72 +1,80 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.tracking.url -{ - import flash.utils.Dictionary; - - import com.dreamsocket.tracking.url.URLTrackerConfig; - import com.dreamsocket.tracking.url.URLTrackHandler; - - - public class URLTrackerConfigXMLDecoder - { - public function URLTrackerConfigXMLDecoder() - { - } - - - public function decode(p_xml:XML):URLTrackerConfig - { - var config:URLTrackerConfig = new URLTrackerConfig(); - var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; - var trackHandlerNode:XML; - var trackHandlers:Dictionary = config.trackHandlers; - - // trackHandlers - for each(trackHandlerNode in trackHandlerNodes) - { - this.addTrack(trackHandlers, trackHandlerNode); - } - // enabled - config.enabled = p_xml.enabled.toString() != "false"; - - return config; - } - - - protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void - { - var ID:String = p_trackHandlerNode.ID.toString(); - var urlNode:XML; - var handler:URLTrackHandler; - - if(ID.length > 0) - { - handler = new URLTrackHandler(); - for each(urlNode in p_trackHandlerNode.URLs.URL) - { - handler.URLs.push(urlNode.toString()); - } - p_trackHandlers[ID] = handler; - } - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.tracking.url +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.url.URLTrackerConfig; + import com.dreamsocket.tracking.url.URLTrackHandler; + + + public class URLTrackerConfigXMLDecoder + { + public function URLTrackerConfigXMLDecoder() + { + } + + + public function decode(p_xml:XML):URLTrackerConfig + { + var config:URLTrackerConfig = new URLTrackerConfig(); + var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; + var trackHandlerNode:XML; + var trackHandlers:Dictionary = config.trackHandlers; + + // trackHandlers + for each(trackHandlerNode in trackHandlerNodes) + { + this.addTrack(trackHandlers, trackHandlerNode); + } + // enabled + config.enabled = p_xml.enabled.toString() != "false"; + + return config; + } + + + protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void + { + var ID:String = p_trackHandlerNode.ID.toString(); + var urlNode:XML; + var handler:URLTrackHandler; + + if(ID.length > 0) + { + handler = new URLTrackHandler(); + for each(urlNode in p_trackHandlerNode.URLs.URL) + { + handler.URLs.push(urlNode.toString()); + } + p_trackHandlers[ID] = handler; + } + } + } +} diff --git a/src/com/dreamsocket/utils/HTTPUtil.as b/src/com/dreamsocket/utils/HTTPUtil.as index 84e41e6..b35f4fa 100644 --- a/src/com/dreamsocket/utils/HTTPUtil.as +++ b/src/com/dreamsocket/utils/HTTPUtil.as @@ -1,111 +1,120 @@ -/** - * Dreamsocket - * - * Copyright 2007 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - -package com.dreamsocket.utils -{ - import flash.events.Event; - import flash.events.IOErrorEvent; - import flash.events.SecurityErrorEvent; - import flash.net.URLRequest; - import flash.net.URLLoader; - import flash.system.Security; - import flash.utils.Dictionary; - - public class HTTPUtil - { - public static var allowLocalQueryStrings:Boolean = false; - - protected static var k_pings:Dictionary = new Dictionary(); - - - public function HTTPUtil() - { - } - - - public static function pingURL(p_URL:String, p_clearCache:Boolean = true, p_rateInSecsToCache:Number = 0):void - { - if(p_URL == null) return; - - var loader:URLLoader = new URLLoader(); - var URL:String = p_URL; - - if(p_clearCache && (HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE)) - { - URL = HTTPUtil.resolveUniqueURL(p_URL, p_rateInSecsToCache); - } - - loader.load(new URLRequest(URL)); - loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); - loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); - loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); - - HTTPUtil.k_pings[loader] = true; - } - - - public static function addQueryParam(p_URL:String, p_name:String, p_val:String, p_delimeter:String = null):String - { - if(HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) - { - if(p_delimeter == null) - p_URL += (p_URL.indexOf( "?" ) != -1 ) ? "&" + p_name + "=" : "?" + p_name + "="; - else - p_URL += p_delimeter + p_name + "="; - p_URL += p_val != null ? escape(p_val) : ""; - } - return p_URL; - } - - - public static function resolveUniqueURL(p_URL:String, p_rateInSecsToCache:Number = 0):String - { - var request:String = p_URL; - - if((HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) && p_URL.indexOf( "&cacheID=" ) == -1 && p_URL.indexOf( "?cacheID=" ) == -1) - { - var d:Date = new Date(); - var ID:String; - var secsPassed:Number = (60 * d.getUTCMinutes()) + d.getUTCSeconds(); - - if(p_rateInSecsToCache == 0) - { - ID = String(d.valueOf()); - } - else - { - ID = d.getUTCFullYear() + "" + d.getUTCMonth() + "" +d.getUTCDate() + "" +d.getUTCHours() + "-" + Math.floor(secsPassed/p_rateInSecsToCache); - } - - request = HTTPUtil.addQueryParam(p_URL, "cacheID", ID); - } - - return request; - } - - - protected static function onPingResult(p_event:Event):void - { // NOTE: let errors be thrown or log them if you want to handle them - URLLoader(p_event.target).removeEventListener(Event.COMPLETE, HTTPUtil.onPingResult); - URLLoader(p_event.target).removeEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); - URLLoader(p_event.target).removeEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); - delete(HTTPUtil.k_pings[p_event.target]); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.utils +{ + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + import flash.system.Security; + import flash.utils.Dictionary; + + public class HTTPUtil + { + public static var allowLocalQueryStrings:Boolean = false; + + protected static var k_pings:Dictionary = new Dictionary(); + + + public function HTTPUtil() + { + } + + + public static function pingURL(p_URL:String, p_clearCache:Boolean = true, p_rateInSecsToCache:Number = 0):void + { + if(p_URL == null) return; + + var loader:URLLoader = new URLLoader(); + var URL:String = p_URL; + + if(p_clearCache && (HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE)) + { + URL = HTTPUtil.resolveUniqueURL(p_URL, p_rateInSecsToCache); + } + + loader.load(new URLRequest(URL)); + loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); + loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); + loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); + + HTTPUtil.k_pings[loader] = true; + } + + + public static function addQueryParam(p_URL:String, p_name:String, p_val:String, p_delimeter:String = null):String + { + if(HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) + { + if(p_delimeter == null) + p_URL += (p_URL.indexOf( "?" ) != -1 ) ? "&" + p_name + "=" : "?" + p_name + "="; + else + p_URL += p_delimeter + p_name + "="; + p_URL += p_val != null ? escape(p_val) : ""; + } + return p_URL; + } + + + public static function resolveUniqueURL(p_URL:String, p_rateInSecsToCache:Number = 0):String + { + var request:String = p_URL; + + if((HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) && p_URL.indexOf( "&cacheID=" ) == -1 && p_URL.indexOf( "?cacheID=" ) == -1) + { + var d:Date = new Date(); + var ID:String; + var secsPassed:Number = (60 * d.getUTCMinutes()) + d.getUTCSeconds(); + + if(p_rateInSecsToCache == 0) + { + ID = String(d.valueOf()); + } + else + { + ID = d.getUTCFullYear() + "" + d.getUTCMonth() + "" +d.getUTCDate() + "" +d.getUTCHours() + "-" + Math.floor(secsPassed/p_rateInSecsToCache); + } + + request = HTTPUtil.addQueryParam(p_URL, "cacheID", ID); + } + + return request; + } + + + protected static function onPingResult(p_event:Event):void + { // NOTE: let errors be thrown or log them if you want to handle them + URLLoader(p_event.target).removeEventListener(Event.COMPLETE, HTTPUtil.onPingResult); + URLLoader(p_event.target).removeEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); + URLLoader(p_event.target).removeEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); + delete(HTTPUtil.k_pings[p_event.target]); + } + } +} diff --git a/src/com/dreamsocket/utils/PropertyStringUtil.as b/src/com/dreamsocket/utils/PropertyStringUtil.as index 67ec772..26ae4eb 100644 --- a/src/com/dreamsocket/utils/PropertyStringUtil.as +++ b/src/com/dreamsocket/utils/PropertyStringUtil.as @@ -1,82 +1,90 @@ -/** - * Dreamsocket - * - * Copyright 2009 Dreamsocket. - * All Rights Reserved. - * - * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and - * international intellectual property laws. No license is granted with respect to the - * software and users may not, among other things, reproduce, prepare derivative works - * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, - * or make any modifications of the Software without written permission from Dreamsocket. - * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, - * copyright or other proprietary notice, legend, symbol, or label in the Software. - * This notice is not intended to, and shall not, limit any rights Dreamsocket has under - * applicable law. - * - */ - - - -package com.dreamsocket.utils -{ - public class PropertyStringUtil - { - public function PropertyStringUtil() - { - } - - - public static function evalPropertyString(p_data:*, p_value:String):String - { - if(p_data == null || p_value == null) return null; - - return p_value.replace( - new RegExp("\\${.*?}", "gi"), - function():String - { - return (PropertyStringUtil.evalSinglePropertyString(p_data, arguments[0].replace(new RegExp( "\\${|}", "gi"), ""))); - } - ); - } - - - protected static function evalSinglePropertyString(p_data:*, p_value:String = null):* - { - var val:String = p_value == null ? "" : p_value; - var currPart:* = p_data; - var parts:Array; - var key:String; - - parts = val.split("."); - key = parts.shift(); - - switch(key) - { - case "cache.UID": - currPart = new Date().valueOf(); - break; - case "data": - try - { - var i:uint = 0; - var len:uint = parts.length; - if(len != 0) - { - for(; i < len; i++) - { - currPart = currPart[parts[i]]; - } - } - } - catch(error:Error) - { - currPart = null; - } - break; - } - - return (currPart); - } - } -} +/** +* Dreamsocket, Inc. +* http://dreamsocket.com +* Copyright 2010 Dreamsocket, Inc. +* +* 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. +**/ + + +package com.dreamsocket.utils +{ + public class PropertyStringUtil + { + public function PropertyStringUtil() + { + } + + + public static function evalPropertyString(p_data:*, p_value:String):String + { + if(p_data == null || p_value == null) return null; + + return p_value.replace( + new RegExp("\\${.*?}", "gi"), + function():String + { + return (PropertyStringUtil.evalSinglePropertyString(p_data, arguments[0].replace(new RegExp( "\\${|}", "gi"), ""))); + } + ); + } + + + protected static function evalSinglePropertyString(p_data:*, p_value:String = null):* + { + var val:String = p_value == null ? "" : p_value; + var currPart:* = p_data; + var parts:Array; + var key:String; + + parts = val.split("."); + key = parts.shift(); + + switch(key) + { + case "cache.UID": + currPart = new Date().valueOf(); + break; + case "data": + try + { + var i:uint = 0; + var len:uint = parts.length; + if(len != 0) + { + for(; i < len; i++) + { + currPart = currPart[parts[i]]; + } + } + } + catch(error:Error) + { + currPart = null; + } + break; + } + + return (currPart); + } + } +}
dreamsocket/actionscript-analytics-framework
855be3f30ba5ea6e6c946e1535e2cb07e5b9b45b
[ADMIN] init
diff --git a/libs/GoogleAnalytics_1.0.1.319.swc b/libs/GoogleAnalytics_1.0.1.319.swc new file mode 100644 index 0000000..4633eeb Binary files /dev/null and b/libs/GoogleAnalytics_1.0.1.319.swc differ diff --git a/libs/OmnitureActionSource_2.8.swc b/libs/OmnitureActionSource_2.8.swc new file mode 100644 index 0000000..66f3f53 Binary files /dev/null and b/libs/OmnitureActionSource_2.8.swc differ diff --git a/src/com/dreamsocket/tracking/ITrack.as b/src/com/dreamsocket/tracking/ITrack.as new file mode 100644 index 0000000..d35bd13 --- /dev/null +++ b/src/com/dreamsocket/tracking/ITrack.as @@ -0,0 +1,28 @@ +/** + * Dreamsocket, Inc. + * + * Copyright 2009 Dreamsocket, Inc.. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket, Inc.. + * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under + * applicable law. + * + */ + + +package com.dreamsocket.tracking +{ + + public interface ITrack + { + function get data():*; + function get type():String; + } +} diff --git a/src/com/dreamsocket/tracking/ITracker.as b/src/com/dreamsocket/tracking/ITracker.as new file mode 100644 index 0000000..61b7166 --- /dev/null +++ b/src/com/dreamsocket/tracking/ITracker.as @@ -0,0 +1,29 @@ +/** + * Dreamsocket, Inc. + * + * Copyright 2009 Dreamsocket, Inc.. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket, Inc.. + * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under + * applicable law. + * + */ + + +package com.dreamsocket.tracking +{ + import com.dreamsocket.tracking.ITrack; + + + public interface ITracker + { + function track(p_track:ITrack):void + } +} diff --git a/src/com/dreamsocket/tracking/Track.as b/src/com/dreamsocket/tracking/Track.as new file mode 100644 index 0000000..744fa1e --- /dev/null +++ b/src/com/dreamsocket/tracking/Track.as @@ -0,0 +1,48 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking +{ + import com.dreamsocket.tracking.ITrack; + + public class Track implements ITrack + { + protected var m_data:*; + protected var m_type:String; + + public function Track(p_type:String, p_data:* = null) + { + this.m_type = p_type; + this.m_data = p_data; + } + + + public function get data():* + { + return this.m_data; + } + + + public function get type():String + { + return this.m_type; + } + } +} diff --git a/src/com/dreamsocket/tracking/TrackingManager.as b/src/com/dreamsocket/tracking/TrackingManager.as new file mode 100644 index 0000000..0e0902d --- /dev/null +++ b/src/com/dreamsocket/tracking/TrackingManager.as @@ -0,0 +1,79 @@ +/** + * Dreamsocket, Inc. + * + * Copyright 2009 Dreamsocket, Inc.. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket, Inc.. + * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under + * applicable law. + * + */ + + +package com.dreamsocket.tracking +{ + import flash.utils.Dictionary; + + public class TrackingManager + { + protected static var k_enabled:Boolean = true; + protected static var k_trackers:Dictionary = new Dictionary(); + + + public function TrackingManager() + { + } + + + public static function get enabled():Boolean + { + return k_enabled; + } + + + public static function set enabled(p_enabled:Boolean):void + { + k_enabled = p_enabled; + } + + + + public static function track(p_track:ITrack):void + { + if(!k_enabled) return; + + var tracker:Object; + + // send track payload to all trackers + for each(tracker in k_trackers) + { + ITracker(tracker).track(p_track); + } + } + + + public static function addTracker(p_ID:String, p_tracker:ITracker):void + { + k_trackers[p_ID] = p_tracker; + } + + + public static function getTracker(p_ID:String):ITracker + { + return k_trackers[p_ID] as ITracker; + } + + + public static function removeTracker(p_ID:String):void + { + delete(k_trackers[p_ID]); + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as b/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as new file mode 100644 index 0000000..9106c67 --- /dev/null +++ b/src/com/dreamsocket/tracking/google/GoogleTrackEventRequest.as @@ -0,0 +1,50 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.google +{ + public class GoogleTrackEventRequest + { + /** + * specifies a string representing groups of events. + */ + public var category:String; + + /** + * specifies a string that is paired with each category and is typically used to track activities + */ + public var action:String; + + /** + * specifies an optional string that provides additional scoping to the category/action pairing + */ + public var label:String; + + /** + * specifies an optional non negative integer for numerical data + */ + public var value:String; + + + public function GoogleTrackEventRequest() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as b/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as new file mode 100644 index 0000000..daf0892 --- /dev/null +++ b/src/com/dreamsocket/tracking/google/GoogleTrackHandler.as @@ -0,0 +1,32 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.google +{ + public class GoogleTrackHandler + { + public var ID:String; + public var request:Object; // GoogleTrackPageViewRequest, GoogleTrackEventRequest + + public function GoogleTrackHandler() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as b/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as new file mode 100644 index 0000000..5dd4563 --- /dev/null +++ b/src/com/dreamsocket/tracking/google/GoogleTrackPageViewRequest.as @@ -0,0 +1,31 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.google +{ + public class GoogleTrackPageViewRequest + { + public var URL:String; + + public function GoogleTrackPageViewRequest() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTracker.as b/src/com/dreamsocket/tracking/google/GoogleTracker.as new file mode 100644 index 0000000..786424f --- /dev/null +++ b/src/com/dreamsocket/tracking/google/GoogleTracker.as @@ -0,0 +1,163 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.google +{ + import flash.display.DisplayObject; + import flash.utils.Dictionary; + + import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.tracking.ITracker; + import com.dreamsocket.tracking.google.GoogleTrackerConfig; + import com.dreamsocket.tracking.google.GoogleTrackEventRequest; + import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; + import com.dreamsocket.tracking.google.GoogleTrackHandler; + + import com.google.analytics.GATracker; + + + public class GoogleTracker implements ITracker + { + public static var display:DisplayObject; + + public static const ID:String = "GoogleTracker"; + + protected var m_config:GoogleTrackerConfig; + protected var m_display:DisplayObject; + protected var m_enabled:Boolean; + protected var m_service:GATracker; + protected var m_trackHandlers:Dictionary; + + public function GoogleTracker(p_display:DisplayObject = null) + { + super(); + + this.m_display = p_display; + this.m_enabled = true; + this.m_trackHandlers = new Dictionary(); + } + + + public function get config():GoogleTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:GoogleTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + + try + { + this.m_service = new GATracker(this.m_display == null ? GoogleTracker.display : this.m_display, p_value.account, p_value.trackingMode, p_value.visualDebug); + } + catch(error:Error) + { + trace(error); + } + this.m_enabled = p_value.enabled; + this.m_trackHandlers = p_value.trackHandlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function addTrackHandler(p_ID:String, p_trackHandler:GoogleTrackHandler):void + { + this.m_trackHandlers[p_ID] = p_trackHandler; + } + + + public function destroy():void + { + } + + + public function getTrackHandler(p_ID:String):GoogleTrackHandler + { + return this.m_trackHandlers[p_ID] as GoogleTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_trackHandlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled || this.m_service == null) return; + + var handler:GoogleTrackHandler = this.m_config.trackHandlers[p_track.type]; + + + if(handler != null) + { // has a track handler + // call correct track method + if(handler.request is GoogleTrackEventRequest) + { + var eventRequest:GoogleTrackEventRequest = GoogleTrackEventRequest(handler.request); + var category:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.category); + var action:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.action); + var label:String = PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.label); + var value:Number = Number(PropertyStringUtil.evalPropertyString(p_track.data, eventRequest.value)); + + try + { + this.m_service.trackEvent(category, action, label, value); + } + catch(error:Error) + { + trace(error); + } + } + else if(handler.request is GoogleTrackPageViewRequest) + { + var viewRequest:GoogleTrackPageViewRequest = GoogleTrackPageViewRequest(handler.request); + + try + { + this.m_service.trackPageview(PropertyStringUtil.evalPropertyString(p_track.data, viewRequest.URL)); + } + catch(error:Error) + { + trace(error); + } + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as b/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as new file mode 100644 index 0000000..b2a32d6 --- /dev/null +++ b/src/com/dreamsocket/tracking/google/GoogleTrackerConfig.as @@ -0,0 +1,44 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.google +{ + import flash.utils.Dictionary; + + import com.google.analytics.core.TrackerMode; + + + public class GoogleTrackerConfig + { + public var account:String; + public var enabled:Boolean; + public var trackingMode:String; + public var visualDebug:Boolean; + public var trackHandlers:Dictionary; + + + public function GoogleTrackerConfig() + { + this.enabled = true; + this.trackingMode = TrackerMode.AS3; + this.trackHandlers = new Dictionary(); + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as new file mode 100644 index 0000000..cf4ffc0 --- /dev/null +++ b/src/com/dreamsocket/tracking/google/GoogleTrackerConfigXMLDecoder.as @@ -0,0 +1,107 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.google +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.google.GoogleTrackerConfig; + import com.dreamsocket.tracking.google.GoogleTrackHandler; + import com.dreamsocket.tracking.google.GoogleTrackEventRequest; + import com.dreamsocket.tracking.google.GoogleTrackPageViewRequest; + + import com.google.analytics.core.TrackerMode; + + + + public class GoogleTrackerConfigXMLDecoder + { + public function GoogleTrackerConfigXMLDecoder() + { + super(); + } + + + public function decode(p_XML:XML):GoogleTrackerConfig + { + var config:GoogleTrackerConfig = new GoogleTrackerConfig(); + + if(p_XML.account.toString().length) + config.account = p_XML.account.toString(); + + config.enabled = p_XML.enabled.toString() != "false"; + config.trackingMode = p_XML.trackingMode.toString() == TrackerMode.AS3 ? TrackerMode.AS3 : TrackerMode.BRIDGE; + config.visualDebug = p_XML.visualDebug.toString() != "false"; + + this.setTrackHandlers(config.trackHandlers, p_XML.trackHandlers.trackHandler); + + return config; + } + + + public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void + { + var handler:GoogleTrackHandler; + var handlerNode:XML; + var ID:String; + var eventRequest:GoogleTrackEventRequest; + var pageViewRequest:GoogleTrackPageViewRequest; + var trackNode:XML; + + for each(handlerNode in p_handlerNodes) + { + ID = handlerNode.ID.toString(); + if(ID.length > 0) + { + if(handlerNode.trackEvent.toString().length) + { // decode trackPageView + handler = new GoogleTrackHandler(); + handler.ID = ID; + handler.request = eventRequest = new GoogleTrackEventRequest(); + trackNode = handlerNode.trackEvent[0]; + + if(trackNode.action.toString().length) + eventRequest.action = trackNode.action.toString(); + if(trackNode.category.toString().length) + eventRequest.category = trackNode.category.toString(); + if(trackNode.label.toString().length) + eventRequest.label = trackNode.label.toString(); + if(trackNode.value.toString().length) + eventRequest.value = trackNode.value.toString(); + + p_handlers[ID] = handler; + } + else if(handlerNode.trackPageView.toString().length) + { // decode track + handler = new GoogleTrackHandler(); + handler.ID = ID; + handler.request = pageViewRequest = new GoogleTrackPageViewRequest(); + trackNode = handlerNode.trackPageView[0]; + + if(trackNode.URL.toString().length) + pageViewRequest.URL = trackNode.URL.toString(); + + p_handlers[ID] = handler; + } + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as b/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as new file mode 100644 index 0000000..f8995cb --- /dev/null +++ b/src/com/dreamsocket/tracking/google/GoogleTrackerParams.as @@ -0,0 +1,26 @@ +/** + * Dreamsocket + * + * Copyright 2010 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.google +{ + public class GoogleTrackerParams + { + } +} diff --git a/src/com/dreamsocket/tracking/js/JSMethodCall.as b/src/com/dreamsocket/tracking/js/JSMethodCall.as new file mode 100644 index 0000000..8f97612 --- /dev/null +++ b/src/com/dreamsocket/tracking/js/JSMethodCall.as @@ -0,0 +1,34 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.js +{ + public class JSMethodCall + { + public var method:String; + public var arguments:Array; + + public function JSMethodCall(p_method:String = null, p_arguments:Array = null) + { + this.method = p_method; + this.arguments = p_arguments == null ? [] : p_arguments; + } + } +} diff --git a/src/com/dreamsocket/tracking/js/JSTrackHandler.as b/src/com/dreamsocket/tracking/js/JSTrackHandler.as new file mode 100644 index 0000000..a893795 --- /dev/null +++ b/src/com/dreamsocket/tracking/js/JSTrackHandler.as @@ -0,0 +1,35 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.js +{ + + public class JSTrackHandler + { + public var ID:String; + public var methodCalls:Array; + + public function JSTrackHandler(p_ID:String = null, p_methodCalls:Array = null) + { + this.ID = p_ID; + this.methodCalls = p_methodCalls == null ? [] : p_methodCalls; + } + } +} diff --git a/src/com/dreamsocket/tracking/js/JSTracker.as b/src/com/dreamsocket/tracking/js/JSTracker.as new file mode 100644 index 0000000..cc9ee25 --- /dev/null +++ b/src/com/dreamsocket/tracking/js/JSTracker.as @@ -0,0 +1,146 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.js +{ + import flash.external.ExternalInterface; + import flash.utils.Dictionary; + + import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.tracking.ITracker; + import com.dreamsocket.tracking.js.JSTrackerConfig; + import com.dreamsocket.tracking.js.JSTrackHandler; + + + public class JSTracker implements ITracker + { + public static const ID:String = "JSTracker"; + + + protected var m_config:JSTrackerConfig; + protected var m_enabled:Boolean; + protected var m_trackHandlers:Dictionary; + + + public function JSTracker() + { + super(); + + this.m_config = new JSTrackerConfig(); + this.m_enabled = true; + this.m_trackHandlers = new Dictionary(); + } + + + public function get config():JSTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:JSTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + this.m_enabled = p_value.enabled; + this.m_trackHandlers = p_value.trackHandlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function addTrackHandler(p_ID:String, p_trackHandler:JSTrackHandler):void + { + this.m_trackHandlers[p_ID] = p_trackHandler; + } + + + public function getTrackHandler(p_ID:String):JSTrackHandler + { + return this.m_trackHandlers[p_ID] as JSTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_trackHandlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled) return; + + var handler:JSTrackHandler = this.m_trackHandlers[p_track.type]; + + if(handler != null) + { // has the track type + var methodCalls:Array = handler.methodCalls; + var i:int = 0; + var len:uint = methodCalls.length; + + while(i < len) + { + this.performJSCall(JSMethodCall(methodCalls[i]), p_track.data); + i++; + } + } + } + + protected function performJSCall(p_methodCall:JSMethodCall, p_data:* = null):void + { + ; + if(ExternalInterface.available) + { + try + { + var args:Array = p_methodCall.arguments.concat(); + var i:int = args.length; + + while(i--) + { + args[i] = PropertyStringUtil.evalPropertyString(p_data, args[i]); + } + + args.unshift(p_methodCall.method); + + ExternalInterface.call.apply(ExternalInterface, args); + } + catch(error:Error) + { // do nothing + trace("JSTracker.track - " + error); + } + } + } + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/tracking/js/JSTrackerConfig.as b/src/com/dreamsocket/tracking/js/JSTrackerConfig.as new file mode 100644 index 0000000..815d54a --- /dev/null +++ b/src/com/dreamsocket/tracking/js/JSTrackerConfig.as @@ -0,0 +1,37 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.js +{ + import flash.utils.Dictionary; + + + public class JSTrackerConfig + { + public var enabled:Boolean; + public var trackHandlers:Dictionary; + + public function JSTrackerConfig() + { + this.enabled = true; + this.trackHandlers = new Dictionary(); + } + } +} diff --git a/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as new file mode 100644 index 0000000..01c26d9 --- /dev/null +++ b/src/com/dreamsocket/tracking/js/JSTrackerConfigXMLDecoder.as @@ -0,0 +1,81 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.js +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.js.JSTrackerConfig; + import com.dreamsocket.tracking.js.JSTrackHandler; + + + public class JSTrackerConfigXMLDecoder + { + public function JSTrackerConfigXMLDecoder() + { + } + + + public function decode(p_xml:XML):JSTrackerConfig + { + var config:JSTrackerConfig = new JSTrackerConfig(); + var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; + var trackHandlerNode:XML; + var trackHandlers:Dictionary = config.trackHandlers; + + // trackHandlers + for each(trackHandlerNode in trackHandlerNodes) + { + this.addTrack(trackHandlers, trackHandlerNode); + } + // enabled + config.enabled = p_xml.enabled.toString() != "false"; + + return config; + } + + + protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void + { + var ID:String = p_trackHandlerNode.ID.toString(); + var methodCallNode:XML; + var handler:JSTrackHandler; + + if(ID.length > 0) + { + handler = new JSTrackHandler(); + for each(methodCallNode in p_trackHandlerNode.methodCalls.methodCall) + { + handler.methodCalls.push(this.createMethodCall(methodCallNode[0])); + } + p_trackHandlers[ID] = handler; + } + } + + protected function createMethodCall(p_methodNode:XML):JSMethodCall + { + var methodCall:JSMethodCall = new JSMethodCall(p_methodNode.ID.toString()); + var arguments:Array = p_methodNode.arguments.argument; + var argumentNode + for each() + methodCall.arguments + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureParams.as b/src/com/dreamsocket/tracking/omniture/OmnitureParams.as new file mode 100644 index 0000000..d857433 --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureParams.as @@ -0,0 +1,58 @@ +/** + * Dreamsocket, Inc. + * + * Copyright 2009 Dreamsocket, Inc.. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket, Inc.. + * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under + * applicable law. + * + */ + + +package com.dreamsocket.tracking.omniture +{ + + public dynamic class OmnitureParams + { + // debug vars + public var debugTracking:Boolean; + public var trackLocal:Boolean; + + // required + public var account:String; + public var dc:String; + public var pageName:String; + public var pageURL:String; + public var visitorNameSpace:String; + + // optional + public var autoTrack:Boolean; + public var charSet:String; + public var cookieDomainPeriods:Number; + public var cookieLifetime:String; + public var currencyCode:String; + public var delayTracking:Number; + public var events:String; + public var linkLeaveQueryString:Boolean; + public var movieID:String; + public var pageType:String; + public var referrer:String; + public var trackClickMap:Boolean; + public var trackingServer:String; + public var trackingServerBase:String; + public var trackingServerSecure:String; + public var vmk:String; + + public function OmnitureParams() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as b/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as new file mode 100644 index 0000000..66b3bf4 --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureParamsXMLDecoder.as @@ -0,0 +1,101 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.omniture +{ + import com.dreamsocket.tracking.omniture.OmnitureParams; + + + public class OmnitureParamsXMLDecoder + { + protected var m_params:OmnitureParams; + + + public function OmnitureParamsXMLDecoder() + { + } + + + public function decode(p_paramNodes:XML):OmnitureParams + { + var params:OmnitureParams = new OmnitureParams(); + + if(p_paramNodes == null) return params; + // debug + if(p_paramNodes.debugTracking.toString().length) + params.debugTracking = p_paramNodes.debugTracking.toString() == "true"; + if(p_paramNodes.trackLocal.toString().length) + params.trackLocal = p_paramNodes.trackLocal.toString() == "true"; + + // required + if(p_paramNodes.account.toString().length) + params.account = p_paramNodes.account.toString(); + if(p_paramNodes.dc.toString().length) + params.dc = p_paramNodes.dc.toString(); + if(p_paramNodes.pageName.toString().length) + params.pageName = p_paramNodes.pageName.toString(); + if(p_paramNodes.pageURL.toString().length) + params.pageURL = p_paramNodes.pageURL.toString(); + if(p_paramNodes.visitorNameSpace.toString().length) + params.visitorNameSpace = p_paramNodes.visitorNameSpace.toString(); + + // optional + if(p_paramNodes.autoTrack.length()) + params.autoTrack = p_paramNodes.autoTrack.toString() == "true"; + if(p_paramNodes.charSet.length()) + params.charSet = p_paramNodes.charSet.toString(); + if(p_paramNodes.cookieDomainPeriods.length()) + params.cookieDomainPeriods = int(p_paramNodes.cookieDomainPeriods.toString()); + if(p_paramNodes.cookieLifetime.length()) + params.cookieLifetime = p_paramNodes.cookieLifetime.toString(); + if(p_paramNodes.currencyCode.length()) + params.currencyCode = p_paramNodes.currencyCode.toString(); + if(p_paramNodes.delayTracking.length()) + params.delayTracking = Number(p_paramNodes.delayTracking.toString()); + if(p_paramNodes.linkLeaveQueryString.length()) + params.linkLeaveQueryString = p_paramNodes.linkLeaveQueryString.toString() == true; + if(p_paramNodes.pageType.length()) + params.pageType = p_paramNodes.pageType.toString(); + if(p_paramNodes.referrer.length()) + params.referrer = p_paramNodes.referrer.toString(); + if(p_paramNodes.trackClickMap.length()) + params.trackClickMap = p_paramNodes.trackClickMap.toString() == "true"; + if(p_paramNodes.trackingServer.length()) + params.trackingServer = p_paramNodes.trackingServer.toString(); + if(p_paramNodes.trackingServerBase.length()) + params.trackingServerBase = p_paramNodes.trackingServerBase.toString(); + if(p_paramNodes.trackingServerSecure.length()) + params.trackingServerSecure = p_paramNodes.trackingServerSecure.toString(); + if(p_paramNodes.vmk.length()) + params.vmk = p_paramNodes.vmk.toString(); + + var paramNode:XML; + for each(paramNode in p_paramNodes.*) + { + if(params[paramNode.name()] == undefined) + { + params[paramNode.name()] = paramNode.toString(); + } + } + + return params; + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureService.as b/src/com/dreamsocket/tracking/omniture/OmnitureService.as new file mode 100644 index 0000000..1854941 --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureService.as @@ -0,0 +1,248 @@ +/** + * Dreamsocket, Inc. + * + * Copyright 2009 Dreamsocket, Inc.. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket, Inc.. + * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under + * applicable law. + * + */ + + +package com.dreamsocket.tracking.omniture +{ + import flash.display.DisplayObjectContainer; + import flash.utils.describeType; + + import com.dreamsocket.tracking.omniture.OmnitureParams; + + import com.omniture.ActionSource; + + + public class OmnitureService + { + public static var display:DisplayObjectContainer; + + protected var m_config:OmnitureParams; + protected var m_display:DisplayObjectContainer; + protected var m_enabled:Boolean; + protected var m_lastTrackParams:OmnitureParams; + protected var m_tracker:ActionSource; + + + public function OmnitureService(p_display:DisplayObjectContainer = null) + { + this.m_display = p_display; + this.m_enabled = true; + } + + + public function get config():OmnitureParams + { + return this.m_config; + } + + + public function set config(p_config:OmnitureParams):void + { + if(p_config != this.m_config) + { + this.m_config = p_config; + this.reset(); + this.mergeParams(p_config, this.m_tracker); + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function destroy():void + { + if(this.m_tracker != null && this.m_display != null && this.m_display.contains(this.m_tracker)) + { + this.m_display.removeChild(this.m_tracker); + } + this.m_tracker = null; + this.m_config = null; + this.m_display = null; + this.m_lastTrackParams = null; + OmnitureService.display = null; + } + + + public function track(p_params:OmnitureParams):void + { + if(!this.m_enabled) return; + + this.resetTrackParams(); + this.m_lastTrackParams = p_params; + this.mergeParams(p_params, this.m_tracker); + + try + { + this.m_tracker.track(); + } + catch(error:Error) + { + trace(error); + } + } + + + public function trackLink(p_params:OmnitureParams, p_URL:String, p_type:String, p_name:String):void + { + if(!this.m_enabled) return; + + this.resetTrackParams(); + this.m_lastTrackParams = p_params; + this.mergeParams(p_params, this.m_tracker); + + try + { + this.m_tracker.trackLink(p_URL, p_type, p_name); + } + catch(error:Error) + { + trace(error); + } + } + + + protected function mergeParams(p_params:OmnitureParams, p_destination:Object):void + { + var desc:XML = describeType(p_params); + var propNode:XML; + var props:XMLList = desc..variable; + var type:String; + var name:String; + var val:*; + + // instance props + for each(propNode in props) + { + name = propNode.@name; + type = propNode.@type; + val = p_params[name]; + if(val is String && val != null) + { + p_destination[name] = val; + } + else if(val is Number && !isNaN(val)) + { + p_destination[name] = val; + } + else if(val is Boolean && val) + { + p_destination[name] = val; + } + } + + // dynamic props + for(name in p_params) + { + val = p_params[name]; + if(val is String && val != null) + { + p_destination[name] = val; + } + else if(val is Number && !isNaN(val)) + { + p_destination[name] = val; + } + else if(val is Boolean && val) + { + p_destination[name] = val; + } + } + } + + + protected function reset():void + { + if(this.m_config == null) return; + + this.m_display = this.m_display == null ? OmnitureService.display : this.m_display; + + if(this.m_tracker != null && this.m_display != null && this.m_display.contains(this.m_tracker)) + { + this.m_display.removeChild(this.m_tracker); + } + this.m_tracker = new ActionSource(); + if(this.m_tracker != null && this.m_display != null) + { + this.m_display.addChild(this.m_tracker); + } + } + + + protected function resetTrackParams():void + { + if(this.m_lastTrackParams == null) return; + + var params:OmnitureParams = this.m_config; + var desc:XML = describeType(this.m_lastTrackParams); + var propNode:XML; + var props:XMLList = desc..variable; + var type:String; + var name:String; + var val:*; + + // instance props + for each(propNode in props) + { + name = propNode.@name; + type = propNode.@type; + + val = this.m_lastTrackParams[name]; + if(val is String && val != null) + { + this.m_tracker[name] = params[name]; + } + else if(val is Number && !isNaN(val)) + { + this.m_tracker[name] = params[name]; + } + else if(val is Boolean && val) + { + this.m_tracker[name] = params[name]; + } + } + + // dynamic props + for(name in this.m_lastTrackParams) + { + val = this.m_lastTrackParams[name]; + if(val is String && val != null) + { + this.m_tracker[name] = params[name]; + } + else if(val is Number && !isNaN(val)) + { + this.m_tracker[name] = params[name]; + } + else if(val is Boolean && val) + { + this.m_tracker[name] = params[name]; + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as new file mode 100644 index 0000000..28cf867 --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackHandler.as @@ -0,0 +1,33 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.omniture +{ + + public class OmnitureTrackHandler + { + public var ID:String; + public var request:Object; + + public function OmnitureTrackHandler() + { + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as new file mode 100644 index 0000000..debc3fa --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackLinkRequest.as @@ -0,0 +1,35 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.omniture +{ + public class OmnitureTrackLinkRequest + { + public var name:String; + public var params:OmnitureParams; + public var type:String; + public var URL:String; + + public function OmnitureTrackLinkRequest() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as new file mode 100644 index 0000000..8b336b8 --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackRequest.as @@ -0,0 +1,32 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.omniture +{ + public class OmnitureTrackRequest + { + public var params:OmnitureParams; + + public function OmnitureTrackRequest() + { + this.params = new OmnitureParams(); + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as b/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as new file mode 100644 index 0000000..29a1bab --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTracker.as @@ -0,0 +1,161 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.omniture +{ + import flash.display.DisplayObjectContainer; + import flash.utils.describeType; + import flash.utils.Dictionary; + + import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.tracking.ITracker; + import com.dreamsocket.tracking.omniture.OmnitureService; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; + import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; + import com.dreamsocket.tracking.omniture.OmnitureTrackRequest; + import com.dreamsocket.tracking.omniture.OmnitureTrackLinkRequest; + + + public class OmnitureTracker implements ITracker + { + public static var display:DisplayObjectContainer; + public static const ID:String = "OmnitureTracker"; + + protected var m_config:OmnitureTrackerConfig; + protected var m_enabled:Boolean; + protected var m_service:OmnitureService; + protected var m_trackHandlers:Dictionary; + + public function OmnitureTracker(p_display:DisplayObjectContainer = null) + { + super(); + + this.m_enabled = true; + this.m_service = new OmnitureService(p_display == null ? OmnitureTracker.display : p_display); + this.m_trackHandlers = new Dictionary(); + } + + + public function get config():OmnitureTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:OmnitureTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + this.m_service.config = p_value.params; + this.m_enabled = p_value.enabled; + this.m_trackHandlers = p_value.trackHandlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function addTrackHandler(p_ID:String, p_trackHandler:OmnitureTrackHandler):void + { + this.m_trackHandlers[p_ID] = p_trackHandler; + } + + + public function getTrackHandler(p_ID:String):OmnitureTrackHandler + { + return this.m_trackHandlers[p_ID] as OmnitureTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_trackHandlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled) return; + + var handler:OmnitureTrackHandler = this.m_config.trackHandlers[p_track.type]; + + + if(handler != null && handler.request != null) + { // has a track handler + var requestParams:OmnitureParams = new OmnitureParams(); + var handlerParams:OmnitureParams; + + if(handler.request.params != null && handler.request.params is OmnitureParams) + { + handlerParams = handler.request.params; + + var desc:XML = describeType(handlerParams); + var propNode:XML; + var props:XMLList = desc..variable; + var prop:String; + var val:*; + + // instance props + for each(propNode in props) + { + prop = propNode.@name; + val = handlerParams[prop]; + if(val is String && val != null) + { + requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, val); + } + } + // dynamic prop + for(prop in handlerParams) + { + requestParams[prop] = PropertyStringUtil.evalPropertyString(p_track.data, handlerParams[prop]); + } + } + + + // call correct track method + if(handler.request is OmnitureTrackLinkRequest) + { + var URL:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.URL); + var type:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.type); + var name:String = PropertyStringUtil.evalPropertyString(p_track.data, handler.request.name); + + this.m_service.trackLink(requestParams, URL, type, name); + } + else if(handler.request is OmnitureTrackRequest) + { + this.m_service.track(requestParams); + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as new file mode 100644 index 0000000..348c05b --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfig.as @@ -0,0 +1,38 @@ +/** + * Dreamsocket, Inc. + * + * Copyright 2009 Dreamsocket, Inc.. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket, Inc.. + * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under + * applicable law. + * + */ + + +package com.dreamsocket.tracking.omniture +{ + import flash.utils.Dictionary; + + + public class OmnitureTrackerConfig + { + public var enabled:Boolean; + public var params:OmnitureParams; + public var trackHandlers:Dictionary; + + public function OmnitureTrackerConfig() + { + this.enabled = true; + this.params = new OmnitureParams(); + this.trackHandlers = new Dictionary(); + } + } +} diff --git a/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as new file mode 100644 index 0000000..9984541 --- /dev/null +++ b/src/com/dreamsocket/tracking/omniture/OmnitureTrackerConfigXMLDecoder.as @@ -0,0 +1,94 @@ +/** + * Dreamsocket, Inc. + * + * Copyright 2009 Dreamsocket, Inc.. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket, Inc. and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket, Inc.. + * Further, Dreamsocket, Inc. does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket, Inc. has under + * applicable law. + * + */ + + +package com.dreamsocket.tracking.omniture +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.omniture.OmnitureParamsXMLDecoder; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; + import com.dreamsocket.tracking.omniture.OmnitureTrackHandler; + + + public class OmnitureTrackerConfigXMLDecoder + { + public function OmnitureTrackerConfigXMLDecoder() + { + } + + + public function decode(p_xml:XML):OmnitureTrackerConfig + { + var config:OmnitureTrackerConfig = new OmnitureTrackerConfig(); + + config.enabled = p_xml.enabled.toString() != "false"; + config.params = new OmnitureParamsXMLDecoder().decode(p_xml.params[0]); + this.setTrackHandlers(config.trackHandlers, p_xml.trackHandlers.trackHandler); + + return config; + } + + + public function setTrackHandlers(p_handlers:Dictionary, p_handlerNodes:XMLList):void + { + var handler:OmnitureTrackHandler; + var handlerNode:XML; + var ID:String; + var trackLinkRequest:OmnitureTrackLinkRequest; + var trackRequest:OmnitureTrackRequest; + var paramsDecoder:OmnitureParamsXMLDecoder = new OmnitureParamsXMLDecoder(); + var trackNode:XML; + for each(handlerNode in p_handlerNodes) + { + ID = handlerNode.ID.toString(); + if(ID.length > 0) + { + if(handlerNode.trackLink.toString().length) + { // decode trackLink + handler = new OmnitureTrackHandler(); + handler.ID = ID; + handler.request = trackLinkRequest = new OmnitureTrackLinkRequest(); + trackNode = handlerNode.trackLink[0]; + + if(trackNode.name.toString().length) + trackLinkRequest.name = trackNode.name.toString(); + if(trackNode.type.toString().length) + trackLinkRequest.type = trackNode.type.toString(); + if(trackNode.URL.toString().length) + trackLinkRequest.URL = trackNode.URL.toString(); + + trackLinkRequest.params = paramsDecoder.decode(trackNode.params[0]); + + p_handlers[ID] = handler; + } + else if(handlerNode.track.toString().length) + { // decode track + handler = new OmnitureTrackHandler(); + handler.ID = ID; + handler.request = trackRequest = new OmnitureTrackRequest(); + trackNode = handlerNode.track[0]; + trackRequest.params = paramsDecoder.decode(trackNode.params[0]); + + p_handlers[ID] = handler; + } + } + } + } + } +} diff --git a/src/com/dreamsocket/tracking/url/URLTrackHandler.as b/src/com/dreamsocket/tracking/url/URLTrackHandler.as new file mode 100644 index 0000000..73ad9b2 --- /dev/null +++ b/src/com/dreamsocket/tracking/url/URLTrackHandler.as @@ -0,0 +1,35 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.url +{ + + public class URLTrackHandler + { + public var ID:String; + public var URLs:Array; + + public function URLTrackHandler(p_ID:String = null, p_URLs:Array = null) + { + this.ID = p_ID; + this.URLs = p_URLs == null ? [] : p_URLs; + } + } +} diff --git a/src/com/dreamsocket/tracking/url/URLTracker.as b/src/com/dreamsocket/tracking/url/URLTracker.as new file mode 100644 index 0000000..ed8f5c0 --- /dev/null +++ b/src/com/dreamsocket/tracking/url/URLTracker.as @@ -0,0 +1,118 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.url +{ + import flash.utils.Dictionary; + + import com.dreamsocket.utils.PropertyStringUtil; + import com.dreamsocket.tracking.ITrack; + import com.dreamsocket.tracking.ITracker; + import com.dreamsocket.tracking.url.URLTrackerConfig; + import com.dreamsocket.tracking.url.URLTrackHandler; + import com.dreamsocket.utils.HTTPUtil; + + + public class URLTracker implements ITracker + { + public static const ID:String = "URLTracker"; + + + protected var m_config:URLTrackerConfig; + protected var m_enabled:Boolean; + protected var m_trackHandlers:Dictionary; + + + public function URLTracker() + { + super(); + + this.m_config = new URLTrackerConfig(); + this.m_enabled = true; + this.m_trackHandlers = new Dictionary(); + } + + + public function get config():URLTrackerConfig + { + return this.m_config; + } + + + public function set config(p_value:URLTrackerConfig):void + { + if(p_value != this.m_config) + { + this.m_config = p_value; + this.m_enabled = p_value.enabled; + this.m_trackHandlers = p_value.trackHandlers; + } + } + + + public function get enabled():Boolean + { + return this.m_enabled; + } + + + public function set enabled(p_enabled:Boolean):void + { + this.m_enabled = p_enabled; + } + + + public function addTrackHandler(p_ID:String, p_trackHandler:URLTrackHandler):void + { + this.m_trackHandlers[p_ID] = p_trackHandler; + } + + + public function getTrackHandler(p_ID:String):URLTrackHandler + { + return this.m_trackHandlers[p_ID] as URLTrackHandler; + } + + + public function removeTrackHandler(p_ID:String):void + { + delete(this.m_trackHandlers[p_ID]); + } + + + public function track(p_track:ITrack):void + { + if(!this.m_enabled) return; + + var handler:URLTrackHandler = this.m_trackHandlers[p_track.type]; + + if(handler != null) + { // has the track type + var URLs:Array = handler.URLs; + var i:uint = URLs.length; + + while(i--) + { + HTTPUtil.pingURL(PropertyStringUtil.evalPropertyString(p_track.data, URLs[i])); + } + } + } + } +} \ No newline at end of file diff --git a/src/com/dreamsocket/tracking/url/URLTrackerConfig.as b/src/com/dreamsocket/tracking/url/URLTrackerConfig.as new file mode 100644 index 0000000..e001bc6 --- /dev/null +++ b/src/com/dreamsocket/tracking/url/URLTrackerConfig.as @@ -0,0 +1,37 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.url +{ + import flash.utils.Dictionary; + + + public class URLTrackerConfig + { + public var enabled:Boolean; + public var trackHandlers:Dictionary; + + public function URLTrackerConfig() + { + this.enabled = true; + this.trackHandlers = new Dictionary(); + } + } +} diff --git a/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as b/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as new file mode 100644 index 0000000..e39207d --- /dev/null +++ b/src/com/dreamsocket/tracking/url/URLTrackerConfigXMLDecoder.as @@ -0,0 +1,72 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.tracking.url +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.url.URLTrackerConfig; + import com.dreamsocket.tracking.url.URLTrackHandler; + + + public class URLTrackerConfigXMLDecoder + { + public function URLTrackerConfigXMLDecoder() + { + } + + + public function decode(p_xml:XML):URLTrackerConfig + { + var config:URLTrackerConfig = new URLTrackerConfig(); + var trackHandlerNodes:XMLList = p_xml.trackHandlers.trackHandler; + var trackHandlerNode:XML; + var trackHandlers:Dictionary = config.trackHandlers; + + // trackHandlers + for each(trackHandlerNode in trackHandlerNodes) + { + this.addTrack(trackHandlers, trackHandlerNode); + } + // enabled + config.enabled = p_xml.enabled.toString() != "false"; + + return config; + } + + + protected function addTrack(p_trackHandlers:Dictionary, p_trackHandlerNode:XML):void + { + var ID:String = p_trackHandlerNode.ID.toString(); + var urlNode:XML; + var handler:URLTrackHandler; + + if(ID.length > 0) + { + handler = new URLTrackHandler(); + for each(urlNode in p_trackHandlerNode.URLs.URL) + { + handler.URLs.push(urlNode.toString()); + } + p_trackHandlers[ID] = handler; + } + } + } +} diff --git a/src/com/dreamsocket/utils/HTTPUtil.as b/src/com/dreamsocket/utils/HTTPUtil.as new file mode 100644 index 0000000..84e41e6 --- /dev/null +++ b/src/com/dreamsocket/utils/HTTPUtil.as @@ -0,0 +1,111 @@ +/** + * Dreamsocket + * + * Copyright 2007 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + +package com.dreamsocket.utils +{ + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + import flash.system.Security; + import flash.utils.Dictionary; + + public class HTTPUtil + { + public static var allowLocalQueryStrings:Boolean = false; + + protected static var k_pings:Dictionary = new Dictionary(); + + + public function HTTPUtil() + { + } + + + public static function pingURL(p_URL:String, p_clearCache:Boolean = true, p_rateInSecsToCache:Number = 0):void + { + if(p_URL == null) return; + + var loader:URLLoader = new URLLoader(); + var URL:String = p_URL; + + if(p_clearCache && (HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE)) + { + URL = HTTPUtil.resolveUniqueURL(p_URL, p_rateInSecsToCache); + } + + loader.load(new URLRequest(URL)); + loader.addEventListener(Event.COMPLETE, HTTPUtil.onPingResult); + loader.addEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); + loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); + + HTTPUtil.k_pings[loader] = true; + } + + + public static function addQueryParam(p_URL:String, p_name:String, p_val:String, p_delimeter:String = null):String + { + if(HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) + { + if(p_delimeter == null) + p_URL += (p_URL.indexOf( "?" ) != -1 ) ? "&" + p_name + "=" : "?" + p_name + "="; + else + p_URL += p_delimeter + p_name + "="; + p_URL += p_val != null ? escape(p_val) : ""; + } + return p_URL; + } + + + public static function resolveUniqueURL(p_URL:String, p_rateInSecsToCache:Number = 0):String + { + var request:String = p_URL; + + if((HTTPUtil.allowLocalQueryStrings || Security.sandboxType == Security.REMOTE) && p_URL.indexOf( "&cacheID=" ) == -1 && p_URL.indexOf( "?cacheID=" ) == -1) + { + var d:Date = new Date(); + var ID:String; + var secsPassed:Number = (60 * d.getUTCMinutes()) + d.getUTCSeconds(); + + if(p_rateInSecsToCache == 0) + { + ID = String(d.valueOf()); + } + else + { + ID = d.getUTCFullYear() + "" + d.getUTCMonth() + "" +d.getUTCDate() + "" +d.getUTCHours() + "-" + Math.floor(secsPassed/p_rateInSecsToCache); + } + + request = HTTPUtil.addQueryParam(p_URL, "cacheID", ID); + } + + return request; + } + + + protected static function onPingResult(p_event:Event):void + { // NOTE: let errors be thrown or log them if you want to handle them + URLLoader(p_event.target).removeEventListener(Event.COMPLETE, HTTPUtil.onPingResult); + URLLoader(p_event.target).removeEventListener(IOErrorEvent.IO_ERROR, HTTPUtil.onPingResult); + URLLoader(p_event.target).removeEventListener(SecurityErrorEvent.SECURITY_ERROR, HTTPUtil.onPingResult); + delete(HTTPUtil.k_pings[p_event.target]); + } + } +} diff --git a/src/com/dreamsocket/utils/PropertyStringUtil.as b/src/com/dreamsocket/utils/PropertyStringUtil.as new file mode 100644 index 0000000..67ec772 --- /dev/null +++ b/src/com/dreamsocket/utils/PropertyStringUtil.as @@ -0,0 +1,82 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package com.dreamsocket.utils +{ + public class PropertyStringUtil + { + public function PropertyStringUtil() + { + } + + + public static function evalPropertyString(p_data:*, p_value:String):String + { + if(p_data == null || p_value == null) return null; + + return p_value.replace( + new RegExp("\\${.*?}", "gi"), + function():String + { + return (PropertyStringUtil.evalSinglePropertyString(p_data, arguments[0].replace(new RegExp( "\\${|}", "gi"), ""))); + } + ); + } + + + protected static function evalSinglePropertyString(p_data:*, p_value:String = null):* + { + var val:String = p_value == null ? "" : p_value; + var currPart:* = p_data; + var parts:Array; + var key:String; + + parts = val.split("."); + key = parts.shift(); + + switch(key) + { + case "cache.UID": + currPart = new Date().valueOf(); + break; + case "data": + try + { + var i:uint = 0; + var len:uint = parts.length; + if(len != 0) + { + for(; i < len; i++) + { + currPart = currPart[parts[i]]; + } + } + } + catch(error:Error) + { + currPart = null; + } + break; + } + + return (currPart); + } + } +} diff --git a/test/TestGoogleTracker.as b/test/TestGoogleTracker.as new file mode 100644 index 0000000..16a0a96 --- /dev/null +++ b/test/TestGoogleTracker.as @@ -0,0 +1,68 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package +{ + import com.dreamsocket.tracking.Track; + import com.dreamsocket.tracking.google.GoogleTrackerConfig; + import com.dreamsocket.tracking.google.GoogleTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.google.GoogleTracker; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestGoogleTracker extends Sprite + { + private var m_loader:URLLoader; + private var m_tracker:GoogleTracker; + + public function TestGoogleTracker() + { + this.m_loader = new URLLoader(); + this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_loader.load(new URLRequest("test_tracking_google.xml")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onXMLLoaded(p_event:Event):void + { + var config:GoogleTrackerConfig = new GoogleTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); + + this.m_tracker = new GoogleTracker(this); + this.m_tracker.config = config; + + this.m_tracker.track(new Track("track1", "test string")); + this.m_tracker.track(new Track("track2", {id:"testid"})); + this.m_tracker.track(new Track("track3", "test string")); + } + } +} diff --git a/test/TestJSTracker.as b/test/TestJSTracker.as new file mode 100644 index 0000000..7a268d1 --- /dev/null +++ b/test/TestJSTracker.as @@ -0,0 +1,82 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package +{ + import flash.utils.Dictionary; + + import com.dreamsocket.tracking.Track; + import com.dreamsocket.tracking.js.JSTrackerConfig; + import com.dreamsocket.tracking.js.JSMethodCall; + import com.dreamsocket.tracking.js.JSTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.js.JSTracker; + import com.dreamsocket.tracking.js.JSTrackHandler; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestJSTracker extends Sprite + { + private var m_loader:URLLoader; + private var m_tracker:JSTracker; + + public function TestJSTracker() + { + //this.m_loader = new URLLoader(); + //this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + //this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + //this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + //this.m_loader.load(new URLRequest("test_tracking_omniture.xml")); + + var config:JSTrackerConfig = new JSTrackerConfig(); + var trackHandler:JSTrackHandler; + + this.m_tracker = new JSTracker(); + this.m_tracker.config = config; + + trackHandler = new JSTrackHandler(); + trackHandler.ID = "track3"; + trackHandler.methodCalls = [new JSMethodCall("doRandomThing", [1, 2, "3...{data.id}"])]; + + config.trackHandlers["track2"] = trackHandler; + + + this.m_tracker.track(new Track("track1", "test string1")); + this.m_tracker.track(new Track("track2", {id:"testid"})); + this.m_tracker.track(new Track("track3", "test string3")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onXMLLoaded(p_event:Event):void + { + + } + } +} diff --git a/test/TestJSTracker.html b/test/TestJSTracker.html new file mode 100644 index 0000000..61d7891 --- /dev/null +++ b/test/TestJSTracker.html @@ -0,0 +1,20 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> + <title>TestJSTracker</title> + <script language="JavaScript1.2" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" type="text/javascript"></script> + + </head> + <body> + <div id="test_swf"></div> + <script> + function doRandomThing(p_arg1, p_arg2, p_arg3) + { + alert(p_arg1 + "-" + p_arg2 + "-" + p_arg3); + } + + swfobject.embedSWF("TestJSTracker.swf", "test_swf", 500, 400, "9.0.0", "TestJSTracker.swf", {}, {allowScriptAccess:"always"}); + </script> + </body> +</html> diff --git a/test/TestOmnitureTracker.as b/test/TestOmnitureTracker.as new file mode 100644 index 0000000..804df84 --- /dev/null +++ b/test/TestOmnitureTracker.as @@ -0,0 +1,68 @@ +/** + * Dreamsocket + * + * Copyright 2009 Dreamsocket. + * All Rights Reserved. + * + * This software (the "Software") is the property of Dreamsocket and is protected by U.S. and + * international intellectual property laws. No license is granted with respect to the + * software and users may not, among other things, reproduce, prepare derivative works + * of, modify, distribute, sublicense, reverse engineer, disassemble, remove, decompile, + * or make any modifications of the Software without written permission from Dreamsocket. + * Further, Dreamsocket does not authorize any user to remove or alter any trademark, logo, + * copyright or other proprietary notice, legend, symbol, or label in the Software. + * This notice is not intended to, and shall not, limit any rights Dreamsocket has under + * applicable law. + * + */ + + + +package +{ + import com.dreamsocket.tracking.Track; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfig; + import com.dreamsocket.tracking.omniture.OmnitureTrackerConfigXMLDecoder; + import com.dreamsocket.tracking.omniture.OmnitureTracker; + + import flash.display.Sprite; + import flash.events.Event; + import flash.events.IOErrorEvent; + import flash.events.SecurityErrorEvent; + import flash.net.URLRequest; + import flash.net.URLLoader; + + public class TestOmnitureTracker extends Sprite + { + private var m_loader:URLLoader; + private var m_tracker:OmnitureTracker; + + public function TestOmnitureTracker() + { + this.m_loader = new URLLoader(); + this.m_loader.addEventListener(Event.COMPLETE, this.onXMLLoaded); + this.m_loader.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorOccurred); + this.m_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorOccurred); + this.m_loader.load(new URLRequest("test_tracking_omniture.xml")); + } + + + private function onErrorOccurred(p_event:Event):void + { + trace(p_event); + } + + + private function onXMLLoaded(p_event:Event):void + { + var config:OmnitureTrackerConfig = new OmnitureTrackerConfigXMLDecoder().decode(new XML(this.m_loader.data)); + + this.m_tracker = new OmnitureTracker(); + this.m_tracker.config = config; + + this.m_tracker.track(new Track("track1", "test string")); + this.m_tracker.track(new Track("track2", {id:"testid"})); + this.m_tracker.track(new Track("track3", "test string")); + } + } +} diff --git a/test/test_tracking_google.xml b/test/test_tracking_google.xml new file mode 100644 index 0000000..c1afc46 --- /dev/null +++ b/test/test_tracking_google.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- tracking: GOOGLE --> +<google> +<!-- enabled: specifies whether GOOGLE tracking will be sent --> + <enabled>true</enabled> + + <account>UA-7275490-5</account> + <visualDebug>false</visualDebug> + <trackingMode>AS3</trackingMode> + + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <trackPageView> + <URL>${data} Scorecard Nav</URL> + </trackPageView> + </trackHandler> + + <trackHandler> + <ID>track2</ID> + <trackEvent> + <category>LiveAt_videoevent1</category> + <action>o1</action> + <label>Mosiac Live Stream1</label> + <value>1</value> + </trackEvent> + </trackHandler> + + <trackHandler> + <ID>track3</ID> + <trackEvent> + <category>LiveAt_videoevent2</category> + <action>o2</action> + </trackEvent> + </trackHandler> + + + </trackHandlers> +</google> \ No newline at end of file diff --git a/test/test_tracking_javascript.xml b/test/test_tracking_javascript.xml new file mode 100644 index 0000000..b70bcea --- /dev/null +++ b/test/test_tracking_javascript.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- url TRACKING + defines a tracker that can ping URLs for a specific track request +--> +<JavaScript> + <!-- enabled: specifies whether url tracking will be sent --> + <enabled>true</enabled> + + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <methodCalls> + <methodCall> + <method>doJS</method> + <arguments> + <argument>1</argument> + <argument>2</argument> + <argument>3</argument> + </arguments> + </methodCall> + </methodCalls> + </trackHandler> + + </trackHandlers> +</JavaScript> \ No newline at end of file diff --git a/test/test_tracking_omniture.xml b/test/test_tracking_omniture.xml new file mode 100644 index 0000000..48a7ab6 --- /dev/null +++ b/test/test_tracking_omniture.xml @@ -0,0 +1,58 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- tracking: OMNITURE --> +<omniture> +<!-- enabled: specifies whether Omniture tracking will be sent --> + <enabled>true</enabled> + <!-- params: + allows you to generically assign values to all omniture values + NOTE: params set will be sent for every track + This can be use to set special props like <eVar23>pga_mosaic_player_09</eVar23> + --> + <params> + <account>foodotcom</account> + <dc>122</dc> + <delayTracking>2</delayTracking> + <trackingServer>stats.foo.com</trackingServer> + <visitorNameSpace>foo</visitorNameSpace> + <trackLocal>true</trackLocal> + </params> + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <trackLink> + <URL>LiveAt_videoevent</URL> + <type>o</type> + <name>Mosiac Live Stream</name> + <params> + <prop7>${data} Leaderboard Link</prop7> + <eVar7>${data} Leaderboard Link</eVar7> + </params> + </trackLink> + </trackHandler> + + <trackHandler> + <ID>track2</ID> + <trackLink> + <URL>LiveAt_videoevent</URL> + <type>o</type> + <name>Mosiac Live Stream</name> + <params> + <prop7>${data.id} Scorecard Search</prop7> + <eVar7>${data.id} Scorecard Search</eVar7> + <events>event14</events> + <eVar8>foo</eVar8> + </params> + </trackLink> + </trackHandler> + + <trackHandler> + <ID>track3</ID> + <track> + <params> + <eVar8>foo</eVar8> + <events>event17</events> + </params> + </track> + </trackHandler> + </trackHandlers> +</omniture> \ No newline at end of file diff --git a/test/test_tracking_url.xml b/test/test_tracking_url.xml new file mode 100644 index 0000000..b220456 --- /dev/null +++ b/test/test_tracking_url.xml @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- url TRACKING + defines a tracker that can ping URLs for a specific track request +--> +<URL> + <!-- enabled: specifies whether url tracking will be sent --> + <enabled>true</enabled> + + <!-- URL track handlers specify a way to respond to a specifically name track request + ID - specifies the specific named track request + URLs - specifies a list of URLs to ping for that specific track request + each URL is actually a template. + Therefore the URL can opt to use data which is specific to that named request. + This is done using a wrapper notation {data}, specifying the value be replaced by dynamic data. + For example: a mediaStarted request may be sent a media object. + This media object is represented by {data} in the template. + Thus a template of http://foo.com?{data.id} would replace {data.id} with the media's ID like http://foo.com?1234 + + --> + <trackHandlers> + <trackHandler> + <ID>track1</ID> + <URLs> + <URL>http://foo.com/track1.gif</URL> + </URLs> + </trackHandler> + + <trackHandler> + <ID>track2</ID> + <URLs> + <URL>http://foo.com/track2.gif?id=${data.id}</URL> + </URLs> + </trackHandler> + + <trackHandler> + <ID>track3</ID> + <URLs> + <URL>http://foo.com/track3.gif?id=${data}</URL> + </URLs> + </trackHandler> + </trackHandlers> +</URL> \ No newline at end of file
sunlightlabs/tcorps
f9fcf8f319c121b3d134e0cd3ee3738c8bf7a306
Finished updating deploy script for unicorn and new box
diff --git a/config/deploy.rb b/config/deploy.rb index b9aebed..e898650 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -1,61 +1,64 @@ -set :environment, (ENV['target'] || 'staging') +set :environment, (ENV['target'] || 'production') # Change repo and domain for your setup #if environment == 'production' set :domain, 'woodley.sunlightlabs.net' #else # set :domain, 'hammond.sunlightlabs.org' # end set :application, "tcorps_#{environment}" set :branch, 'master' set :user, 'tcorps' set :scm, :git set :repository, "[email protected]:sunlightlabs/tcorps.git" set :deploy_to, "/projects/tcorps/www/#{application}" set :deploy_via, :remote_cache role :app, domain role :web, domain set :sock, "#{user}.sock" set :runner, user set :admin_runner, runner +set :use_sudo, false after "deploy", "deploy:cleanup" +after "deploy:update_code", "deploy:shared_links" namespace :deploy do desc "Migrate the database" task :migrate, :roles => [:web, :app] do run "cd #{deploy_to}/current && rake db:migrate RAILS_ENV=#{environment}" deploy.restart end task :start do run "cd #{current_path} && unicorn -D -l #{shared_path}/#{sock}" end task :stop do run "killall unicorn" end desc "Restart the server" task :restart, :roles => :app, :except => {:no_release => true} do run "killall -HUP unicorn" end desc "Get shared files into position" - task :after_update_code, :roles => [:web, :app] do + task :shared_links, :roles => [:web, :app] do run "ln -nfs #{shared_path}/database.yml #{release_path}/config/database.yml" run "ln -nfs #{shared_path}/mailer.rb #{release_path}/config/initializers/mailer.rb" + run "ln -nfs #{shared_path}/system #{release_path}/public/system" end desc "Initial deploy" task :cold do deploy.update deploy.migrate end end \ No newline at end of file
sunlightlabs/tcorps
e02c114a4c2d27db87722e0d2b0d97ae31a6dd83
Tentative new deploy details
diff --git a/config/deploy.rb b/config/deploy.rb index f6722a7..b9aebed 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -1,51 +1,61 @@ set :environment, (ENV['target'] || 'staging') # Change repo and domain for your setup -if environment == 'production' - set :domain, 'belushi.sunlightlabs.org' -else - set :domain, 'hammond.sunlightlabs.org' -end +#if environment == 'production' + set :domain, 'woodley.sunlightlabs.net' +#else +# set :domain, 'hammond.sunlightlabs.org' +# end set :application, "tcorps_#{environment}" set :branch, 'master' set :user, 'tcorps' set :scm, :git set :repository, "[email protected]:sunlightlabs/tcorps.git" -set :deploy_to, "/home/tcorps/www/#{application}" +set :deploy_to, "/projects/tcorps/www/#{application}" set :deploy_via, :remote_cache role :app, domain role :web, domain - + +set :sock, "#{user}.sock" + set :runner, user set :admin_runner, runner after "deploy", "deploy:cleanup" namespace :deploy do - desc "Restart the server" - task :restart, :roles => [:web, :app] do - run "touch #{deploy_to}/current/tmp/restart.txt" - end - desc "Migrate the database" task :migrate, :roles => [:web, :app] do run "cd #{deploy_to}/current && rake db:migrate RAILS_ENV=#{environment}" deploy.restart end + task :start do + run "cd #{current_path} && unicorn -D -l #{shared_path}/#{sock}" + end + + task :stop do + run "killall unicorn" + end + + desc "Restart the server" + task :restart, :roles => :app, :except => {:no_release => true} do + run "killall -HUP unicorn" + end + desc "Get shared files into position" task :after_update_code, :roles => [:web, :app] do run "ln -nfs #{shared_path}/database.yml #{release_path}/config/database.yml" run "ln -nfs #{shared_path}/mailer.rb #{release_path}/config/initializers/mailer.rb" end desc "Initial deploy" task :cold do deploy.update deploy.migrate end end \ No newline at end of file
sunlightlabs/tcorps
2f10a32bfcec418760e381f2645aecc3ed83c0f0
Simplified contact form and made the from address the sender of the email
diff --git a/app/models/contact_mailer.rb b/app/models/contact_mailer.rb index bf9ceec..791db4e 100644 --- a/app/models/contact_mailer.rb +++ b/app/models/contact_mailer.rb @@ -1,10 +1,10 @@ class ContactMailer < ActionMailer::Base def contact_form(name, email, message) recipients '[email protected]' - from '[email protected]' + from email subject "[T-Corps] Contact form submission from #{name}" - body :name => name, :email => email, :message => message + body :message => message end end \ No newline at end of file diff --git a/app/views/contact_mailer/contact_form.erb b/app/views/contact_mailer/contact_form.erb index 193a0af..17a3d7c 100644 --- a/app/views/contact_mailer/contact_form.erb +++ b/app/views/contact_mailer/contact_form.erb @@ -1,3 +1 @@ -<%= @name %> (<%= @email %>) wrote: - <%= @message %> \ No newline at end of file
sunlightlabs/tcorps
82a67ae98e272250983320bbca56a5394e5fb94e
adding new avatar images and placing borders around avatar photos
diff --git a/public/images/avatar_female_normal.jpg b/public/images/avatar_female_normal.jpg index 8f818f2..24455ec 100644 Binary files a/public/images/avatar_female_normal.jpg and b/public/images/avatar_female_normal.jpg differ diff --git a/public/images/avatar_male_normal.jpg b/public/images/avatar_male_normal.jpg index efa42d7..ee1554d 100644 Binary files a/public/images/avatar_male_normal.jpg and b/public/images/avatar_male_normal.jpg differ diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 8592ba2..90457ca 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,325 +1,325 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#7b7373; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #9b9b9b; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} /*body.home div#ltColumn{ width: 492px;}*/ div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} /*body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;}*/ div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} /*body.home div#rtContent{ width: 306px; }*/ div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } /*body.home div#rtColumn{ margin-left: 0;}*/ h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left; width: 430px;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} form.edit_user input.file {width: 300px;} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #c0dee2; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.nav div.links {margin-top: 5px;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 99%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } -ol.leaders li img{ float: left; margin: 0 10px 20px 0;} +ol.leaders li img{ float: left; margin: 0 10px 20px 0; border: 2px solid #ECECED;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 0 0; border: 2px solid #ececed;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} div.withRSS h2 { width: 400px;} a.rssIcon { background: url(/images/rssIcon.png) top right no-repeat; text-indent: -9999em; display: block; width: 118px; height: 16px; float: left; margin-top: 10px;} \ No newline at end of file
sunlightlabs/tcorps
024ff67d62292b713a16d4eb6b3a8c5440e7d3aa
No deploy environment is using SQLite3, so don't need to manage the DB file in the deploy script anymore
diff --git a/config/deploy.rb b/config/deploy.rb index c7155e8..f6722a7 100644 --- a/config/deploy.rb +++ b/config/deploy.rb @@ -1,52 +1,51 @@ set :environment, (ENV['target'] || 'staging') # Change repo and domain for your setup if environment == 'production' set :domain, 'belushi.sunlightlabs.org' else set :domain, 'hammond.sunlightlabs.org' end set :application, "tcorps_#{environment}" set :branch, 'master' set :user, 'tcorps' set :scm, :git set :repository, "[email protected]:sunlightlabs/tcorps.git" set :deploy_to, "/home/tcorps/www/#{application}" set :deploy_via, :remote_cache role :app, domain role :web, domain set :runner, user set :admin_runner, runner after "deploy", "deploy:cleanup" namespace :deploy do desc "Restart the server" task :restart, :roles => [:web, :app] do run "touch #{deploy_to}/current/tmp/restart.txt" end desc "Migrate the database" task :migrate, :roles => [:web, :app] do run "cd #{deploy_to}/current && rake db:migrate RAILS_ENV=#{environment}" deploy.restart end desc "Get shared files into position" task :after_update_code, :roles => [:web, :app] do run "ln -nfs #{shared_path}/database.yml #{release_path}/config/database.yml" run "ln -nfs #{shared_path}/mailer.rb #{release_path}/config/initializers/mailer.rb" - run "ln -nfs #{shared_path}/#{environment}.sqlite3 #{release_path}/db/#{environment}.sqlite3" end desc "Initial deploy" task :cold do deploy.update deploy.migrate end end \ No newline at end of file
sunlightlabs/tcorps
996af32f9c453b9ebe47134633782092e6452667
Ignoring config/initializers/mailer.rb
diff --git a/.gitignore b/.gitignore index da61acc..91507c3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ tmp/* log/* config/database.yml +config/initializers/mailer.rb db/*.sqlite3 db/*.sql public/system/* .DS_Store
sunlightlabs/tcorps
779ba2ec93564ffd74f9a0bf2a4d7aa703a9d19e
Splitting out mailer.rb into an example file
diff --git a/README.md b/README.md index 68ec0b1..976cf34 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,57 @@ # TransparencyCorps TransparencyCorps is a volunteer-driven, decentralized microtask campaign platform. ## What does that mean? In fact, it's really more of an enhanced microtask directory, as no tasks are actually hosted inside TransparencyCorps. To keep a consistent user experience, TransparencyCorps will load these externally hosted tasks in an iframe, surrounded by a TransparencyCorps-branded bar, and the user will never appear to leave transparencycorps.org. Since TransparencyCorps is volunteer-driven, users who complete tasks are awarded points, and after accumulating certain amounts of points, can reach certain "levels". Users can upload avatars of themselves, and the most accomplished users are featured on the front page. Organizations who want to run a TransparencyCorps task will create a "Campaign". A campaign consists of some descriptive copy and HTML, the URL of their task application to land users at, and some basic parameters about how many times to run the task and how many points to award for completion. TransparencyCorps, and tasks built to interoperate with it, use a narrow, simple API (documented below) to communicate, and to award users points for completing these tasks. ## Managing a Campaign The campaign management area for TransparencyCorps is at transparencycorps.org/admin. A user will need to have been granted admin access by Sunlight Labs before this URL will be accessible. Once a user has been given access, they should see a link to the Admin area on the header bar, once they are logged in. Inside the campaign management area, a campaign manager can create, update, and delete campaigns (but only their own, obviously). Campaign ownership is given to a particular user; they cannot be jointly owned by more than one user account. Some basic statistics regarding that user's campaigns will be shown in a sidebar inside this area. + ## API The API has two parts - creating a new task, and completing a task. ### A New Task When the user asks for a new task from a campaign, an iframe is brought up within TransparencyCorps that will load up the campaign's URL for that task. This is a GET request, and a few parameters will be passed along in the query string: * task_key - This is a randomly generated unique key that the campaign application must keep throughout the user's interaction with the campaign. This key will be needed once the campaign is completed, to signal TransparencyCorps that the user should be awarded points. * username - The Transparency user's username. A campaign might use this to welcome the user by name. * points - The number of points that the user has accumulated towards this particular campaign. A campaign might use this to give harder tasks to more experienced users. An example URL might be: http://your-site.com/campaign?task_key=03bd230045e5bcd12e46e2e7c08dbdd4&username=freddy&points=150 Of course, campaigns should bear in mind that this URL can be spoofed, and so each of these parameters could be fake. In the future, we may introduce a mechanism to guarantee that each of these parameters comes directly from TransparencyCorps. For the time being, we have chosen simplicity over complete security, with the assumption that campaigns are comfortable with non-TransparencyCorps users participating in the work. If for some reason a campaign is given an invalid task key, there won't be any harm done in sending this task key to TransparencyCorps when the task is complete; but, no one will be getting any points. ### Completing a Task When a user completes a task on a campaign, that campaign should perform a POST to: http://transparencycorps.org/tasks/complete -The only parameter to send is "task_key", with the value being the task_key that was originally given as a parameter when the user first created their task. \ No newline at end of file +The only parameter to send is "task_key", with the value being the task_key that was originally given as a parameter when the user first created their task. + +## Developing Locally + +To set up this app to run locally: + +* copy config/initializers/mailer.rb.example to config/initializers/mailer.rb and fill in your mailer settings +* copy config/database.yml.example to config/database.yml and fill in your database settings +* run "rake db:schema:load" to initialize the database +* run "rake db:fixtures:load" to get a starting admin user account, with username/password: user1/test \ No newline at end of file diff --git a/config/initializers/mailer.rb.example b/config/initializers/mailer.rb.example new file mode 100644 index 0000000..17ec835 --- /dev/null +++ b/config/initializers/mailer.rb.example @@ -0,0 +1,8 @@ +ActionMailer::Base.smtp_settings = { + :address => '', + :port => 25, + :user_name => '', + :password => '', + :authentication => :plain, + :domain => '' +} \ No newline at end of file
sunlightlabs/tcorps
fec53dce91809e5ff500d69dcb0b6daaa991c34e
Added a 'Give Feedback' link to the task frame that links to the Contact page.
diff --git a/app/views/tasks/show.html.erb b/app/views/tasks/show.html.erb index 5416c7f..61007a2 100644 --- a/app/views/tasks/show.html.erb +++ b/app/views/tasks/show.html.erb @@ -1,24 +1,27 @@ <div class="header"> <div class="campaign"> <span class="title"> <%= h @task.campaign.name %> </span> <span class="instructions"> <%= simple_format @task.campaign.instructions %> </span> </div> <div class="nav"> <% form_tag tasks_path, :method => :post do %> <%= hidden_field_tag :campaign_id, @task.campaign.id %> <%= submit_tag "I'd Like Another Task", :id => 'anotherTask' %> <% end %> - <br/> - <a href="<%= root_path %>" class="back">Back to TransparencyCorps</a> + <div class="links"> + <a href="<%= root_path %>" class="back">Back to TransparencyCorps</a> + <br/> + <a href="<%= contact_path %>" class="back">Give Feedback</a> + </div> </div> <div class="clear"></div> </div> <iframe id="task_frame" name="task_frame" src="<%= remote_task_url @task, current_user %>"></iframe> \ No newline at end of file diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index cf6648d..8592ba2 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,324 +1,325 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#7b7373; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #9b9b9b; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} /*body.home div#ltColumn{ width: 492px;}*/ div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} /*body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;}*/ div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} /*body.home div#rtContent{ width: 306px; }*/ div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } /*body.home div#rtColumn{ margin-left: 0;}*/ h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left; width: 430px;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} form.edit_user input.file {width: 300px;} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #c0dee2; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} +body.task div.nav div.links {margin-top: 5px;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 99%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 0 0; border: 2px solid #ececed;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} div.withRSS h2 { width: 400px;} a.rssIcon { background: url(/images/rssIcon.png) top right no-repeat; text-indent: -9999em; display: block; width: 118px; height: 16px; float: left; margin-top: 10px;} \ No newline at end of file
sunlightlabs/tcorps
30d229fec1d1b99b47bd8150ffc6bba611c20aed
Margin fix to user avatars on sidebar
diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 29540f5..cf6648d 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,324 +1,324 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#7b7373; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #9b9b9b; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} /*body.home div#ltColumn{ width: 492px;}*/ div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} /*body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;}*/ div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} /*body.home div#rtContent{ width: 306px; }*/ div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } /*body.home div#rtColumn{ margin-left: 0;}*/ h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left; width: 430px;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} form.edit_user input.file {width: 300px;} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #c0dee2; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 99%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} -div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0; border: 2px solid #ececed;} +div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 0 0; border: 2px solid #ececed;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} div.withRSS h2 { width: 400px;} a.rssIcon { background: url(/images/rssIcon.png) top right no-repeat; text-indent: -9999em; display: block; width: 118px; height: 16px; float: left; margin-top: 10px;} \ No newline at end of file
sunlightlabs/tcorps
1d6f2bcdd22ccfb969bcc08719b47cc8af17bab0
cleaning up some styling things and adding rss link
diff --git a/app/views/campaigns/index.html.erb b/app/views/campaigns/index.html.erb index d86fca0..fa14c2e 100644 --- a/app/views/campaigns/index.html.erb +++ b/app/views/campaigns/index.html.erb @@ -1,10 +1,11 @@ <% content_for :class, :tasks %> <% content_for :header, :scoreboard %> <% content_for :hide_sidebar, true %> -<div class="mainTaskHeader"> +<div class="mainTaskHeader withRSS"> <h2>Tasks</h2> + <a class="rssIcon" href="http://transparencycorps.org/campaigns.xml">Keep up to Date</a> <div class="clear"></div> </div> <%= render :partial => 'campaigns/index', :locals => {:campaigns => @campaigns} %> \ No newline at end of file diff --git a/app/views/pages/index.html.erb b/app/views/pages/index.html.erb index 2ffe90b..0a2b427 100644 --- a/app/views/pages/index.html.erb +++ b/app/views/pages/index.html.erb @@ -1,10 +1,12 @@ <% content_for :class, :home %> <% content_for :header, :banner %> <% content_for :sidebar, :user_sidebar %> -<div class="mainTaskHeader"> - <h2>Welcome</h2> +<div class="mainTaskHeader withRSS"> + <h2>Latest Tasks</h2> + <a class="rssIcon" href="http://transparencycorps.org/campaigns.xml">Keep up to Date</a> <div class="clear"></div> </div> + <%= render :partial => 'campaigns/index', :locals => {:campaigns => @campaigns} %> \ No newline at end of file diff --git a/public/images/avatar_female_normal.jpg b/public/images/avatar_female_normal.jpg index 18722ae..8f818f2 100644 Binary files a/public/images/avatar_female_normal.jpg and b/public/images/avatar_female_normal.jpg differ diff --git a/public/images/avatar_male_normal.jpg b/public/images/avatar_male_normal.jpg index 71e57bb..efa42d7 100644 Binary files a/public/images/avatar_male_normal.jpg and b/public/images/avatar_male_normal.jpg differ diff --git a/public/images/rssIcon.png b/public/images/rssIcon.png new file mode 100644 index 0000000..09ea545 Binary files /dev/null and b/public/images/rssIcon.png differ diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 7788bc1..29540f5 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,322 +1,324 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ - color:#6c6d6e; + color:#7b7373; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } -div#ltColumn p { font-size: 108%; line-height: 21px;} - .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; - color: #848383; + color: #9b9b9b; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} -body.home div#ltColumn{ width: 492px;} +/*body.home div#ltColumn{ width: 492px;}*/ div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} -body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;} + +/*body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;}*/ div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} -body.home div#rtContent{ width: 306px; } +/*body.home div#rtContent{ width: 306px; }*/ div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } -body.home div#rtColumn{ margin-left: 0;} +/*body.home div#rtColumn{ margin-left: 0;}*/ h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left; width: 430px;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} form.edit_user input.file {width: 300px;} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} -div#footerBrand{ float: left; border-right: 1px solid #6c6b6b; margin-right: 15px; padding-right: 15px;} +div#footerBrand{ float: left; border-right: 1px solid #c0dee2; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 99%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} -div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0;} +div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0; border: 2px solid #ececed;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} -li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} \ No newline at end of file +li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} + +div.withRSS h2 { width: 400px;} +a.rssIcon { background: url(/images/rssIcon.png) top right no-repeat; text-indent: -9999em; display: block; width: 118px; height: 16px; float: left; margin-top: 10px;} \ No newline at end of file
sunlightlabs/tcorps
051a1f56ff26bc79d204452900b5f66d8d213739
Adding in a db dumping and loading helper
diff --git a/lib/tasks/yaml_db_tasks.rake b/lib/tasks/yaml_db_tasks.rake new file mode 100644 index 0000000..6851d44 --- /dev/null +++ b/lib/tasks/yaml_db_tasks.rake @@ -0,0 +1,23 @@ +namespace :db do + desc "Dump schema and data to db/schema.rb and db/data.yml" + task(:dump => [ "db:schema:dump", "db:data:dump" ]) + + desc "Load schema and data from db/schema.rb and db/data.yml" + task(:load => [ "db:schema:load", "db:data:load" ]) + + namespace :data do + def db_dump_data_file + "#{RAILS_ROOT}/db/data.yml" + end + + desc "Dump contents of database to db/data.yml" + task(:dump => :environment) do + YamlDb.dump db_dump_data_file + end + + desc "Load contents of db/data.yml into database" + task(:load => :environment) do + YamlDb.load db_dump_data_file + end + end +end diff --git a/lib/yaml_db.rb b/lib/yaml_db.rb new file mode 100644 index 0000000..1cd485e --- /dev/null +++ b/lib/yaml_db.rb @@ -0,0 +1,180 @@ +require 'rubygems' +require 'yaml' +require 'active_record' + + +module YamlDb + def self.dump(filename) + disable_logger + YamlDb::Dump.dump(File.new(filename, "w")) + reenable_logger + end + + def self.load(filename) + disable_logger + YamlDb::Load.load(File.new(filename, "r")) + reenable_logger + end + + def self.disable_logger + @@old_logger = ActiveRecord::Base.logger + ActiveRecord::Base.logger = nil + end + + def self.reenable_logger + ActiveRecord::Base.logger = @@old_logger + end +end + + +module YamlDb::Utils + def self.chunk_records(records) + yaml = [ records ].to_yaml + yaml.sub!("--- \n", "") + yaml.sub!('- - -', ' - -') + yaml + end + + def self.unhash(hash, keys) + keys.map { |key| hash[key] } + end + + def self.unhash_records(records, keys) + records.each_with_index do |record, index| + records[index] = unhash(record, keys) + end + + records + end + + def self.convert_booleans(records, columns) + records.each do |record| + columns.each do |column| + next if is_boolean(record[column]) + record[column] = (record[column] == 't' or record[column] == '1') + end + end + records + end + + def self.boolean_columns(table) + columns = ActiveRecord::Base.connection.columns(table).reject { |c| c.type != :boolean } + columns.map { |c| c.name } + end + + def self.is_boolean(value) + value.kind_of?(TrueClass) or value.kind_of?(FalseClass) + end + + def self.quote_table(table) + ActiveRecord::Base.connection.quote_table_name(table) + end +end + + +module YamlDb::Dump + def self.dump(io) + tables.each do |table| + dump_table(io, table) + end + end + + def self.tables + ActiveRecord::Base.connection.tables.reject { |table| ['schema_info', 'schema_migrations'].include?(table) } + end + + def self.dump_table(io, table) + return if table_record_count(table).zero? + + dump_table_columns(io, table) + dump_table_records(io, table) + end + + def self.dump_table_columns(io, table) + io.write("\n") + io.write({ table => { 'columns' => table_column_names(table) } }.to_yaml) + end + + def self.dump_table_records(io, table) + table_record_header(io) + + column_names = table_column_names(table) + + each_table_page(table) do |records| + rows = YamlDb::Utils.unhash_records(records, column_names) + io.write(YamlDb::Utils.chunk_records(records)) + end + end + + def self.table_record_header(io) + io.write(" records: \n") + end + + def self.table_column_names(table) + ActiveRecord::Base.connection.columns(table).map { |c| c.name } + end + + def self.each_table_page(table, records_per_page=1000) + total_count = table_record_count(table) + pages = (total_count.to_f / records_per_page).ceil - 1 + id = table_column_names(table).first + boolean_columns = YamlDb::Utils.boolean_columns(table) + quoted_table_name = YamlDb::Utils.quote_table(table) + + (0..pages).to_a.each do |page| + sql = ActiveRecord::Base.connection.add_limit_offset!("SELECT * FROM #{quoted_table_name} ORDER BY #{id}", + :limit => records_per_page, :offset => records_per_page * page + ) + records = ActiveRecord::Base.connection.select_all(sql) + records = YamlDb::Utils.convert_booleans(records, boolean_columns) + yield records + end + end + + def self.table_record_count(table) + ActiveRecord::Base.connection.select_one("SELECT COUNT(*) FROM #{YamlDb::Utils.quote_table(table)}").values.first.to_i + end +end + + +module YamlDb::Load + def self.load(io) + ActiveRecord::Base.connection.transaction do + YAML.load_documents(io) do |ydoc| + ydoc.keys.each do |table_name| + next if ydoc[table_name].nil? + load_table(table_name, ydoc[table_name]) + end + end + end + end + + def self.truncate_table(table) + begin + ActiveRecord::Base.connection.execute("TRUNCATE #{YamlDb::Utils.quote_table(table)}") + rescue Exception + ActiveRecord::Base.connection.execute("DELETE FROM #{YamlDb::Utils.quote_table(table)}") + end + end + + def self.load_table(table, data) + column_names = data['columns'] + truncate_table(table) + load_records(table, column_names, data['records']) + reset_pk_sequence!(table) + end + + def self.load_records(table, column_names, records) + quoted_column_names = column_names.map { |column| ActiveRecord::Base.connection.quote_column_name(column) }.join(',') + quoted_table_name = YamlDb::Utils.quote_table(table) + records.each do |record| + ActiveRecord::Base.connection.execute("INSERT INTO #{quoted_table_name} (#{quoted_column_names}) VALUES (#{record.map { |r| ActiveRecord::Base.connection.quote(r) }.join(',')})") + end + end + + def self.reset_pk_sequence!(table_name) + if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!) + ActiveRecord::Base.connection.reset_pk_sequence!(table_name) + end + end +end
sunlightlabs/tcorps
6e92eafcd879b9e0b0feb4dd8c8faac186467923
Whitespace
diff --git a/app/controllers/admin/campaigns_controller.rb b/app/controllers/admin/campaigns_controller.rb index 36425b0..78d7c08 100644 --- a/app/controllers/admin/campaigns_controller.rb +++ b/app/controllers/admin/campaigns_controller.rb @@ -1,64 +1,64 @@ class Admin::CampaignsController < ApplicationController layout 'admin' skip_before_filter :load_sidebar before_filter :require_login before_filter :require_manager before_filter :load_campaign, :only => [:edit, :update, :confirm_destroy, :destroy] def index @campaigns = current_user.campaigns.all(:order => 'created_at DESC') end def new @campaign = current_user.campaigns.new :points => RECOMMENDED_CAMPAIGN_POINTS end def create @campaign = current_user.campaigns.new params[:campaign] if @campaign.save deliver_campaign_notifications @campaign flash[:success] = 'Campaign created.' redirect_to admin_campaigns_path else render :action => :new end end def edit end def update if @campaign.update_attributes params[:campaign] flash[:success] = 'Your campaign has been updated.' redirect_to admin_campaigns_path else render :action => :edit end end def confirm_destroy end def destroy @campaign.destroy flash[:success] = 'Your campaign has been deleted.' redirect_to admin_campaigns_path end protected def load_campaign unless @campaign = Campaign.find_by_id(params[:id]) and @campaign.creator == current_user redirect_to root_path and return false end end def deliver_campaign_notifications(campaign) (User.campaign_subscribers.all - [campaign.creator]).each do |user| - CampaignMailer.deliver_new_campaign(campaign, user) + CampaignMailer.deliver_new_campaign campaign, user end end end \ No newline at end of file
sunlightlabs/tcorps
3567a276b24ebd6ea4a6864136035ca574bdc5ad
Lightly narrowed the iframe, to avoid a horizontal scrollbar
diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index c2ae5c5..7788bc1 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,322 +1,322 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#6c6d6e; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } div#ltColumn p { font-size: 108%; line-height: 21px;} .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #848383; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} body.home div#ltColumn{ width: 492px;} div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;} div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} body.home div#rtContent{ width: 306px; } div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } body.home div#rtColumn{ margin-left: 0;} h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left; width: 430px;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} form.edit_user input.file {width: 300px;} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #6c6b6b; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } -iframe#task_frame {width: 100%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} +iframe#task_frame {width: 99%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} \ No newline at end of file
sunlightlabs/tcorps
6e21238a9b2da76dea191ec8af6ab2990a330d91
Scoped elvolunteer man-hours count to campaigns belonging to logged in user
diff --git a/app/models/user.rb b/app/models/user.rb index c3847a4..02a93bd 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,67 +1,71 @@ class User < ActiveRecord::Base attr_accessible :login, :email, :openid_identifier, :password, :password_confirmation, :avatar, :subscribe_campaigns, :subscribe_all has_many :tasks has_many :campaigns, :foreign_key => :creator_id has_attached_file :avatar, :styles => {:normal => '64x64#', :tiny => '24x24#'}, :default_url => "/images/avatar_:gender_:style.jpg" named_scope :by_points, :select => 'users.*, (select sum(tasks.points) as sum_points from tasks where completed_at is not null and tasks.user_id = users.id) as sum_points', :order => 'sum_points desc' named_scope :leaders, lambda { {:conditions => ['sum_points >= ?', LEVELS.keys.sort.first]} } named_scope :participants, :select => 'users.*, (select count(*) from tasks where completed_at is not null and tasks.user_id = users.id) as num_tasks', :conditions => 'num_tasks > 0' named_scope :participants_in, lambda {|campaign| { :select => "users.*, (select count(*) from tasks where completed_at is not null and campaign_id = #{campaign.id} and tasks.user_id = users.id) as num_tasks", :conditions => 'num_tasks > 0' }} named_scope :campaign_subscribers, :conditions => ['subscribe_campaigns = ?', true] acts_as_authentic def total_points tasks.sum :points, :conditions => 'completed_at is not null' end def campaign_points(campaign) tasks.sum :points, :conditions => ['completed_at is not null and campaign_id = ?', campaign.id] end def campaigns_completed_tasks_count - campaigns.all.map {|c| c.tasks.completed.count}.sum + campaigns.all.map {|campaign| campaign.tasks.completed.count}.sum end def campaigns_percent_complete - completed = campaigns.all.map {|c| c.tasks.completed.count}.sum + completed = campaigns.all.map {|campaign| campaign.tasks.completed.count}.sum runs = campaigns.sum(:runs).to_f runs <= 0 ? 0 : ((completed / runs) * 100).to_i end def campaigns_participants_count - campaigns.all.map {|c| User.participants_in(c)}.flatten.uniq.size + campaigns.all.map {|campaign| User.participants_in campaign}.flatten.uniq.size + end + + def campaigns_elapsed_seconds + campaigns.all.map {|campaign| campaign.tasks.sum :elapsed_seconds}.sum end def manager? !organization_name.blank? end def level points = respond_to?(:sum_points) ? sum_points.to_i : total_points levels = LEVELS.keys.sort level = 0 levels.each_with_index do |minimum, i| level = i + 1 if points >= minimum end level end Paperclip.interpolates :gender do |attachment, style| [:female, :male][rand 2] end end \ No newline at end of file diff --git a/app/views/layouts/partials/_stats.html.erb b/app/views/layouts/partials/_stats.html.erb index 5e90bfa..a5f48da 100644 --- a/app/views/layouts/partials/_stats.html.erb +++ b/app/views/layouts/partials/_stats.html.erb @@ -1,19 +1,19 @@ <h3>Stats</h3> <ul> <li> <span><%= current_user.campaigns_percent_complete %>%</span> <p>all tasks complete</p> </li> <li> <span><%= current_user.campaigns_participants_count %></span> <p>people participating</p> </li> <li> <span><%= current_user.campaigns_completed_tasks_count %></span> <p>tasks completed</p> </li> <li> - <span><%= to_hours Task.sum(:elapsed_seconds) %></span> + <span><%= to_hours current_user.campaigns_elapsed_seconds %></span> <p>hours spent on tasks</p> </li> </ul> \ No newline at end of file diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index 729e362..18ccb48 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -1,193 +1,213 @@ require 'test_helper' class UserTest < ActiveSupport::TestCase + test '#campaigns_elapsed_seconds returns total elapsed seconds of completed tasks for the campaigns belonging to this user' do + admin1 = Factory :user + admin2 = Factory :user + campaign_one = Factory :campaign, :creator => admin1 + campaign_two = Factory :campaign, :creator => admin1 + campaign_three = Factory :campaign, :creator => admin2 + campaign_four = Factory :campaign, :creator => admin2 + user1 = Factory :user + user2 = Factory :user + + Factory :completed_task, :campaign => campaign_one, :user => user1, :elapsed_seconds => 2 + Factory :completed_task, :campaign => campaign_two, :user => user1, :elapsed_seconds => 2 + Factory :completed_task, :campaign => campaign_three, :user => user1, :elapsed_seconds => 2 + Factory :completed_task, :campaign => campaign_three, :user => user2, :elapsed_seconds => 2 + Factory :completed_task, :campaign => campaign_four, :user => user2, :elapsed_seconds => 2 + + assert_equal 4, admin1.campaigns_elapsed_seconds + assert_equal 6, admin2.campaigns_elapsed_seconds + end + test '#campaigns_completed_tasks_count returns number of completed tasks for the campaigns belonging to this user' do admin1 = Factory :user admin2 = Factory :user campaign_one = Factory :campaign, :creator => admin1 campaign_two = Factory :campaign, :creator => admin1 campaign_three = Factory :campaign, :creator => admin2 campaign_four = Factory :campaign, :creator => admin2 user1 = Factory :user user2 = Factory :user Factory :completed_task, :campaign => campaign_one, :user => user1 Factory :completed_task, :campaign => campaign_two, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user2 Factory :completed_task, :campaign => campaign_four, :user => user2 assert_equal 2, admin1.campaigns_completed_tasks_count assert_equal 3, admin2.campaigns_completed_tasks_count end test '#campaigns_participants_count returns number of participating users in the campaigns belonging to this user' do admin1 = Factory :user admin2 = Factory :user campaign_one = Factory :campaign, :creator => admin1 campaign_two = Factory :campaign, :creator => admin1 campaign_three = Factory :campaign, :creator => admin2 campaign_four = Factory :campaign, :creator => admin2 user1 = Factory :user user2 = Factory :user Factory :completed_task, :campaign => campaign_one, :user => user1 Factory :completed_task, :campaign => campaign_one, :user => user1 Factory :completed_task, :campaign => campaign_two, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user2 Factory :completed_task, :campaign => campaign_four, :user => user2 assert_equal 1, admin1.campaigns_participants_count assert_equal 2, admin2.campaigns_participants_count end test '#campaigns_percent_complete calculates percent complete of all campaigns together' do user = Factory :user campaign_one = Factory :campaign, :creator => user, :runs => 4 campaign_two = Factory :campaign, :creator => user, :runs => 4 campaign_three = Factory :campaign, :creator => user, :runs => 2 Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_three Factory :completed_task, :campaign => campaign_three assert_equal 0, campaign_one.percent_complete assert_equal 75, campaign_two.percent_complete assert_equal 100, campaign_three.percent_complete assert_equal 50, user.campaigns_percent_complete end test '#by_points includes points as an attribute on user and sorts on this attribute' do user1 = Factory :user user2 = Factory :user user3 = Factory :user campaign_one = Factory :campaign, :creator => user1, :points => 1 campaign_two = Factory :campaign, :creator => user2, :points => 2 campaign_three = Factory :campaign, :creator => user3, :points => 4 campaign_four = Factory :campaign, :creator => user3, :points => 8 Factory :completed_task, :campaign => campaign_one, :user => user3 Factory :completed_task, :campaign => campaign_two, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user2 Factory :completed_task, :campaign => campaign_four, :user => user2 assert_equal [user2, user1, user3], User.by_points.all assert_nothing_raised do assert_equal 12, User.by_points.first.sum_points.to_i end end test '#participants only returns people who have at least one completed task' do no_tasks = Factory :user only_uncompleted_tasks = Factory :user only_completed_tasks = Factory :user some_of_both = Factory :user Factory :task, :user => only_uncompleted_tasks Factory :task, :user => only_uncompleted_tasks Factory :task, :user => some_of_both Factory :task, :user => some_of_both Factory :completed_task, :user => only_completed_tasks Factory :completed_task, :user => only_completed_tasks Factory :completed_task, :user => some_of_both Factory :completed_task, :user => some_of_both participants = User.participants.all assert_equal 2, participants.size assert !participants.include?(no_tasks) assert !participants.include?(only_uncompleted_tasks) assert participants.include?(only_completed_tasks) assert participants.include?(some_of_both) end test '#leaders only returns people who are at least level 1' do minimum = LEVELS.keys.sort.first user1 = Factory :user user2 = Factory :user user3 = Factory :user campaign_one = Factory :campaign, :creator => user1, :points => minimum - 1 campaign_two = Factory :campaign, :creator => user1, :points => minimum campaign_three = Factory :campaign, :creator => user1, :points => minimum + 1 Factory :completed_task, :campaign => campaign_one, :user => user1 Factory :completed_task, :campaign => campaign_two, :user => user2 Factory :completed_task, :campaign => campaign_three, :user => user3 assert_equal [user3, user2], User.by_points.leaders.all end test '#total_points counts tasks from all campaigns' do user = Factory :user assert_equal 0, user.total_points campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 Factory :completed_task, :campaign => campaign_one, :user => user Factory :completed_task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 7, user.total_points end test '#total_points counts only completed tasks' do user = Factory :user assert_equal 0, user.total_points campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 Factory :completed_task, :campaign => campaign_one, :user => user Factory :task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 5, user.total_points end test '#campaign_points counts tasks from one campaign' do user = Factory :user campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 assert_equal 0, user.campaign_points(campaign_one) assert_equal 0, user.campaign_points(campaign_two) assert_equal 0, user.campaign_points(campaign_three) Factory :completed_task, :campaign => campaign_one, :user => user Factory :completed_task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 1, user.campaign_points(campaign_one) assert_equal 2, user.campaign_points(campaign_two) assert_equal 4, user.campaign_points(campaign_three) end test '#campaign_points counts only completed tasks' do user = Factory :user campaign = Factory :campaign, :points => 1 assert_equal 0, user.campaign_points(campaign) Factory :completed_task, :campaign => campaign, :user => user Factory :completed_task, :campaign => campaign, :user => user Factory :task, :campaign => campaign, :user => user assert_equal 2, user.campaign_points(campaign) end test '#manager? depends on presence of organization name' do assert Factory(:user, :organization_name => 'any name').manager? assert !Factory(:user, :organization_name => nil).manager? assert !Factory(:user, :admin => true, :organization_name => nil).manager? end end \ No newline at end of file
sunlightlabs/tcorps
e27f5479d28352e96db67bd4625bf9027a67104d
Scoped the completed task count for a campaign to the logged in user's campaigns
diff --git a/app/models/user.rb b/app/models/user.rb index d74558f..c3847a4 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,63 +1,67 @@ class User < ActiveRecord::Base attr_accessible :login, :email, :openid_identifier, :password, :password_confirmation, :avatar, :subscribe_campaigns, :subscribe_all has_many :tasks has_many :campaigns, :foreign_key => :creator_id has_attached_file :avatar, :styles => {:normal => '64x64#', :tiny => '24x24#'}, :default_url => "/images/avatar_:gender_:style.jpg" named_scope :by_points, :select => 'users.*, (select sum(tasks.points) as sum_points from tasks where completed_at is not null and tasks.user_id = users.id) as sum_points', :order => 'sum_points desc' named_scope :leaders, lambda { {:conditions => ['sum_points >= ?', LEVELS.keys.sort.first]} } named_scope :participants, :select => 'users.*, (select count(*) from tasks where completed_at is not null and tasks.user_id = users.id) as num_tasks', :conditions => 'num_tasks > 0' named_scope :participants_in, lambda {|campaign| { :select => "users.*, (select count(*) from tasks where completed_at is not null and campaign_id = #{campaign.id} and tasks.user_id = users.id) as num_tasks", :conditions => 'num_tasks > 0' }} named_scope :campaign_subscribers, :conditions => ['subscribe_campaigns = ?', true] acts_as_authentic def total_points tasks.sum :points, :conditions => 'completed_at is not null' end def campaign_points(campaign) tasks.sum :points, :conditions => ['completed_at is not null and campaign_id = ?', campaign.id] end + def campaigns_completed_tasks_count + campaigns.all.map {|c| c.tasks.completed.count}.sum + end + def campaigns_percent_complete completed = campaigns.all.map {|c| c.tasks.completed.count}.sum runs = campaigns.sum(:runs).to_f runs <= 0 ? 0 : ((completed / runs) * 100).to_i end def campaigns_participants_count campaigns.all.map {|c| User.participants_in(c)}.flatten.uniq.size end def manager? !organization_name.blank? end def level points = respond_to?(:sum_points) ? sum_points.to_i : total_points levels = LEVELS.keys.sort level = 0 levels.each_with_index do |minimum, i| level = i + 1 if points >= minimum end level end Paperclip.interpolates :gender do |attachment, style| [:female, :male][rand 2] end end \ No newline at end of file diff --git a/app/views/layouts/partials/_stats.html.erb b/app/views/layouts/partials/_stats.html.erb index 158dbfd..5e90bfa 100644 --- a/app/views/layouts/partials/_stats.html.erb +++ b/app/views/layouts/partials/_stats.html.erb @@ -1,19 +1,19 @@ <h3>Stats</h3> <ul> <li> <span><%= current_user.campaigns_percent_complete %>%</span> <p>all tasks complete</p> </li> <li> <span><%= current_user.campaigns_participants_count %></span> <p>people participating</p> </li> <li> - <span><%= Task.completed.count %></span> + <span><%= current_user.campaigns_completed_tasks_count %></span> <p>tasks completed</p> </li> <li> <span><%= to_hours Task.sum(:elapsed_seconds) %></span> <p>hours spent on tasks</p> </li> </ul> \ No newline at end of file diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index e8854a4..729e362 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -1,173 +1,193 @@ require 'test_helper' class UserTest < ActiveSupport::TestCase - + + test '#campaigns_completed_tasks_count returns number of completed tasks for the campaigns belonging to this user' do + admin1 = Factory :user + admin2 = Factory :user + campaign_one = Factory :campaign, :creator => admin1 + campaign_two = Factory :campaign, :creator => admin1 + campaign_three = Factory :campaign, :creator => admin2 + campaign_four = Factory :campaign, :creator => admin2 + user1 = Factory :user + user2 = Factory :user + + Factory :completed_task, :campaign => campaign_one, :user => user1 + Factory :completed_task, :campaign => campaign_two, :user => user1 + Factory :completed_task, :campaign => campaign_three, :user => user1 + Factory :completed_task, :campaign => campaign_three, :user => user2 + Factory :completed_task, :campaign => campaign_four, :user => user2 + + assert_equal 2, admin1.campaigns_completed_tasks_count + assert_equal 3, admin2.campaigns_completed_tasks_count + end + test '#campaigns_participants_count returns number of participating users in the campaigns belonging to this user' do admin1 = Factory :user admin2 = Factory :user campaign_one = Factory :campaign, :creator => admin1 campaign_two = Factory :campaign, :creator => admin1 campaign_three = Factory :campaign, :creator => admin2 campaign_four = Factory :campaign, :creator => admin2 user1 = Factory :user user2 = Factory :user Factory :completed_task, :campaign => campaign_one, :user => user1 Factory :completed_task, :campaign => campaign_one, :user => user1 Factory :completed_task, :campaign => campaign_two, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user2 Factory :completed_task, :campaign => campaign_four, :user => user2 assert_equal 1, admin1.campaigns_participants_count assert_equal 2, admin2.campaigns_participants_count end test '#campaigns_percent_complete calculates percent complete of all campaigns together' do user = Factory :user campaign_one = Factory :campaign, :creator => user, :runs => 4 campaign_two = Factory :campaign, :creator => user, :runs => 4 campaign_three = Factory :campaign, :creator => user, :runs => 2 Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_three Factory :completed_task, :campaign => campaign_three assert_equal 0, campaign_one.percent_complete assert_equal 75, campaign_two.percent_complete assert_equal 100, campaign_three.percent_complete assert_equal 50, user.campaigns_percent_complete end test '#by_points includes points as an attribute on user and sorts on this attribute' do user1 = Factory :user user2 = Factory :user user3 = Factory :user campaign_one = Factory :campaign, :creator => user1, :points => 1 campaign_two = Factory :campaign, :creator => user2, :points => 2 campaign_three = Factory :campaign, :creator => user3, :points => 4 campaign_four = Factory :campaign, :creator => user3, :points => 8 Factory :completed_task, :campaign => campaign_one, :user => user3 Factory :completed_task, :campaign => campaign_two, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user2 Factory :completed_task, :campaign => campaign_four, :user => user2 assert_equal [user2, user1, user3], User.by_points.all assert_nothing_raised do assert_equal 12, User.by_points.first.sum_points.to_i end end test '#participants only returns people who have at least one completed task' do no_tasks = Factory :user only_uncompleted_tasks = Factory :user only_completed_tasks = Factory :user some_of_both = Factory :user Factory :task, :user => only_uncompleted_tasks Factory :task, :user => only_uncompleted_tasks Factory :task, :user => some_of_both Factory :task, :user => some_of_both Factory :completed_task, :user => only_completed_tasks Factory :completed_task, :user => only_completed_tasks Factory :completed_task, :user => some_of_both Factory :completed_task, :user => some_of_both participants = User.participants.all assert_equal 2, participants.size assert !participants.include?(no_tasks) assert !participants.include?(only_uncompleted_tasks) assert participants.include?(only_completed_tasks) assert participants.include?(some_of_both) end test '#leaders only returns people who are at least level 1' do minimum = LEVELS.keys.sort.first user1 = Factory :user user2 = Factory :user user3 = Factory :user campaign_one = Factory :campaign, :creator => user1, :points => minimum - 1 campaign_two = Factory :campaign, :creator => user1, :points => minimum campaign_three = Factory :campaign, :creator => user1, :points => minimum + 1 Factory :completed_task, :campaign => campaign_one, :user => user1 Factory :completed_task, :campaign => campaign_two, :user => user2 Factory :completed_task, :campaign => campaign_three, :user => user3 assert_equal [user3, user2], User.by_points.leaders.all end test '#total_points counts tasks from all campaigns' do user = Factory :user assert_equal 0, user.total_points campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 Factory :completed_task, :campaign => campaign_one, :user => user Factory :completed_task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 7, user.total_points end test '#total_points counts only completed tasks' do user = Factory :user assert_equal 0, user.total_points campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 Factory :completed_task, :campaign => campaign_one, :user => user Factory :task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 5, user.total_points end test '#campaign_points counts tasks from one campaign' do user = Factory :user campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 assert_equal 0, user.campaign_points(campaign_one) assert_equal 0, user.campaign_points(campaign_two) assert_equal 0, user.campaign_points(campaign_three) Factory :completed_task, :campaign => campaign_one, :user => user Factory :completed_task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 1, user.campaign_points(campaign_one) assert_equal 2, user.campaign_points(campaign_two) assert_equal 4, user.campaign_points(campaign_three) end test '#campaign_points counts only completed tasks' do user = Factory :user campaign = Factory :campaign, :points => 1 assert_equal 0, user.campaign_points(campaign) Factory :completed_task, :campaign => campaign, :user => user Factory :completed_task, :campaign => campaign, :user => user Factory :task, :campaign => campaign, :user => user assert_equal 2, user.campaign_points(campaign) end test '#manager? depends on presence of organization name' do assert Factory(:user, :organization_name => 'any name').manager? assert !Factory(:user, :organization_name => nil).manager? assert !Factory(:user, :admin => true, :organization_name => nil).manager? end end \ No newline at end of file
sunlightlabs/tcorps
1d7af7e25024eec10090967e9165339b22825f37
Scoped participant count to logged in user's campaigns
diff --git a/app/models/user.rb b/app/models/user.rb index b6d0091..d74558f 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,58 +1,63 @@ class User < ActiveRecord::Base attr_accessible :login, :email, :openid_identifier, :password, :password_confirmation, :avatar, :subscribe_campaigns, :subscribe_all has_many :tasks has_many :campaigns, :foreign_key => :creator_id has_attached_file :avatar, :styles => {:normal => '64x64#', :tiny => '24x24#'}, :default_url => "/images/avatar_:gender_:style.jpg" named_scope :by_points, :select => 'users.*, (select sum(tasks.points) as sum_points from tasks where completed_at is not null and tasks.user_id = users.id) as sum_points', :order => 'sum_points desc' named_scope :leaders, lambda { {:conditions => ['sum_points >= ?', LEVELS.keys.sort.first]} } named_scope :participants, :select => 'users.*, (select count(*) from tasks where completed_at is not null and tasks.user_id = users.id) as num_tasks', :conditions => 'num_tasks > 0' named_scope :participants_in, lambda {|campaign| { :select => "users.*, (select count(*) from tasks where completed_at is not null and campaign_id = #{campaign.id} and tasks.user_id = users.id) as num_tasks", :conditions => 'num_tasks > 0' }} named_scope :campaign_subscribers, :conditions => ['subscribe_campaigns = ?', true] acts_as_authentic def total_points tasks.sum :points, :conditions => 'completed_at is not null' end def campaign_points(campaign) tasks.sum :points, :conditions => ['completed_at is not null and campaign_id = ?', campaign.id] end def campaigns_percent_complete completed = campaigns.all.map {|c| c.tasks.completed.count}.sum - ((completed / campaigns.sum(:runs).to_f) * 100).to_i + runs = campaigns.sum(:runs).to_f + runs <= 0 ? 0 : ((completed / runs) * 100).to_i + end + + def campaigns_participants_count + campaigns.all.map {|c| User.participants_in(c)}.flatten.uniq.size end def manager? !organization_name.blank? end def level points = respond_to?(:sum_points) ? sum_points.to_i : total_points levels = LEVELS.keys.sort level = 0 levels.each_with_index do |minimum, i| level = i + 1 if points >= minimum end level end Paperclip.interpolates :gender do |attachment, style| [:female, :male][rand 2] end end \ No newline at end of file diff --git a/app/views/layouts/partials/_stats.html.erb b/app/views/layouts/partials/_stats.html.erb index c79b910..158dbfd 100644 --- a/app/views/layouts/partials/_stats.html.erb +++ b/app/views/layouts/partials/_stats.html.erb @@ -1,19 +1,19 @@ <h3>Stats</h3> <ul> <li> <span><%= current_user.campaigns_percent_complete %>%</span> <p>all tasks complete</p> </li> <li> - <span><%= User.participants.all.size %></span> + <span><%= current_user.campaigns_participants_count %></span> <p>people participating</p> </li> <li> <span><%= Task.completed.count %></span> <p>tasks completed</p> </li> <li> <span><%= to_hours Task.sum(:elapsed_seconds) %></span> <p>hours spent on tasks</p> </li> </ul> \ No newline at end of file diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index ddded1f..e8854a4 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -1,152 +1,173 @@ require 'test_helper' class UserTest < ActiveSupport::TestCase + test '#campaigns_participants_count returns number of participating users in the campaigns belonging to this user' do + admin1 = Factory :user + admin2 = Factory :user + campaign_one = Factory :campaign, :creator => admin1 + campaign_two = Factory :campaign, :creator => admin1 + campaign_three = Factory :campaign, :creator => admin2 + campaign_four = Factory :campaign, :creator => admin2 + user1 = Factory :user + user2 = Factory :user + + Factory :completed_task, :campaign => campaign_one, :user => user1 + Factory :completed_task, :campaign => campaign_one, :user => user1 + Factory :completed_task, :campaign => campaign_two, :user => user1 + Factory :completed_task, :campaign => campaign_three, :user => user1 + Factory :completed_task, :campaign => campaign_three, :user => user2 + Factory :completed_task, :campaign => campaign_four, :user => user2 + + assert_equal 1, admin1.campaigns_participants_count + assert_equal 2, admin2.campaigns_participants_count + end + test '#campaigns_percent_complete calculates percent complete of all campaigns together' do user = Factory :user campaign_one = Factory :campaign, :creator => user, :runs => 4 campaign_two = Factory :campaign, :creator => user, :runs => 4 campaign_three = Factory :campaign, :creator => user, :runs => 2 Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_two Factory :completed_task, :campaign => campaign_three Factory :completed_task, :campaign => campaign_three assert_equal 0, campaign_one.percent_complete assert_equal 75, campaign_two.percent_complete assert_equal 100, campaign_three.percent_complete assert_equal 50, user.campaigns_percent_complete end test '#by_points includes points as an attribute on user and sorts on this attribute' do user1 = Factory :user user2 = Factory :user user3 = Factory :user campaign_one = Factory :campaign, :creator => user1, :points => 1 campaign_two = Factory :campaign, :creator => user2, :points => 2 campaign_three = Factory :campaign, :creator => user3, :points => 4 campaign_four = Factory :campaign, :creator => user3, :points => 8 Factory :completed_task, :campaign => campaign_one, :user => user3 Factory :completed_task, :campaign => campaign_two, :user => user1 Factory :completed_task, :campaign => campaign_three, :user => user2 Factory :completed_task, :campaign => campaign_four, :user => user2 assert_equal [user2, user1, user3], User.by_points.all assert_nothing_raised do assert_equal 12, User.by_points.first.sum_points.to_i end end test '#participants only returns people who have at least one completed task' do no_tasks = Factory :user only_uncompleted_tasks = Factory :user only_completed_tasks = Factory :user some_of_both = Factory :user Factory :task, :user => only_uncompleted_tasks Factory :task, :user => only_uncompleted_tasks Factory :task, :user => some_of_both Factory :task, :user => some_of_both Factory :completed_task, :user => only_completed_tasks Factory :completed_task, :user => only_completed_tasks Factory :completed_task, :user => some_of_both Factory :completed_task, :user => some_of_both participants = User.participants.all assert_equal 2, participants.size assert !participants.include?(no_tasks) assert !participants.include?(only_uncompleted_tasks) assert participants.include?(only_completed_tasks) assert participants.include?(some_of_both) end test '#leaders only returns people who are at least level 1' do minimum = LEVELS.keys.sort.first user1 = Factory :user user2 = Factory :user user3 = Factory :user campaign_one = Factory :campaign, :creator => user1, :points => minimum - 1 campaign_two = Factory :campaign, :creator => user1, :points => minimum campaign_three = Factory :campaign, :creator => user1, :points => minimum + 1 Factory :completed_task, :campaign => campaign_one, :user => user1 Factory :completed_task, :campaign => campaign_two, :user => user2 Factory :completed_task, :campaign => campaign_three, :user => user3 assert_equal [user3, user2], User.by_points.leaders.all end test '#total_points counts tasks from all campaigns' do user = Factory :user assert_equal 0, user.total_points campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 Factory :completed_task, :campaign => campaign_one, :user => user Factory :completed_task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 7, user.total_points end test '#total_points counts only completed tasks' do user = Factory :user assert_equal 0, user.total_points campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 Factory :completed_task, :campaign => campaign_one, :user => user Factory :task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 5, user.total_points end test '#campaign_points counts tasks from one campaign' do user = Factory :user campaign_one = Factory :campaign, :points => 1 campaign_two = Factory :campaign, :points => 2 campaign_three = Factory :campaign, :points => 4 assert_equal 0, user.campaign_points(campaign_one) assert_equal 0, user.campaign_points(campaign_two) assert_equal 0, user.campaign_points(campaign_three) Factory :completed_task, :campaign => campaign_one, :user => user Factory :completed_task, :campaign => campaign_two, :user => user Factory :completed_task, :campaign => campaign_three, :user => user assert_equal 1, user.campaign_points(campaign_one) assert_equal 2, user.campaign_points(campaign_two) assert_equal 4, user.campaign_points(campaign_three) end test '#campaign_points counts only completed tasks' do user = Factory :user campaign = Factory :campaign, :points => 1 assert_equal 0, user.campaign_points(campaign) Factory :completed_task, :campaign => campaign, :user => user Factory :completed_task, :campaign => campaign, :user => user Factory :task, :campaign => campaign, :user => user assert_equal 2, user.campaign_points(campaign) end test '#manager? depends on presence of organization name' do assert Factory(:user, :organization_name => 'any name').manager? assert !Factory(:user, :organization_name => nil).manager? assert !Factory(:user, :admin => true, :organization_name => nil).manager? end end \ No newline at end of file
sunlightlabs/tcorps
15071364d823f8560946edaaee81c5953a1ff682
Fixed an out of date attribute name
diff --git a/test/factories.rb b/test/factories.rb index 1cca56b..a48d165 100644 --- a/test/factories.rb +++ b/test/factories.rb @@ -1,44 +1,44 @@ require 'factory_girl' Factory.define :task do |t| t.association :user t.association :campaign end Factory.define :completed_task, :parent => :task do |t| t.completed_at {Time.now} end Factory.define :campaign do |c| c.association :creator, :factory => :manager c.name {Factory.next :campaign_name} c.keyword {Factory.next :campaign_keyword} c.url {|a| "http://example.com/#{a.keyword}"} c.instructions 'Instructions' c.description 'Public description' - c.private_description 'Private description' + c.short_description 'Private description' c.points 5 c.runs 100 c.user_runs 100 c.start_at {2.days.ago} end Factory.sequence(:campaign_keyword) {|i| "campaign#{i}"} Factory.sequence(:campaign_name) {|i| "Campaign #{i}"} Factory.define :user do |u| u.login {Factory.next :user_login} u.email {Factory.next :user_email} u.password 'test' u.password_confirmation 'test' end Factory.sequence(:user_login) {|i| "user#{i}"} Factory.sequence(:user_email) {|i| "user#{i}@example.com"} Factory.define :manager, :parent => :user do |u| u.organization_name 'Organization Name' end Factory.define :admin, :parent => :user do |u| u.admin true end \ No newline at end of file
sunlightlabs/tcorps
19904e1d6c02a377aec4d6b8d2f459bf14a8d1e4
Fixed a failing functional test
diff --git a/test/functional/pages_controller_test.rb b/test/functional/pages_controller_test.rb index fefee5a..c9d5a8e 100644 --- a/test/functional/pages_controller_test.rb +++ b/test/functional/pages_controller_test.rb @@ -1,97 +1,98 @@ require 'test_helper' class PagesControllerTest < ActionController::TestCase setup :activate_authlogic test '#index loads the most recent 5 users' do user = Factory :user + User.any_instance.expects(:sum_points).returns 0 User.expects(:by_points).returns User User.expects(:all).with(:limit => 5).returns [Factory(:user)] get :index end test '#index loads all active campaigns' do Campaign.expects(:active).returns Campaign get :index assert_response :success assert_template 'index' end test '#index loads all active campaigns relevant to the logged in user, if the user is logged in' do user = Factory :user Campaign.expects(:active_for).with(user).returns Campaign login user get :index end # every page should have these campaigns for the sidebar, but we'll just test it here test '#about loads the most recent 5 active campaigns for the sidebar' do Campaign.expects(:active).returns Campaign get :about end test '#about loads the most recent 5 active campaigns for the logged in user for the sidebar, if logged in' do user = Factory :user Campaign.expects(:active_for).with(user).returns Campaign login user get :about end test '#contact with post and all data sends contact form email' do name = 'name' email = 'email' message = 'message' ContactMailer.expects(:deliver_contact_form).with(name, email, message) post :contact, :name => name, :email => email, :message => message assert_redirected_to contact_path assert_not_nil flash[:success] end test '#contact with post requires name' do name = 'name' email = 'email' message = 'message' ContactMailer.expects(:deliver_contact_form).never post :contact, :email => email, :message => message assert_response :success assert_template 'contact' assert_not_nil assigns(:error_messages) end test '#contact with post requires email' do name = 'name' email = 'email' message = 'message' ContactMailer.expects(:deliver_contact_form).never post :contact, :name => name, :message => message assert_response :success assert_template 'contact' assert_not_nil assigns(:error_messages) end test '#contact with post requires message' do name = 'name' email = 'email' message = 'message' ContactMailer.expects(:deliver_contact_form).never post :contact, :name => name, :email => email assert_response :success assert_template 'contact' assert_not_nil assigns(:error_messages) end test 'page routes' do [:about, :contact].each do |page| assert_routing "/#{page}", :controller => 'pages', :action => page.to_s end assert_routing '/', :controller => 'pages', :action => 'index' end end
sunlightlabs/tcorps
df5dd10d518672b70303a7db370f8645ffdc8024
Added a named_scope for users who participated in a specific campaign
diff --git a/app/models/user.rb b/app/models/user.rb index 4beedb3..2f98ce6 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,49 +1,53 @@ class User < ActiveRecord::Base attr_accessible :login, :email, :openid_identifier, :password, :password_confirmation, :avatar, :subscribe_campaigns, :subscribe_all has_many :tasks has_many :campaigns, :foreign_key => :creator_id has_attached_file :avatar, :styles => {:normal => '64x64#', :tiny => '24x24#'}, :default_url => "/images/avatar_:gender_:style.jpg" named_scope :by_points, :select => 'users.*, (select sum(tasks.points) as sum_points from tasks where completed_at is not null and tasks.user_id = users.id) as sum_points', :order => 'sum_points desc' named_scope :leaders, lambda { {:conditions => ['sum_points >= ?', LEVELS.keys.sort.first]} } named_scope :participants, :select => 'users.*, (select count(*) from tasks where completed_at is not null and tasks.user_id = users.id) as num_tasks', :conditions => 'num_tasks > 0' + named_scope :participants_in, lambda {|campaign| { + :select => "users.*, (select count(*) from tasks where completed_at is not null and campaign_id = #{campaign.id} and tasks.user_id = users.id) as num_tasks", + :conditions => 'num_tasks > 0' + }} named_scope :campaign_subscribers, :conditions => ['subscribe_campaigns = ?', true] acts_as_authentic def total_points tasks.sum :points, :conditions => 'completed_at is not null' end def campaign_points(campaign) tasks.sum :points, :conditions => ['completed_at is not null and campaign_id = ?', campaign.id] end def manager? !organization_name.blank? end def level points = respond_to?(:sum_points) ? sum_points.to_i : total_points levels = LEVELS.keys.sort level = 0 levels.each_with_index do |minimum, i| level = i + 1 if points >= minimum end level end Paperclip.interpolates :gender do |attachment, style| [:female, :male][rand 2] end end \ No newline at end of file
sunlightlabs/tcorps
b849017702662eb879b3d2490a9b8ad8ffca1b95
CSS class wasn't being applied to dropdown
diff --git a/app/views/admin/campaigns/_form.html.erb b/app/views/admin/campaigns/_form.html.erb index 54120dd..eaac828 100644 --- a/app/views/admin/campaigns/_form.html.erb +++ b/app/views/admin/campaigns/_form.html.erb @@ -1,50 +1,50 @@ <ul> <li> <%= f.label :name %> <%= f.text_field :name, :class => 'text' %> </li> <li> <%= f.label :url %> <%= f.text_field :url, :class => 'text' %> </li> <li> <label for="campaign[short_description]">Short Description</label> <%= f.text_area :short_description, :class => 'textarea', :cols => 32, :rows => 5 %> </li> <li> <label for="campaign[description]">Description</label> <%= f.text_area :description, :class => 'textarea', :cols => 32, :rows => 5 %> </li> <li> <label for="campaign[points]">Points Per Task</label> - <%= f.select :points, 1..9, :class => 'pointsDropdown' %> + <%= f.select :points, 1..9, {}, {:class => 'pointsDropdown'} %> <% if_javascript do %> <span> <a href="#" onclick="$('#campaign_points').val('<%= RECOMMENDED_CAMPAIGN_POINTS %>'); return false"> Recommended Number of Points </a> </span> <% end %> </li> <li> <label for="campaign[instructions]">Task Instructions</label> <%= f.text_area :instructions, :class => 'textarea', :cols => '32', :rows => '5' %> </li> <li> <label for="campaign[start_at]">Start</label> <%= f.datetime_select :start_at, :prompt => true, :twelve_hour => true %> <% if_javascript do %> <%= link_to 'Now', '#', :onclick => 'setToNow("campaign", "start_at"); return false' %> <% end %> </li> <li> <label for="campaign[runs]">Times to Run Task</label> <%= f.text_field :runs, :class => 'text' %> </li> <li> <label for="campaign[user_runs]">Runs Per User </label> <%= f.text_field :user_runs, :class => 'text' %> </li> </ul> \ No newline at end of file
sunlightlabs/tcorps
88c570c1106745d8fa5c6bc4f6f58ad30ffc4f41
Let strong tags be strong, and em tags have emphasis
diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 7ff0a9c..c2ae5c5 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,322 +1,322 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ -body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} +body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#6c6d6e; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } div#ltColumn p { font-size: 108%; line-height: 21px;} .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #848383; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} body.home div#ltColumn{ width: 492px;} div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;} div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} body.home div#rtContent{ width: 306px; } div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } body.home div#rtColumn{ margin-left: 0;} h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left; width: 430px;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} form.edit_user input.file {width: 300px;} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #6c6b6b; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 100%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} \ No newline at end of file
sunlightlabs/tcorps
c21ab19785a1a7025b1d868baf7380d994467a31
Added a README that documents the TransparencyCorps API.
diff --git a/README b/README index e69de29..68ec0b1 100644 --- a/README +++ b/README @@ -0,0 +1,47 @@ +# TransparencyCorps + +TransparencyCorps is a volunteer-driven, decentralized microtask campaign platform. + +## What does that mean? + +In fact, it's really more of an enhanced microtask directory, as no tasks are actually hosted inside TransparencyCorps. To keep a consistent user experience, TransparencyCorps will load these externally hosted tasks in an iframe, surrounded by a TransparencyCorps-branded bar, and the user will never appear to leave transparencycorps.org. + +Since TransparencyCorps is volunteer-driven, users who complete tasks are awarded points, and after accumulating certain amounts of points, can reach certain "levels". Users can upload avatars of themselves, and the most accomplished users are featured on the front page. + +Organizations who want to run a TransparencyCorps task will create a "Campaign". A campaign consists of some descriptive copy and HTML, the URL of their task application to land users at, and some basic parameters about how many times to run the task and how many points to award for completion. + +TransparencyCorps, and tasks built to interoperate with it, use a narrow, simple API (documented below) to communicate, and to award users points for completing these tasks. + +## Managing a Campaign + +The campaign management area for TransparencyCorps is at transparencycorps.org/admin. A user will need to have been granted admin access by Sunlight Labs before this URL will be accessible. Once a user has been given access, they should see a link to the Admin area on the header bar, once they are logged in. + +Inside the campaign management area, a campaign manager can create, update, and delete campaigns (but only their own, obviously). Campaign ownership is given to a particular user; they cannot be jointly owned by more than one user account. Some basic statistics regarding that user's campaigns will be shown in a sidebar inside this area. + +## API + +The API has two parts - creating a new task, and completing a task. + +### A New Task + +When the user asks for a new task from a campaign, an iframe is brought up within TransparencyCorps that will load up the campaign's URL for that task. This is a GET request, and a few parameters will be passed along in the query string: + +* task_key - This is a randomly generated unique key that the campaign application must keep throughout the user's interaction with the campaign. This key will be needed once the campaign is completed, to signal TransparencyCorps that the user should be awarded points. +* username - The Transparency user's username. A campaign might use this to welcome the user by name. +* points - The number of points that the user has accumulated towards this particular campaign. A campaign might use this to give harder tasks to more experienced users. + +An example URL might be: + +http://your-site.com/campaign?task_key=03bd230045e5bcd12e46e2e7c08dbdd4&username=freddy&points=150 + +Of course, campaigns should bear in mind that this URL can be spoofed, and so each of these parameters could be fake. In the future, we may introduce a mechanism to guarantee that each of these parameters comes directly from TransparencyCorps. For the time being, we have chosen simplicity over complete security, with the assumption that campaigns are comfortable with non-TransparencyCorps users participating in the work. + +If for some reason a campaign is given an invalid task key, there won't be any harm done in sending this task key to TransparencyCorps when the task is complete; but, no one will be getting any points. + +### Completing a Task + +When a user completes a task on a campaign, that campaign should perform a POST to: + +http://transparencycorps.org/tasks/complete + +The only parameter to send is "task_key", with the value being the task_key that was originally given as a parameter when the user first created their task. \ No newline at end of file
sunlightlabs/tcorps
52dc01fe73f39f6d418b64a6256406422a2416db
Zero prefixing elapsed time summary
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 2f1ec3a..b7ca642 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,40 +1,44 @@ module ApplicationHelper def is_home?(body_class) [nil, :home].include? body_class end def errors(object) render :partial => 'layouts/partials/errors', :locals => {:object => object} end def period(string) string << (string.last == '.' ? '' : '.') end def open_id_return? params[:open_id_complete] == '1' end def to_word(number) { 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine', 10 => 'Ten' }[number] || number end def to_minutes(seconds) - "#{seconds / 60}:#{seconds % 60}" + "#{zero_prefix(seconds / 60)}:#{zero_prefix(seconds % 60)}" end def to_hours(seconds) - "#{(seconds / 3600).to_i}:#{(seconds % 3600) / 60}" + "#{zero_prefix((seconds / 3600).to_i)}:#{zero_prefix((seconds % 3600) / 60)}" + end + + def zero_prefix(n) + "#{0 if n < 10}#{n}" end end \ No newline at end of file
sunlightlabs/tcorps
cfc9a197864e4f91db6e9d324a3e95556160e166
gave task h3 titles a width
diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 6af2b9f..7ff0a9c 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,322 +1,322 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#6c6d6e; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } div#ltColumn p { font-size: 108%; line-height: 21px;} .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #848383; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} body.home div#ltColumn{ width: 492px;} div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;} div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} body.home div#rtContent{ width: 306px; } div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } body.home div#rtColumn{ margin-left: 0;} h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} -ul#taskList h3 { font-size: 150%; float: left;} +ul#taskList h3 { font-size: 150%; float: left; width: 430px;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} form.edit_user input.file {width: 300px;} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #6c6b6b; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 100%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} \ No newline at end of file
sunlightlabs/tcorps
85cee47c21e7b06baa2703a56858a7fcda9cadcf
Made checkboxes work
diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb index bea9f59..53e46bc 100644 --- a/app/views/users/edit.html.erb +++ b/app/views/users/edit.html.erb @@ -1,48 +1,50 @@ <div class="mainTaskHeader"> <h2>Edit Profile</h2> <div class="clear"></div> </div> <% form_for @user, :html => {:multipart => true} do |f| %> <%= errors @user %> <ul> <li> <label for='username'>Username</label> <%= f.text_field :login, :id => 'username', :class => 'text', :size => '32' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text', :size => '32' %> </li> <li> <%= f.label :password %> <%= f.password_field :password, :class => 'text', :size => '32' %> </li> <li> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation, :class => 'text', :size => '32' %> </li> <li> <label for='avatar'>Current Avatar</label> <%= image_tag @user.avatar.url(:normal) %> </li> <li> <label for='user_avatar'>Upload a new avatar</label> <%= f.file_field :avatar, :class => 'file' %> </li> <li class="checkboxIndent"> - <input type="hidden" value="0" name="user[subscribe_campaigns]"/> - <label class="subscribe_label" for="user_subscribe_campaigns"><input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> - Email me when there's a new campaign</label> + <label class="subscribe_label" for="user_subscribe_campaigns"> + <%= f.check_box :subscribe_campaigns, :id => 'user_subscribe_campaigns' %> + Email me when there's a new campaign + </label> </li> <li class="checkboxIndent"> - <input type="hidden" value="0" name="user[subscribe_all]"/> - <label class="subscribe_label" for="user_subscribe_all"><input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> - Email me about other Sunlight services</label> + <label class="subscribe_label" for="user_subscribe_all"> + <%= f.check_box :subscribe_all, :id => 'user_subscribe_all' %> + Email me about other Sunlight services + </label> </li> <input type="submit" value="Update" name="commit" id="update_button" /> </ul> <% end %> diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb index cc728fa..57ebe91 100644 --- a/app/views/users/new.html.erb +++ b/app/views/users/new.html.erb @@ -1,134 +1,138 @@ <% content_for :class, :signup %> <div class="mainTaskHeader"> <h2>Join Us</h2> <div class="clear"></div> </div> <p class="join">Already have an account? <%= link_to 'Sign in!', login_path %></p> <p>Join the cause, by signing up for Transparency Corps with one of the options below.</p> <div id="signup_nav" class="nav"> <ul> <li id="nav_standard" class="active"><a href="#">Standard Sign Up</a></li> <!-- <li id="nav_aol"><a href="#">AOL</a></li> <li id="nav_yahoo"><a href="#">Yahoo</a></li> <li id="nav_google"><a href="#">Google</a></li> <li id="nav_facebook"><a href="#">Facebook</a></li> --> <li id="nav_openid"><a href="#">OpenID</a></li> </ul> <div class="clear"></div> </div> <div id="signup_options"> <%= errors @user %> <div id="signup_standard" class="signup_option"> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> <%= f.text_field :login, :class => 'text' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text' %> </li> <li> <%= f.label :password %> <%= f.password_field :password, :class => 'text' %> </li> <li> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation, :class => 'text' %> </li> <li class="checkboxIndent"> - <input type="hidden" value="0" name="user[subscribe_campaigns]"/> - <label class="subscribe_label" for="user_subscribe_campaigns"><input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> - Email me when there's a new campaign</label> + <label class="subscribe_label" for="user_subscribe_campaigns"> + <%= f.check_box :subscribe_campaigns, :id => 'user_subscribe_campaigns' %> + Email me when there's a new campaign + </label> </li> <li class="checkboxIndent"> - <input type="hidden" value="0" name="user[subscribe_all]"/> - <label class="subscribe_label" for="user_subscribe_all"><input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> - Email me about other Sunlight services</label> + <label class="subscribe_label" for="user_subscribe_all"> + <%= f.check_box :subscribe_all, :id => 'user_subscribe_all' %> + Email me about other Sunlight services + </label> </li> </ul> <%= f.submit 'Register' %> <% end %> </div> <div id="signup_aol" class="signup_option" style="display: none"> <h3>Sign up using your AOL account.</h3> <p class="tip">Clicking this button will take you to AOL to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="aolBtn" type="submit"> <span>Sign Up Using AOL</span> </button> </div> <div id="signup_yahoo" class="signup_option" style="display: none"> <h3>Sign up using your Yahoo account.</h3> <p class="tip">Clicking this button will take you to Yahoo to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="yahooBtn" type="submit"> <span>Sign Up Using Yahoo</span> </button> </div> <div id="signup_google" class="signup_option" style="display: none"> <h3>Sign up using your Google account.</h3> <p class="tip">Clicking this button will take you to Google to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="googleBtn" type="submit"> <span>Sign Up Using Google</span> </button> </div> <div id="signup_facebook" class="signup_option" style="display: none"> <h3>Sign up using your Facebook account.</h3> <p class="tip">Clicking this button will take you to Facebook to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="facebookBtn" type="submit"> <span>Sign Up Using Facebook</span> </button> </div> <div id="signup_openid" class="signup_option" style="display: none"> <h3>Sign up using your OpenID account.</h3> <p class="tip">Clicking this button will take you to OpenID to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> <%= f.text_field :login, :class => 'text' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text' %> </li> <li> <label for="user_openid_identifier">OpenID</label> <%= f.text_field :openid_identifier, :value => @user.openid_identifier.blank? ? 'http://' : @user.openid_identifier, :class => 'text' %> </li> <li class="checkboxIndent"> - <input type="hidden" value="0" name="user[subscribe_campaigns]"/> - <label class="subscribe_label" for="user_subscribe_campaigns2"><input id="user_subscribe_campaigns2" type="checkbox" value="1" name="user[subscribe_campaigns]"/> - Email me when there's a new campaign</label> + <label class="subscribe_label" for="user_subscribe_campaigns"> + <%= f.check_box :subscribe_campaigns, :id => 'user_subscribe_campaigns2' %> + Email me when there's a new campaign + </label> </li> <li class="checkboxIndent"> - <input type="hidden" value="0" name="user[subscribe_all]"/> - <label class="subscribe_label" for="user_subscribe_all2"><input id="user_subscribe_all2" type="checkbox" value="1" name="user[subscribe_all]"/> - Email me about other Sunlight services</label> + <label class="subscribe_label" for="user_subscribe_all"> + <%= f.check_box :subscribe_all, :id => 'user_subscribe_all2' %> + Email me about other Sunlight services + </label> </li> </ul> <button class="openidBtn" type="submit"> <span>Sign Up Using OpenID</span> </button> <% end %> </div> </div> <% if open_id_return? %> <% javascript_tag do %> switch_nav('openid', 'signup'); <% end %> <% end %> \ No newline at end of file
sunlightlabs/tcorps
51f5ac9b73bfe9c4df98f8fd2e74b592bd8b1459
Finally fixed last problem around adding these checkboxes
diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb index 60c0262..bea9f59 100644 --- a/app/views/users/edit.html.erb +++ b/app/views/users/edit.html.erb @@ -1,48 +1,48 @@ <div class="mainTaskHeader"> <h2>Edit Profile</h2> <div class="clear"></div> </div> <% form_for @user, :html => {:multipart => true} do |f| %> <%= errors @user %> <ul> <li> <label for='username'>Username</label> <%= f.text_field :login, :id => 'username', :class => 'text', :size => '32' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text', :size => '32' %> </li> <li> <%= f.label :password %> <%= f.password_field :password, :class => 'text', :size => '32' %> </li> <li> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation, :class => 'text', :size => '32' %> </li> <li> <label for='avatar'>Current Avatar</label> <%= image_tag @user.avatar.url(:normal) %> </li> <li> <label for='user_avatar'>Upload a new avatar</label> - <%= f.file_field :avatar %> + <%= f.file_field :avatar, :class => 'file' %> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_campaigns]"/> <label class="subscribe_label" for="user_subscribe_campaigns"><input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> Email me when there's a new campaign</label> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_all]"/> <label class="subscribe_label" for="user_subscribe_all"><input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> Email me about other Sunlight services</label> </li> <input type="submit" value="Update" name="commit" id="update_button" /> </ul> <% end %> diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 25769b2..6af2b9f 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,321 +1,322 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#6c6d6e; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } div#ltColumn p { font-size: 108%; line-height: 21px;} .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #848383; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} body.home div#ltColumn{ width: 492px;} div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;} div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} body.home div#rtContent{ width: 306px; } div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } body.home div#rtColumn{ margin-left: 0;} h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} +form.edit_user input.file {width: 300px;} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #6c6b6b; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 100%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} \ No newline at end of file
sunlightlabs/tcorps
db1bf471e34677654f60ab2584bcc81eb5964da3
putting label tags around check box text
diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb index 9d60c22..60c0262 100644 --- a/app/views/users/edit.html.erb +++ b/app/views/users/edit.html.erb @@ -1,48 +1,48 @@ <div class="mainTaskHeader"> <h2>Edit Profile</h2> <div class="clear"></div> </div> <% form_for @user, :html => {:multipart => true} do |f| %> <%= errors @user %> <ul> <li> <label for='username'>Username</label> <%= f.text_field :login, :id => 'username', :class => 'text', :size => '32' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text', :size => '32' %> </li> <li> <%= f.label :password %> <%= f.password_field :password, :class => 'text', :size => '32' %> </li> <li> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation, :class => 'text', :size => '32' %> </li> <li> <label for='avatar'>Current Avatar</label> <%= image_tag @user.avatar.url(:normal) %> </li> <li> <label for='user_avatar'>Upload a new avatar</label> <%= f.file_field :avatar %> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_campaigns]"/> - <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> - Email me when there's a new campaign + <label class="subscribe_label" for="user_subscribe_campaigns"><input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> + Email me when there's a new campaign</label> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_all]"/> - <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> - Email me about other Sunlight services + <label class="subscribe_label" for="user_subscribe_all"><input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> + Email me about other Sunlight services</label> </li> <input type="submit" value="Update" name="commit" id="update_button" /> </ul> <% end %> diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb index d8d8b2a..cc728fa 100644 --- a/app/views/users/new.html.erb +++ b/app/views/users/new.html.erb @@ -1,134 +1,134 @@ <% content_for :class, :signup %> <div class="mainTaskHeader"> <h2>Join Us</h2> <div class="clear"></div> </div> <p class="join">Already have an account? <%= link_to 'Sign in!', login_path %></p> <p>Join the cause, by signing up for Transparency Corps with one of the options below.</p> <div id="signup_nav" class="nav"> <ul> <li id="nav_standard" class="active"><a href="#">Standard Sign Up</a></li> <!-- <li id="nav_aol"><a href="#">AOL</a></li> <li id="nav_yahoo"><a href="#">Yahoo</a></li> <li id="nav_google"><a href="#">Google</a></li> <li id="nav_facebook"><a href="#">Facebook</a></li> --> <li id="nav_openid"><a href="#">OpenID</a></li> </ul> <div class="clear"></div> </div> <div id="signup_options"> <%= errors @user %> <div id="signup_standard" class="signup_option"> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> <%= f.text_field :login, :class => 'text' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text' %> </li> <li> <%= f.label :password %> <%= f.password_field :password, :class => 'text' %> </li> <li> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation, :class => 'text' %> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_campaigns]"/> - <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> - Email me when there's a new campaign + <label class="subscribe_label" for="user_subscribe_campaigns"><input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> + Email me when there's a new campaign</label> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_all]"/> - <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> - Email me about other Sunlight services + <label class="subscribe_label" for="user_subscribe_all"><input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> + Email me about other Sunlight services</label> </li> </ul> <%= f.submit 'Register' %> <% end %> </div> <div id="signup_aol" class="signup_option" style="display: none"> <h3>Sign up using your AOL account.</h3> <p class="tip">Clicking this button will take you to AOL to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="aolBtn" type="submit"> <span>Sign Up Using AOL</span> </button> </div> <div id="signup_yahoo" class="signup_option" style="display: none"> <h3>Sign up using your Yahoo account.</h3> <p class="tip">Clicking this button will take you to Yahoo to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="yahooBtn" type="submit"> <span>Sign Up Using Yahoo</span> </button> </div> <div id="signup_google" class="signup_option" style="display: none"> <h3>Sign up using your Google account.</h3> <p class="tip">Clicking this button will take you to Google to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="googleBtn" type="submit"> <span>Sign Up Using Google</span> </button> </div> <div id="signup_facebook" class="signup_option" style="display: none"> <h3>Sign up using your Facebook account.</h3> <p class="tip">Clicking this button will take you to Facebook to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="facebookBtn" type="submit"> <span>Sign Up Using Facebook</span> </button> </div> <div id="signup_openid" class="signup_option" style="display: none"> <h3>Sign up using your OpenID account.</h3> <p class="tip">Clicking this button will take you to OpenID to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> <%= f.text_field :login, :class => 'text' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text' %> </li> <li> <label for="user_openid_identifier">OpenID</label> <%= f.text_field :openid_identifier, :value => @user.openid_identifier.blank? ? 'http://' : @user.openid_identifier, :class => 'text' %> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_campaigns]"/> - <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> - Email me when there's a new campaign + <label class="subscribe_label" for="user_subscribe_campaigns2"><input id="user_subscribe_campaigns2" type="checkbox" value="1" name="user[subscribe_campaigns]"/> + Email me when there's a new campaign</label> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_all]"/> - <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> - Email me about other Sunlight services + <label class="subscribe_label" for="user_subscribe_all2"><input id="user_subscribe_all2" type="checkbox" value="1" name="user[subscribe_all]"/> + Email me about other Sunlight services</label> </li> </ul> <button class="openidBtn" type="submit"> <span>Sign Up Using OpenID</span> </button> <% end %> </div> </div> <% if open_id_return? %> <% javascript_tag do %> switch_nav('openid', 'signup'); <% end %> <% end %> \ No newline at end of file diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 716ca9b..25769b2 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,319 +1,321 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#6c6d6e; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } div#ltColumn p { font-size: 108%; line-height: 21px;} .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #848383; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} body.home div#ltColumn{ width: 492px;} div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;} div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} body.home div#rtContent{ width: 306px; } div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } body.home div#rtColumn{ margin-left: 0;} h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} +div#ltColumn label.subscribe_label { float: none; width: 300px; font-weight: normal;} + form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #6c6b6b; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 100%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} \ No newline at end of file
sunlightlabs/tcorps
fb8d7f7faf87b3153280f4d500302a30807ea51b
Renamed internal descriiption to short description, and placed on the sidebar display of campaigns
diff --git a/app/views/admin/campaigns/_form.html.erb b/app/views/admin/campaigns/_form.html.erb index 1175aa0..54120dd 100644 --- a/app/views/admin/campaigns/_form.html.erb +++ b/app/views/admin/campaigns/_form.html.erb @@ -1,50 +1,50 @@ <ul> <li> <%= f.label :name %> <%= f.text_field :name, :class => 'text' %> </li> <li> <%= f.label :url %> <%= f.text_field :url, :class => 'text' %> </li> <li> - <label for="campaign[private_description]">Internal Description</label> - <%= f.text_area :private_description, :class => 'textarea', :cols => 32, :rows => 5 %> + <label for="campaign[short_description]">Short Description</label> + <%= f.text_area :short_description, :class => 'textarea', :cols => 32, :rows => 5 %> </li> <li> - <label for="campaign[description]">External Description</label> + <label for="campaign[description]">Description</label> <%= f.text_area :description, :class => 'textarea', :cols => 32, :rows => 5 %> </li> <li> <label for="campaign[points]">Points Per Task</label> <%= f.select :points, 1..9, :class => 'pointsDropdown' %> <% if_javascript do %> <span> <a href="#" onclick="$('#campaign_points').val('<%= RECOMMENDED_CAMPAIGN_POINTS %>'); return false"> Recommended Number of Points </a> </span> <% end %> </li> <li> <label for="campaign[instructions]">Task Instructions</label> <%= f.text_area :instructions, :class => 'textarea', :cols => '32', :rows => '5' %> </li> <li> <label for="campaign[start_at]">Start</label> <%= f.datetime_select :start_at, :prompt => true, :twelve_hour => true %> <% if_javascript do %> <%= link_to 'Now', '#', :onclick => 'setToNow("campaign", "start_at"); return false' %> <% end %> </li> <li> <label for="campaign[runs]">Times to Run Task</label> <%= f.text_field :runs, :class => 'text' %> </li> <li> <label for="campaign[user_runs]">Runs Per User </label> <%= f.text_field :user_runs, :class => 'text' %> </li> </ul> \ No newline at end of file diff --git a/app/views/admin/campaigns/index.html.erb b/app/views/admin/campaigns/index.html.erb index cac1ad4..8692250 100644 --- a/app/views/admin/campaigns/index.html.erb +++ b/app/views/admin/campaigns/index.html.erb @@ -1,40 +1,40 @@ <div id="editTask_header"> <h2>My Campaign</h2> </div> <% @campaigns.each do |campaign| %> <div class="task"> <% if_javascript do %> <%= link_to 'Delete Campaign', admin_campaign_path(campaign), :method => :delete, :confirm => 'Are you sure you want to delete this campaign?', :class => 'deleteTask' %> <% end %> <% no_javascript do %> <%= link_to 'Delete Campaign', confirm_destroy_admin_campaign_path(:id => campaign), :class => 'deleteTask' %> <% end %> <div class="taskMain"> <h3> <%= link_to h(campaign.name), edit_admin_campaign_path(campaign) %> </h3> <p> - <%= h campaign.private_description %> + <%= h campaign.short_description %> </p> </div> <div class="taskStatus"> <!-- <select name="Status" class="statusDropdown"> <option value="Draft">Draft</option> <option value="Public">Public</option> <option value="Closed">Closed</option> </select> --> <div class="taskComplete"> <span> <%= campaign.percent_complete %>% </span> <p>complete</p> </div> </div> <div class="clear"></div> </div> <% end %> \ No newline at end of file diff --git a/app/views/layouts/partials/_sidebar.html.erb b/app/views/layouts/partials/_sidebar.html.erb index eb7208a..beaef1d 100644 --- a/app/views/layouts/partials/_sidebar.html.erb +++ b/app/views/layouts/partials/_sidebar.html.erb @@ -1,30 +1,30 @@ <h3><%= yield(:sidebar_title) || "Get Started by Choosing <br/>a Task Below" %></h3> <ul> <% campaigns.each do |campaign| %> <li> <div class="taskTop"> <div class="taskHeader"> <h4><%= link_to h(campaign.name), campaign_path(campaign) %></h4> <div class="taskMetadata"> <% if is_home? yield(:class) %> <span>points</span> <% end %> <span class="taskValue"><%= campaign.points %></span> </div> <div class="clear"></div> </div> <p> - <%= simple_format campaign.description %> + <%= simple_format campaign.short_description %> </p> </div> <div class="taskDetail"> <% percent = campaign.percent_complete %> <div class="taskBar"> <span class="tagValue" style="width: <%= percent %>%"><%= percent %>%</span> </div> <span class="tagNumber"><%= 100 - percent %>% To Go</span> <div class="clear"></div> </div> </li> <% end %> </ul> \ No newline at end of file diff --git a/db/migrate/014_rename_internal_description_to_short_description_on_campaign.rb b/db/migrate/014_rename_internal_description_to_short_description_on_campaign.rb new file mode 100644 index 0000000..9eee52c --- /dev/null +++ b/db/migrate/014_rename_internal_description_to_short_description_on_campaign.rb @@ -0,0 +1,9 @@ +class RenameInternalDescriptionToShortDescriptionOnCampaign < ActiveRecord::Migration + def self.up + rename_column :campaigns, :private_description, :short_description + end + + def self.down + rename_column :campaigns, :short_description, :private_description + end +end \ No newline at end of file diff --git a/db/schema.rb b/db/schema.rb index 45b4bb6..ab399eb 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,89 +1,89 @@ # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 13) do +ActiveRecord::Schema.define(:version => 14) do create_table "campaigns", :force => true do |t| t.string "name" t.string "keyword" t.string "url" t.text "instructions" t.text "description" - t.text "private_description" + t.text "short_description" t.text "template" t.integer "points" - t.integer "runs", :default => 0 + t.integer "runs", :default => 0 t.datetime "created_at" t.datetime "updated_at" t.integer "user_runs" t.integer "creator_id" t.datetime "start_at" end add_index "campaigns", ["creator_id"], :name => "index_campaigns_on_creator_id" add_index "campaigns", ["keyword"], :name => "index_campaigns_on_keyword" create_table "open_id_authentication_associations", :force => true do |t| t.integer "issued" t.integer "lifetime" t.string "handle" t.string "assoc_type" t.binary "server_url" t.binary "secret" end create_table "open_id_authentication_nonces", :force => true do |t| t.integer "timestamp", :null => false t.string "server_url" t.string "salt", :null => false end create_table "tasks", :force => true do |t| t.integer "user_id" t.integer "campaign_id" t.integer "points" t.datetime "completed_at" t.string "key" t.datetime "created_at" t.datetime "updated_at" t.integer "elapsed_seconds" end add_index "tasks", ["campaign_id"], :name => "index_tasks_on_campaign_id" add_index "tasks", ["key"], :name => "index_tasks_on_key" add_index "tasks", ["user_id", "campaign_id"], :name => "index_tasks_on_user_id_and_campaign_id" create_table "users", :force => true do |t| t.boolean "admin", :default => false t.string "email" t.datetime "created_at" t.datetime "updated_at" t.string "login", :null => false t.string "crypted_password" t.string "password_salt" t.string "persistence_token", :null => false t.string "openid_identifier" t.string "avatar_file_name" t.string "avatar_content_type" t.integer "avatar_file_size" t.datetime "avatar_updated_at" t.string "organization_name" t.boolean "subscribe_campaigns", :default => false t.boolean "subscribe_all", :default => false end add_index "users", ["login"], :name => "index_users_on_login" add_index "users", ["openid_identifier"], :name => "index_users_on_openid_identifier" add_index "users", ["persistence_token"], :name => "index_users_on_persistence_token" add_index "users", ["subscribe_all"], :name => "index_users_on_subscribe_all" add_index "users", ["subscribe_campaigns"], :name => "index_users_on_subscribe_campaigns" end
sunlightlabs/tcorps
b6f7ff36ed06a9d80ed70084a48db4e21a750a1e
changing css so hidden input fields won't show
diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb index 86108eb..d8d8b2a 100644 --- a/app/views/users/new.html.erb +++ b/app/views/users/new.html.erb @@ -1,134 +1,134 @@ <% content_for :class, :signup %> <div class="mainTaskHeader"> <h2>Join Us</h2> <div class="clear"></div> </div> <p class="join">Already have an account? <%= link_to 'Sign in!', login_path %></p> <p>Join the cause, by signing up for Transparency Corps with one of the options below.</p> <div id="signup_nav" class="nav"> <ul> <li id="nav_standard" class="active"><a href="#">Standard Sign Up</a></li> <!-- <li id="nav_aol"><a href="#">AOL</a></li> <li id="nav_yahoo"><a href="#">Yahoo</a></li> <li id="nav_google"><a href="#">Google</a></li> <li id="nav_facebook"><a href="#">Facebook</a></li> --> <li id="nav_openid"><a href="#">OpenID</a></li> </ul> <div class="clear"></div> </div> <div id="signup_options"> <%= errors @user %> <div id="signup_standard" class="signup_option"> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> <%= f.text_field :login, :class => 'text' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text' %> </li> <li> <%= f.label :password %> <%= f.password_field :password, :class => 'text' %> </li> <li> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation, :class => 'text' %> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_campaigns]"/> <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> Email me when there's a new campaign </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_all]"/> <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> Email me about other Sunlight services </li> </ul> <%= f.submit 'Register' %> <% end %> </div> <div id="signup_aol" class="signup_option" style="display: none"> <h3>Sign up using your AOL account.</h3> <p class="tip">Clicking this button will take you to AOL to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="aolBtn" type="submit"> <span>Sign Up Using AOL</span> </button> </div> <div id="signup_yahoo" class="signup_option" style="display: none"> <h3>Sign up using your Yahoo account.</h3> <p class="tip">Clicking this button will take you to Yahoo to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="yahooBtn" type="submit"> <span>Sign Up Using Yahoo</span> </button> </div> <div id="signup_google" class="signup_option" style="display: none"> <h3>Sign up using your Google account.</h3> <p class="tip">Clicking this button will take you to Google to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="googleBtn" type="submit"> <span>Sign Up Using Google</span> </button> </div> <div id="signup_facebook" class="signup_option" style="display: none"> <h3>Sign up using your Facebook account.</h3> <p class="tip">Clicking this button will take you to Facebook to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="facebookBtn" type="submit"> <span>Sign Up Using Facebook</span> </button> </div> <div id="signup_openid" class="signup_option" style="display: none"> <h3>Sign up using your OpenID account.</h3> <p class="tip">Clicking this button will take you to OpenID to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> - <%= f.text_field :login %> + <%= f.text_field :login, :class => 'text' %> </li> <li> <%= f.label :email %> - <%= f.text_field :email %> + <%= f.text_field :email, :class => 'text' %> </li> <li> <label for="user_openid_identifier">OpenID</label> - <%= f.text_field :openid_identifier, :value => @user.openid_identifier.blank? ? 'http://' : @user.openid_identifier %> + <%= f.text_field :openid_identifier, :value => @user.openid_identifier.blank? ? 'http://' : @user.openid_identifier, :class => 'text' %> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_campaigns]"/> <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> Email me when there's a new campaign </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_all]"/> <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> Email me about other Sunlight services </li> </ul> <button class="openidBtn" type="submit"> <span>Sign Up Using OpenID</span> </button> <% end %> </div> </div> <% if open_id_return? %> <% javascript_tag do %> switch_nav('openid', 'signup'); <% end %> <% end %> \ No newline at end of file diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css index 64bc1ff..716ca9b 100644 --- a/public/stylesheets/style.css +++ b/public/stylesheets/style.css @@ -1,319 +1,319 @@ /* * YUI Resect CSS version: 2.2.2 * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Licensed under the BSD License: http://developer.yahoo.net/yui/license.txt */ body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,optgroup,button,p,blockquote,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}table{border-collapse:collapse;border-spacing:0;}caption,th{text-align:left;}ol,ul{list-style:none;}fieldset,img{border:0;}input,textarea,select,optgroup,option,button{font-family:inherit;font-size:100%;}button,input {width: auto;overflow: visible;}optgroup,address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;} dl li{list-style: none;} a:link{outline: none; color: #00788a;} a:visited{outline: none; color: #00788a} a:hover{outline: none; color: #00788a} a:active{outline: none; color: #00788a} body{ color:#6c6d6e; background: url(/images/mainBg.jpg) top left repeat; font-size: 76%; line-height: 20px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif; } div#ltColumn p { font-size: 108%; line-height: 21px;} .clear{ clear: both;} .fieldWithErrors {padding: 0; margin: 0; display: inline;} div#headerWrapper{ background: url(/images/headerBg2_repeat.jpg) top center repeat-x;} div#pageMain{ background: url(/images/headerBg2.jpg) top center no-repeat; width: 960px; margin: 0 auto;} div#header{ height: 237px;} h1{ float: left; width: 260px; height: 176px; margin-left: 20px;} h1 a{ width: 260px; height: 176px; background: url(/images/logo.png) top left no-repeat; text-indent: -9999em; display: block;} div#accountInfo a{ color: #fff; font-weight: bold; padding: 0 3px 0 4px; margin-right: 3px; float: right;} div#accountInfo span{ float: right; margin-right: 5px;} div#accountInfo{ text-align: right; color: #e6e7e8; padding-top: 11px;} div#accountInfo a#smAvatar { padding-top:3px; width: 24px; height: 24px; display: block; padding-top: 3px; margin-top: -8px;} span.bar { float: right;} div#nav { float: left; margin-top: -25px;} div#featureSection a { background: url(/images/btn_getStarted.png) bottom left no-repeat; display: block; width: 197px; height: 85px; text-indent: -9999em; margin-left: 720px; //padding-top: 130px; padding-top: 105px; } div#featureSection h2{ font-size: 250%; color: #e7e7e8; line-height: 35px; margin-bottom: 15px; width: 700px;} div#featureText{ //width: 480px; width: 550px; float: left; //margin-left: 220px; margin-left: 50px; //padding-top: 55px; padding-top: 40px; } div#featureText p { //width: 370px; width: 600px; font-size: 113%; color: #848383; } div#nav ul{ margin-left:350px;} div#nav ul li {float: left; margin-left: 10px;} div#nav li a { width: 108px; height: 59px; text-indent: -9999em; display: block;} li#nav_tasks a{ background: url(/images/nav_tasks.png) left top no-repeat;} li#nav_tasks a.active{ background: url(/images/nav_tasks.png) left bottom no-repeat;} div#nav ul li#nav_leaders a{ background: url(/images/nav_leaders.png) left top no-repeat; width: 208px; } div#nav ul li#nav_leaders a.active{ background: url(/images/nav_leaders.png) left bottom no-repeat; width: 208px; } li#nav_about a{ background: url(/images/nav_about.png) left top no-repeat;} li#nav_about a.active{ background: url(/images/nav_about.png) left bottom no-repeat;} li#nav_contact a{ background: url(/images/nav_contact.png) left top no-repeat;} li#nav_contact a.active{ background: url(/images/nav_contact.png) left bottom no-repeat;} div#mainContent{ background: #fff; margin: 0 20px 20px; border-left: 1px solid #e2e2e2; border-right: 1px solid #e2e2e2; border-bottom: 1px solid #e2e2e2; padding-top: 20px; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px;} div#featureSection { background: url(/images/featureBox2.jpg) top left no-repeat; width: 960px; height: 249px; margin: 0px; padding: 0px;} body.home div#ltColumn{ width: 492px;} div#ltColumn{ padding: 20px 30px 40px; width: 540px; float: left;} h2{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; font-size: 235%; float: left; } /*div#ltColumn h2{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 492px; height: 29px; display: block; font-size: 235%; padding-bottom: 10px; margin-bottom: 10px;}*/ div.mainTaskHeader{ background: url(/images/bar_ltColumn.png) bottom left no-repeat; width: 572px; display: block; padding-bottom: 15px; margin-bottom: 20px; } div.mainTaskHeader h2{ width: 420px; line-height: 32px; margin-top: -5px; float: left;} body.home div.mainTaskHeader{ background: url(/images/bar_ltColumn_home.png) bottom left no-repeat; width: 492px;} div#rtColumn{ float: left; background: url(/images/rtBorder.jpg) 3px top repeat-y; margin-left: 43px;} div#rtContent{ width: 215px; padding: 10px 30px 30px 30px;} body.home div#rtContent{ width: 306px; } div#rtBorder{ background: url(/images/rtBorder_top.jpg) left top no-repeat; } body.home div#rtColumn{ margin-left: 0;} h3{ color: #4f4e4d; font-size: 140%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; margin-bottom: 5px;} div#rtColumn h3{ background: url(/images/bar_rtColumn.png) bottom left no-repeat; margin-bottom: 20px; font-size: 160%; line-height: 21px; padding-bottom: 5px;} div#rtColumn h4 { font-size: 130%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; float: left; height: auto !important; min-height: 27px; width: auto !important; max-width: 140px;} body.home div#rtColumn h4{ width: auto !important; max-width: 180px;} body.home div.taskTop{ padding: 20px 20px 0;} div.taskTop{ padding: 15px 15px 0; } div#rtColumn div.taskTop img { max-width: 180px; } div#ltColumn img { max-width: 540px; } p img { display: block; margin-top: 10px; margin-bottom: 10px;} div#rtContent ul li{ background: #f9f9f9; border: 1px solid #e6e7e7; -moz-border-radius: 3px; -webkit-border-radius: 3px;} div.taskMetadata span.taskValue, body.home div#rtColumn div.taskMetadata span.taskValue{ background: url(/images/task_pointCircle.png) top left no-repeat; color: #fff; width: 27px; height: 27px; text-align: center; padding-top: 3px; margin-right: 5px; margin-top: -4px;} div#rtColumn div.taskMetadata span.taskValue{ margin-right: 0;} div#ltColumn div.taskMetadata span.taskValue{ background: url(/images/mainTask_pointCircle.jpg) top left no-repeat; width: 30px; height: 30px; float: right; padding-top: 5px; margin-right: 5px} div.taskMetadata span {float: right;} div#ltColumn div.taskMetadata span{ margin-right: 55px;} div.taskMetadata { font-style: oblique;} div#ltColumn div.taskMetadata { font-style: oblique; font-size: 110%;} div.taskHeader{ margin-bottom: 10px;} p {margin-bottom: 20px;} div#rtColumn ul li { margin-bottom: 20px;} div.taskDetail{ background: #ececed; -moz-border-radius-bottomright: 3px; -webkit-border-radius-bottomleft: 3px; padding: 5px 15px;} body.home div.taskDetail{ padding: 5px 20px;} div#ltColumn div.taskDetail, form#contactForm, div#signup_options, form.edit_user, div#signin_options{ background: #f9f9f9; -moz-border-radius: 3px; -webkit-border-radius: 3px; border: solid 1px #ececed; padding: 15px 20px; margin-bottom: 15px;} div#signup_options, div#signin_options{ margin-top: -2px;} p.join {font-weight: bold; font-size: 1.2em;} div#signup_options, form#contactForm, div.signin_option ul, form.edit_user{ padding-top: 25px; padding-bottom: 40px;} span.tagValue{ background: url(/images/highlightBar2.jpg) left top repeat-x; position: absolute; top: 0; left: 0; text-indent: -9999em; float: left; overflow: hidden; } div#rtContent span.tagValue{ background: url(/images/highlightBar.jpg) left top repeat-x;} div.taskBar{ background-color: #fff; width: 403px; border: 1px solid #bfbfbe; position: relative; line-height: 1.3em; height: 10px; float: left; margin: 6px 13px 0 0;} div#rtContent div.taskBar{ width: 180px; height: 5px;} body.home div#rtContent div.taskBar{ width: 185px;} ul#taskList div.taskBar{ height: 5px;} div#ltColumn ul#taskList div.taskMetadata span{ margin-right: 10px;} div#ltColumn ul#taskList div.taskTop{ padding: 15px 0 0 0 ;} ul#taskList li { border-bottom: solid 1px #ececed; padding-bottom: 15px; margin-bottom: 15px;} ul#taskList h3 { font-size: 150%; float: left;} div#ltColumn ul#taskList div.taskDetail { padding: 8px 20px;} div#ltColumn ul#taskList span.tagNumber{ font-size: 90%;} div#ltColumn ul#taskList span.tagValue { background: url(/images/highlightBar.jpg) repeat-x left top;} span.startBtn{ width: 98px; height: 36px; border: none 0; background: none; margin-bottom: 15px; cursor: pointer;} span.startBtn a{ width: 98px; height: 36px; text-indent: -9999em; background: url(/images/btn_start.png) top left no-repeat; display: block; border: none;} span.tagNumber { font-weight: bold; font-size: 90%; color: #da7c02;} div#ltColumn span.tagNumber { font-size: 110%; padding-top: 5px; } div#taskScoreboard{ float: right; background: url(/images/scoreboardBg.jpg) top right no-repeat; width: 312px; height: 158px; } div#taskScoreboard dt, div#taskScoreboard dd{ color: #fff; font-size: 150%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; line-height: 28px;} div#taskScoreboard dl { padding: 50px 0 0 60px;} div#taskScoreboard dt{ float: left; font-weight: bold; margin-right: 5px;} form#contactForm label, form#new_user label, form#new_user_session label, form.edit_user label{ font-weight: bold; width: 100px; display: block; float: left; padding-top:5px;} form#new_user label, form.edit_user label{ width: 160px;} -form#contactForm input, form#contactForm textarea, form#new_user input, form#new_user textarea, form#new_user_session input, form#new_user_session textarea, form.edit_user input, input#openid_username{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} +form#contactForm input.text, form#contactForm textarea, form#new_user input.text, form#new_user textarea, form#new_user_session input.text, form#new_user_session textarea, form.edit_user input.text, input#openid_username.text{ border: dotted 1px #d8d8d8; -moz-border-radius: 3px; -webkit-border-radius: 3px; width: 300px; padding: 5px;} form#contactForm input, form#new_user input, form#new_user_session input, form.edit_user input{ height: 15px;} form li{ margin-bottom: 10px;} input:hidden {display: none} form.edit_user input#user_avatar{ height: 25px;} input#openid_username{ margin-bottom: 15px;} button.submitBtn span{ background: url(/images/btn_submit.png) top left no-repeat; display: block; width: 136px; height: 43px; text-indent: -9999em; } button.submitBtn{ border: 0; background: none; margin-left: 100px; margin-top: 20px;} div#footer{ width: 960; margin: 0 auto; font-size: 90%; padding: 0 20px;} div#footerBrand{ float: left; border-right: 1px solid #6c6b6b; margin-right: 15px; padding-right: 15px;} div#footerBrand a{ background: url(/images/foundationLogo.png) top left no-repeat; display: block; text-indent: -9999em; width: 132px; height: 61px;} /* Styling for popup task page - needs attention */ body.task div.header {height: 50px; padding: 10px; margin-bottom: 10px;} body.task div.campaign {float: left; width: 78%;} body.task div.nav {float: right; width: 18%;} body.task div.header span.title { font-size: 200%; font-family: Baskerville, Georgia, Times New Roman, Times, serif; color: #231f20; margin-bottom: 10px; padding-top: 5px; } body.task div.header span.instructions { font-family: Helvetica Neue, Helvetica, Arial, sans-serif; margin-bottom: 15px; } body.task div.header span.instructions p {padding: 0; margin: 5px;} body.task div.header div.nav a.back {} input#anotherTask { background: url(/images/btn_anotherTask.png) top left no-repeat; width: 148px; height: 37px; display: block; text-indent: -9999em; border: none; } iframe#task_frame {width: 100%; height: 800px; margin: 0; padding: 0; clear: both; margin-top: 10px;} form#new_user input#user_submit, form#new_user_session input#user_session_submit, form.edit_user input#update_button, button.openidBtn { border: none; display: block; width: 137px; height: 44px; text-indent: -9999em; margin-top: 20px;} div#signin_options button.openidBtn{ margin-left: 0px;} button.openidBtn{ margin-left: 160px;} input#update_button{ background: url(/images/btn_update.png) top left no-repeat; margin-left: 160px;} form#new_user input#user_submit{ background: url(/images/btn_register.png) top left no-repeat; margin-left: 160px;} form#new_user_session input#user_session_submit { background: url(/images/btn_login.png) top left no-repeat; margin-left: 100px;} div#signup_nav li, div#signin_nav li{ float: left; padding: 5px 5px 8px; margin-top: 10px; margin-right: 5px;} li#nav_aol a{ width: 75px; height: 20px; background: url(/images/logo_aol.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_aol { width: 75px; height: 20px;} li#nav_yahoo a{ width: 75px; height: 20px; background: url(/images/logo_yahoo.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_yahoo { width: 75px; height: 20px;} li#nav_google a{ width: 75px; height: 20px; background: url(/images/logo_google.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_google { width: 75px; height: 20px;} li#nav_facebook a{ width: 75px; height: 20px; background: url(/images/logo_facebook.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_facebook { width: 75px; height: 20px;} li#nav_openid a{ width: 75px; height: 20px; background: url(/images/logo_openid.png) top center no-repeat; text-indent: -9999em; display: block;} li#nav_openid { width: 75px; height: 20px;} li.active{ background-color: #F9F9F9; border-top: 1px solid #ECECED; border-left: 1px solid #ECECED; border-right: 1px solid #ECECED; -moz-border-radius-topright: 4px; -webkit-border-radius-topleft: 4px;} li#nav_standard a{ color: #d65203; font-weight: bold; text-decoration: none;} div#signup_options button, div#signin_options button{ border: none; text-indent: -9999em; display: block; height: 42px; } button.aolBtn{ background: url(/images/btn_aol.png) top left no-repeat; width: 176px; } button.yahooBtn{ background: url(/images/btn_yahoo.png) top left no-repeat; width: 196px; } button.googleBtn{ background: url(/images/btn_google.png) top left no-repeat; width: 196px; } button.facebookBtn{ background: url(/images/btn_facebook.png) top left no-repeat; width: 209px; } button.openidBtn{ background: url(/images/btn_openid.png) top left no-repeat; width: 209px; } div#signin_options button.aolBtn{ background: url(/images/btn_aol2.png) top left no-repeat; width: 176px; } div#signin_options button.yahooBtn{ background: url(/images/btn_yahoo2.png) top left no-repeat; width: 196px; } div#signin_options button.googleBtn{ background: url(/images/btn_google2.png) top left no-repeat; width: 196px; } div#signin_options button.facebookBtn{ background: url(/images/btn_facebook2.png) top left no-repeat; width: 209px; } div#signin_options button.openidBtn{ background: url(/images/btn_openid2.png) top left no-repeat; width: 209px; } p.tip{ font-style: oblique; font-size: 90%; line-height: 15px; color: #909192;} input#startTask { background: url(/images/btn_startthis.png) top left no-repeat; width: 124px; height: 36px; display: block; text-indent: -9999em; border: none;} body.leaders div#ltColumn{ width: 860px;} div.rank { margin-bottom: 30px;} div.rank p{ text-align: center; font-style: oblique;} ol.leaders{ margin-left: 50px;} ol.leaders li{ margin-left: 10px; margin-right: 10px;float: left; width: 170px; } ol.leaders li img{ float: left; margin: 0 10px 20px 0;} div.rankHeader{ background: url(/images/fullBar.png) bottom left no-repeat; width: ; padding-bottom: 30px; margin-bottom: 20px;} body.leaders dl{ font-family: Baskerville, Georgia, Times New Roman, Times, serif; padding-top: 40px; padding-left: 60px;} body.leaders dt{ float: left;} span.leaderName{ display: block; line-height: 18px; padding-top: 15px;} dt.rankTitle, dt.pointTitle {display: none; } dd.rankTitle{ font-size: 280%; color: #231f20; margin-bottom: 10px; font-weight: bold;} div.rankHeader dl dt { margin-right: 3px;} .level{ font-size: 140%; margin-bottom: 8px; color: #797474; } dd.pointTitle, span.leaderPoints {font-family: Helvetica Neue, Helvetica, Arial, sans-serif; color: #a8a8a8; font-style: oblique;} div.rankHeader img { float: left; margin: 0 10px 10px 40px;} div.contact_form_validation, div.error { margin-bottom: 15px; font-size: 120%; font-weight: bold; color: #b52802;} div.error{ margin-bottom: 0px;} div.errors{ margin-bottom: 15px;} div.flash { width: 520px; background: #f7f2cc; -moz-border-radius: 3px; -webkit-border-radius: 3px; padding: 10px; margin-left: 30px; } div.flash.failure { border: 1px solid #fae19c; color: #da7c02; } div.flash.success { border: 1px solid #fae19c; color: #da7c02; } body.home div.flash { width: 472px; } div#rtColumn ul#newMembers li { background: none; border: none; height: 64px; margin-bottom: 15px;} div#rtColumn ul#newMembers img { float: left; height: 64px; margin: 0 15px 15px 0;} li.checkboxIndent { margin-left: 160px; font-style: oblique; font-size: 95%; margin-bottom: 5px;} li.checkboxIndent input { display: block; float: left; margin-right: 10px; margin-top: 2px;} \ No newline at end of file
sunlightlabs/tcorps
d31f1472d67bec80bfc8f098ec8b13711f07212c
Added a class of 'text' to text input fields
diff --git a/app/views/user_sessions/new.html.erb b/app/views/user_sessions/new.html.erb index 96cf4e1..3062b54 100644 --- a/app/views/user_sessions/new.html.erb +++ b/app/views/user_sessions/new.html.erb @@ -1,98 +1,98 @@ <% content_for :class, :signin %> <div class="mainTaskHeader"> <h2>Sign In</h2> <div class="clear"></div> </div> <p class="join">Don't have an account? <%= link_to 'Join us!', register_path %></p> <div id="signin_nav" class="nav"> <ul> <li id="nav_standard" class="active"><a href="#">Standard Sign In</a></li> <!-- <li id="nav_aol"><a href="#">AOL</a></li> <li id="nav_yahoo"><a href="#">Yahoo</a></li> <li id="nav_google"><a href="#">Google</a></li> <li id="nav_facebook"><a href="#">Facebook</a></li> --> <li id="nav_openid"><a href="#">OpenID</a></li> </ul> <div class="clear"></div> </div> <div id="signin_options"> <% if @error_message %> <div class="error"> <%= @error_message %> </div> <% end %> <div id="signin_standard" class="signin_option"> <% form_for @user_session, :url => user_session_path do |f| %> <ul> <li> <label for="username_login">Username</label> - <%= f.text_field :login %> + <%= f.text_field :login, :class => 'text' %> </li> <li> <%= f.label :password %> - <%= f.password_field :password %> + <%= f.password_field :password, :class => 'text' %> </li> </ul> <%= f.submit 'Login' %> <% end %> </div> <div id="signin_aol" class="signin_option" style="display: none"> <h3>Sign In using your AOL account.</h3> <p class="tip">Clicking this button will take you to AOL to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="aolBtn" type="submit"> <span>Sign In Using AOL</span> </button> </div> <div id="signin_yahoo" class="signin_option" style="display: none"> <h3>Sign In using your Yahoo account.</h3> <p class="tip">Clicking this button will take you to Yahoo to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="yahooBtn" type="submit"> <span>Sign In Using Yahoo</span> </button> </div> <div id="signin_google" class="signin_option" style="display: none"> <h3>Sign In using your Google account.</h3> <p class="tip">Clicking this button will take you to Google to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="googleBtn" type="submit"> <span>Sign In Using Google</span> </button> </div> <div id="signin_facebook" class="signin_option" style="display: none"> <h3>Sign In using your Facebook account.</h3> <p class="tip">Clicking this button will take you to Facebook to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="facebookBtn" type="submit"> <span>Sign In Using Facebook</span> </button> </div> <div id="signin_openid" class="signin_option" style="display: none"> <h3>Sign In using your OpenID account.</h3> <p class="tip">Clicking this button will take you to OpenID to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <% form_for @user_session, :url => user_session_path do |f| %> - <%= f.text_field :openid_identifier, :value => 'http://' %> + <%= f.text_field :openid_identifier, :value => 'http://', :class => 'text' %> <button class="openidBtn" type="submit"> <span>Sign In Using OpenID</span> </button> <% end %> </div> </div> <% if open_id_return? %> <% javascript_tag do %> // switch_nav('openid', 'signin'); <% end %> <% end %> \ No newline at end of file diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb index 12032e3..86108eb 100644 --- a/app/views/users/new.html.erb +++ b/app/views/users/new.html.erb @@ -1,134 +1,134 @@ <% content_for :class, :signup %> <div class="mainTaskHeader"> <h2>Join Us</h2> <div class="clear"></div> </div> <p class="join">Already have an account? <%= link_to 'Sign in!', login_path %></p> <p>Join the cause, by signing up for Transparency Corps with one of the options below.</p> <div id="signup_nav" class="nav"> <ul> <li id="nav_standard" class="active"><a href="#">Standard Sign Up</a></li> <!-- <li id="nav_aol"><a href="#">AOL</a></li> <li id="nav_yahoo"><a href="#">Yahoo</a></li> <li id="nav_google"><a href="#">Google</a></li> <li id="nav_facebook"><a href="#">Facebook</a></li> --> <li id="nav_openid"><a href="#">OpenID</a></li> </ul> <div class="clear"></div> </div> <div id="signup_options"> <%= errors @user %> <div id="signup_standard" class="signup_option"> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> - <%= f.text_field :login %> + <%= f.text_field :login, :class => 'text' %> </li> <li> <%= f.label :email %> - <%= f.text_field :email %> + <%= f.text_field :email, :class => 'text' %> </li> <li> <%= f.label :password %> - <%= f.password_field :password %> + <%= f.password_field :password, :class => 'text' %> </li> <li> <%= f.label :password_confirmation %> - <%= f.password_field :password_confirmation %> + <%= f.password_field :password_confirmation, :class => 'text' %> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_campaigns]"/> <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> Email me when there's a new campaign </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_all]"/> <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> Email me about other Sunlight services </li> </ul> <%= f.submit 'Register' %> <% end %> </div> <div id="signup_aol" class="signup_option" style="display: none"> <h3>Sign up using your AOL account.</h3> <p class="tip">Clicking this button will take you to AOL to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="aolBtn" type="submit"> <span>Sign Up Using AOL</span> </button> </div> <div id="signup_yahoo" class="signup_option" style="display: none"> <h3>Sign up using your Yahoo account.</h3> <p class="tip">Clicking this button will take you to Yahoo to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="yahooBtn" type="submit"> <span>Sign Up Using Yahoo</span> </button> </div> <div id="signup_google" class="signup_option" style="display: none"> <h3>Sign up using your Google account.</h3> <p class="tip">Clicking this button will take you to Google to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="googleBtn" type="submit"> <span>Sign Up Using Google</span> </button> </div> <div id="signup_facebook" class="signup_option" style="display: none"> <h3>Sign up using your Facebook account.</h3> <p class="tip">Clicking this button will take you to Facebook to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="facebookBtn" type="submit"> <span>Sign Up Using Facebook</span> </button> </div> <div id="signup_openid" class="signup_option" style="display: none"> <h3>Sign up using your OpenID account.</h3> <p class="tip">Clicking this button will take you to OpenID to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> <%= f.text_field :login %> </li> <li> <%= f.label :email %> <%= f.text_field :email %> </li> <li> <label for="user_openid_identifier">OpenID</label> <%= f.text_field :openid_identifier, :value => @user.openid_identifier.blank? ? 'http://' : @user.openid_identifier %> </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_campaigns]"/> <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> Email me when there's a new campaign </li> <li class="checkboxIndent"> <input type="hidden" value="0" name="user[subscribe_all]"/> <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> Email me about other Sunlight services </li> </ul> <button class="openidBtn" type="submit"> <span>Sign Up Using OpenID</span> </button> <% end %> </div> </div> <% if open_id_return? %> <% javascript_tag do %> switch_nav('openid', 'signup'); <% end %> <% end %> \ No newline at end of file
sunlightlabs/tcorps
3917b268503a6bc43701864a17f5b69ce2a82900
Put plain HTML instead of checkbox generator tags, for now
diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb index eb23f70..9d60c22 100644 --- a/app/views/users/edit.html.erb +++ b/app/views/users/edit.html.erb @@ -1,45 +1,48 @@ <div class="mainTaskHeader"> <h2>Edit Profile</h2> <div class="clear"></div> </div> <% form_for @user, :html => {:multipart => true} do |f| %> <%= errors @user %> <ul> <li> <label for='username'>Username</label> <%= f.text_field :login, :id => 'username', :class => 'text', :size => '32' %> </li> <li> <%= f.label :email %> <%= f.text_field :email, :class => 'text', :size => '32' %> </li> <li> <%= f.label :password %> <%= f.password_field :password, :class => 'text', :size => '32' %> </li> <li> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation, :class => 'text', :size => '32' %> </li> <li> <label for='avatar'>Current Avatar</label> <%= image_tag @user.avatar.url(:normal) %> </li> <li> <label for='user_avatar'>Upload a new avatar</label> <%= f.file_field :avatar %> </li> <li class="checkboxIndent"> - <%= f.check_box :subscribe_campaigns %> Email me when there's a new campaign + <input type="hidden" value="0" name="user[subscribe_campaigns]"/> + <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> + Email me when there's a new campaign </li> - <li class="checkboxIndent"> - <%= f.check_box :subscribe_all %>Email me about other Sunlight services + <input type="hidden" value="0" name="user[subscribe_all]"/> + <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> + Email me about other Sunlight services </li> <input type="submit" value="Update" name="commit" id="update_button" /> </ul> <% end %> diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb index afd15f6..12032e3 100644 --- a/app/views/users/new.html.erb +++ b/app/views/users/new.html.erb @@ -1,128 +1,134 @@ <% content_for :class, :signup %> <div class="mainTaskHeader"> <h2>Join Us</h2> <div class="clear"></div> </div> <p class="join">Already have an account? <%= link_to 'Sign in!', login_path %></p> <p>Join the cause, by signing up for Transparency Corps with one of the options below.</p> <div id="signup_nav" class="nav"> <ul> <li id="nav_standard" class="active"><a href="#">Standard Sign Up</a></li> <!-- <li id="nav_aol"><a href="#">AOL</a></li> <li id="nav_yahoo"><a href="#">Yahoo</a></li> <li id="nav_google"><a href="#">Google</a></li> <li id="nav_facebook"><a href="#">Facebook</a></li> --> <li id="nav_openid"><a href="#">OpenID</a></li> </ul> <div class="clear"></div> </div> <div id="signup_options"> <%= errors @user %> <div id="signup_standard" class="signup_option"> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> <%= f.text_field :login %> </li> <li> <%= f.label :email %> <%= f.text_field :email %> </li> <li> <%= f.label :password %> <%= f.password_field :password %> </li> <li> <%= f.label :password_confirmation %> <%= f.password_field :password_confirmation %> </li> <li class="checkboxIndent"> - <%= f.check_box :subscribe_campaigns %>Email me when there's a new campaign + <input type="hidden" value="0" name="user[subscribe_campaigns]"/> + <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> + Email me when there's a new campaign </li> <li class="checkboxIndent"> - <%= f.check_box :subscribe_all %>Email me about other Sunlight services + <input type="hidden" value="0" name="user[subscribe_all]"/> + <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> + Email me about other Sunlight services </li> </ul> <%= f.submit 'Register' %> <% end %> </div> <div id="signup_aol" class="signup_option" style="display: none"> <h3>Sign up using your AOL account.</h3> <p class="tip">Clicking this button will take you to AOL to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="aolBtn" type="submit"> <span>Sign Up Using AOL</span> </button> </div> <div id="signup_yahoo" class="signup_option" style="display: none"> <h3>Sign up using your Yahoo account.</h3> <p class="tip">Clicking this button will take you to Yahoo to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="yahooBtn" type="submit"> <span>Sign Up Using Yahoo</span> </button> </div> <div id="signup_google" class="signup_option" style="display: none"> <h3>Sign up using your Google account.</h3> <p class="tip">Clicking this button will take you to Google to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="googleBtn" type="submit"> <span>Sign Up Using Google</span> </button> </div> <div id="signup_facebook" class="signup_option" style="display: none"> <h3>Sign up using your Facebook account.</h3> <p class="tip">Clicking this button will take you to Facebook to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <button class="facebookBtn" type="submit"> <span>Sign Up Using Facebook</span> </button> </div> <div id="signup_openid" class="signup_option" style="display: none"> <h3>Sign up using your OpenID account.</h3> <p class="tip">Clicking this button will take you to OpenID to sign in to your account. Once your account has been verified you'll be magically sent back to Transparency Corps.</p> <% form_for @user do |f| %> <ul> <li> <label for="username_login">Username</label> <%= f.text_field :login %> </li> <li> <%= f.label :email %> <%= f.text_field :email %> </li> <li> <label for="user_openid_identifier">OpenID</label> <%= f.text_field :openid_identifier, :value => @user.openid_identifier.blank? ? 'http://' : @user.openid_identifier %> </li> - <li> - <label for='user_subscribe_campaigns'>Email me when there's a new campaign:</label> - <%= f.check_box :subscribe_campaigns %> + <li class="checkboxIndent"> + <input type="hidden" value="0" name="user[subscribe_campaigns]"/> + <input id="user_subscribe_campaigns" type="checkbox" value="1" name="user[subscribe_campaigns]"/> + Email me when there's a new campaign </li> - <li> - <label for='user_subscribe_all'>Email me about other Sunlight services:</label> - <%= f.check_box :subscribe_all %> + <li class="checkboxIndent"> + <input type="hidden" value="0" name="user[subscribe_all]"/> + <input id="user_subscribe_all" type="checkbox" value="1" name="user[subscribe_all]"/> + Email me about other Sunlight services </li> </ul> <button class="openidBtn" type="submit"> <span>Sign Up Using OpenID</span> </button> <% end %> </div> </div> <% if open_id_return? %> <% javascript_tag do %> switch_nav('openid', 'signup'); <% end %> <% end %> \ No newline at end of file
sunlightlabs/tcorps
8d6562984b62d598a8ec970a1b7f15b8af417f5d
Converted display of elapsed time to hours and minutes
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index b853558..2f1ec3a 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,36 +1,40 @@ module ApplicationHelper def is_home?(body_class) [nil, :home].include? body_class end def errors(object) render :partial => 'layouts/partials/errors', :locals => {:object => object} end def period(string) string << (string.last == '.' ? '' : '.') end def open_id_return? params[:open_id_complete] == '1' end def to_word(number) { 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine', 10 => 'Ten' }[number] || number end def to_minutes(seconds) "#{seconds / 60}:#{seconds % 60}" end + + def to_hours(seconds) + "#{(seconds / 3600).to_i}:#{(seconds % 3600) / 60}" + end end \ No newline at end of file diff --git a/app/views/layouts/partials/_stats.html.erb b/app/views/layouts/partials/_stats.html.erb index 25b079d..bcbf8a0 100644 --- a/app/views/layouts/partials/_stats.html.erb +++ b/app/views/layouts/partials/_stats.html.erb @@ -1,19 +1,19 @@ <h3>Stats</h3> <ul> <li> <span><%= Campaign.percent_complete %>%</span> <p>all tasks complete</p> </li> <li> <span><%= User.participants.all.size %></span> <p>people participating</p> </li> <li> <span><%= Task.completed.count %></span> <p>tasks completed</p> </li> <li> - <span><%= to_minutes Task.sum(:elapsed_seconds) %></span> - <p>time spent on tasks<br/>(minutes:seconds)</p> + <span><%= to_hours Task.sum(:elapsed_seconds) %></span> + <p>hours spent on tasks</p> </li> </ul> \ No newline at end of file