Skip to content
Browse files

rebranding, add followers support and some bugfixes

  • Loading branch information...
1 parent 1cb3d40 commit b59e610a89100fc9064cc1e0077f4aa9b6467501 nov committed Mar 4, 2009
View
9 ChangeLog
@@ -13,7 +13,7 @@
== 0.1.0
-* add Iknow::Auth (supports basic_auth and oauth)
+* add Smartfm::Auth (supports basic_auth and oauth)
* add List#create, List#delete, List#add_item, List#delete_item
== 0.1.1
@@ -30,4 +30,9 @@
== 0.2.2
-* add attribution support for add_image & add_sound APIs
+* add attribution support for add_image & add_sound APIs
+
+== 0.3.0
+
+* iKnow! => smart.fm
+* now, iKnow! is the name of Flash study application
View
22 README
@@ -1,19 +1,19 @@
-= iknow
+= smart.fm
- by nov <developer@iknow.co.jp>
+ by nov <nov@cerego.com>
== Description
- This rubygem is a wrapper of iKnow! API.
+ This rubygem is a wrapper of smart.fm API.
You can get pure-ruby example at examples/pure_ruby.rb.
- http://github.com/nov/iknow/tree/master/examples/pure_ruby.rb
+ http://github.com/nov/smartfm/tree/master/examples/pure_ruby.rb
It shows all API calls you can use with this gem.
== Installation
- git clone http://github.com/nov/iknow.git
- cd iknow
+ git clone http://github.com/nov/smartfm.git
+ cd smartfm
rake install
=== Archive Installation
@@ -22,7 +22,7 @@
=== Gem Installation
- gem install iknow
+ gem install smartfm
== Features/Problems
@@ -31,15 +31,15 @@
Create/Add/Delete APIs are not implemented.
They will be implemented in a few weeks.
- iKnow! OAuth is still pre-alpha.
+ smart.fm OAuth is still pre-alpha.
== Synopsis
- See examples and iKnow! Developers, please.
- iKnow! Developers (http://developer.iknow.co.jp)
+ See examples and smart.fm Developers, please.
+ smart.fm Developers (http://developer.smart.fm)
== Copyright
-Author:: nov <developer@iknow.co.jp>
+Author:: nov <nov@cerego.com>
Copyright:: Copyright (c) 2008 nov
License:: MIT License
View
18 Rakefile
@@ -10,17 +10,17 @@ require 'rake/contrib/sshpublisher'
require 'fileutils'
include FileUtils
-NAME = "iknow"
+NAME = "smartfm"
AUTHOR = "nov"
-EMAIL = "developer@iknow.co.jp"
-DESCRIPTION = "A rubygem for iKnow! APIs"
+EMAIL = "developer@smart.fm"
+DESCRIPTION = "A rubygem for smart.fm APIs"
RUBYFORGE_PROJECT = NAME
HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org"
BIN_FILES = %w( )
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/lib"
-require 'lib/iknow'
-VERS = Iknow::Version.to_version
+require 'lib/smartfm'
+VERS = Smartfm::Version.to_version
REV = File.read(".svn/entries")[/committed-rev="(d+)"/, 1] rescue nil
CLEAN.include ['**/.*.sw?', '*.gem', '.config']
RDOC_OPTS = [
@@ -41,6 +41,12 @@ Rake::TestTask.new("test") do |t|
t.verbose = true
end
+Rake::TestTask.new("spec") do |t|
+ t.libs << "spec"
+ t.pattern = "spec/**/*_spec.rb"
+ t.verbose = true
+end
+
spec = Gem::Specification.new do |s|
s.name = NAME
s.version = VERS
@@ -65,7 +71,7 @@ spec = Gem::Specification.new do |s|
# s.required_ruby_version = '>= 1.8.6'
s.files = %w(README ChangeLog Rakefile) +
- Dir.glob("{bin,doc,test,lib,templates,extras,website,script}/**/*") +
+ Dir.glob("{bin,doc,test,spec,lib,templates,extras,website,script}/**/*") +
Dir.glob("ext/**/*.{h,c,rb}") +
Dir.glob("examples/**/*.rb") +
Dir.glob("tools/*.rb") +
View
80 examples/pure_ruby.rb
@@ -1,9 +1,9 @@
require 'rubygems'
-require 'iknow'
+require 'smartfm'
require 'oauth/consumer'
-Iknow::Config.init do |conf|
- conf.api_host = 'api.iknow.co.jp'
+Smartfm::Config.init do |conf|
+ conf.api_host = 'api.smart.fm'
conf.api_key = '' # 'SET_YOUR_API_KEY'
conf.oauth_consumer_key = '' # 'SET_YOUR_OAUTH_CONSUMER_KEY'
conf.oauth_consumer_secret = '' # 'SET_YOUR_OAUTH_CONSUMER_SECRET'
@@ -17,20 +17,20 @@
OAUTH_ACCESS_TOKEN_SECRET = ''
# Edit here
-IKNOW_USERNAME = ''
-IKNOW_PASSWORD = ''
+SMARTFM_USERNAME = ''
+SMARTFM_PASSWORD = ''
please_get_api_key =<<EOS
-This example needs your own iKnow! API key.
-(for only Iknow::Item.extract example)
+This example needs your own smart.fm API key.
+(for only Smartfm::Item.extract example)
-You can get iKnow! API key at iKnow! Developers.
-iKnow! Developers (http://developer.iknow.co.jp/)
+You can get smart.fm API key at smart.fm Developers.
+smart.fm Developers (http://developer.smart.fm/)
Thanks!
EOS
-if Iknow::Config.api_key == ''
+if Smartfm::Config.api_key == ''
raise ArgumentError.new(please_get_api_key)
end
@@ -43,76 +43,76 @@
## User API
puts "# User API Calls"
-@user = Iknow::User.find('kirk')
+@user = Smartfm::User.find('kirk')
@user.items(:include_sentences => true)
@user.lists
@user.friends
@user.study.results
@user.study.total_summary
-@matched_users = Iknow::User.matching('matake')
+@matched_users = Smartfm::User.matching('matake')
## List API
puts "# List API Calls"
-@recent_lists = Iknow::List.recent
-@list = Iknow::List.find(31509, :include_sentences => true, :include_items => true)
+@recent_lists = Smartfm::List.recent
+@list = Smartfm::List.find(31509, :include_sentences => true, :include_items => true)
@list.items
@list.sentences
-@matched_lists = Iknow::List.matching("イタリア語であいさつ")
+@matched_lists = Smartfm::List.matching("イタリア語であいさつ")
## Item API
puts "# Item API Calls"
-@recent_items = Iknow::Item.recent(:include_sentences => true)
-@item = Iknow::Item.find(437525)
-@matched_items = Iknow::Item.matching('record', :include_sentences => true)
-@items = Iknow::Item.extract("sometimes, often, electrical")
+@recent_items = Smartfm::Item.recent(:include_sentences => true)
+@item = Smartfm::Item.find(437525)
+@matched_items = Smartfm::Item.matching('record', :include_sentences => true)
+@items = Smartfm::Item.extract("sometimes, often, electrical")
@items.first.sentences
## Sentence API
puts "# Sentence API Calls"
-@recent_sentences = Iknow::Sentence.recent
-@sentence = Iknow::Sentence.find(312271)
-@matched_sentences = Iknow::Sentence.matching('record')
+@recent_sentences = Smartfm::Sentence.recent
+@sentence = Smartfm::Sentence.find(312271)
+@matched_sentences = Smartfm::Sentence.matching('record')
########################
## WITH AUTHORIZATION ##
########################
-iknow_auth = case
+auth = case
when !OAUTH_ACCESS_TOKEN.empty?
- if Iknow::Config.oauth_consumer_key.empty? or Iknow::Config.oauth_consumer_secret.empty?
+ if Smartfm::Config.oauth_consumer_key.empty? or Smartfm::Config.oauth_consumer_secret.empty?
raise ArgumentError.new("oauth_consumer_key and oauth_consumer_secret are required")
end
- Iknow::Auth.new(:token => OAUTH_ACCESS_TOKEN, :secret => OAUTH_ACCESS_TOKEN_SECRET)
- when IKNOW_USERNAME != ''
- Iknow::Auth.new(:username => IKNOW_USERNAME, :password => IKNOW_PASSWORD)
+ Smartfm::Auth.new(:token => OAUTH_ACCESS_TOKEN, :secret => OAUTH_ACCESS_TOKEN_SECRET)
+ when SMARTFM_USERNAME != ''
+ Smartfm::Auth.new(:username => SMARTFM_USERNAME, :password => SMARTFM_PASSWORD)
else
nil
end
-unless iknow_auth
+unless auth
puts "Skip calls which require authentication"
exit
else
- puts "## WITH AUTHORIZATION :: #{iknow_auth.mode}"
+ puts "## WITH AUTHORIZATION :: #{auth.mode}"
end
## List API
puts "# List API"
-@list = Iknow::List.create(iknow_auth, :title => 'iKnow! gem test', :description => 'A list for iKnow! gem test')
-@list.add_item(iknow_auth, Iknow::Item.find(437525))
-@list.delete_item(iknow_auth, @list.items.first)
-@list.delete(iknow_auth)
+@list = Smartfm::List.create(auth, :title => 'smart.fm gem test', :description => 'A list for smart.fm gem test')
+@list.add_item(auth, Smartfm::Item.find(437525))
+@list.delete_item(auth, @list.items.first)
+@list.delete(auth)
## Item API
puts "# Item API"
-@item = Iknow::Item.create(iknow_auth, :cue => {:text => 'hello world! 2', :language => 'en', :part_of_speech => 'E'},
+@item = Smartfm::Item.create(auth, :cue => {:text => 'hello world! 2', :language => 'en', :part_of_speech => 'E'},
:response => {:text => 'ハローワールド!', :language => 'ja'})
-@item.add_image(iknow_auth, 'http://farm4.static.flickr.com/3276/3102381796_a33c1ffdf1.jpg')
-@item.add_sound(iknow_auth, 'http://matake.jp/download/hello_world.mp3')
-@item.add_tags(iknow_auth, 'sample', 'programming')
+@item.add_image(auth, 'http://farm4.static.flickr.com/3276/3102381796_a33c1ffdf1.jpg')
+@item.add_sound(auth, 'http://matake.jp/download/hello_world.mp3')
+@item.add_tags(auth, 'sample', 'programming')
## Sentence API
puts "# Sentence API"
-@sentence = Iknow::Sentence.create(iknow_auth, :text => 'Hello World!', :item => Iknow::Item.matching('hello world').first)
-@sentence.add_image(iknow_auth, 'http://farm4.static.flickr.com/3276/3102381796_a33c1ffdf1.jpg')
-@sentence.add_sound(iknow_auth, 'http://matake.jp/download/hello_world.mp3')
+@sentence = Smartfm::Sentence.create(auth, :text => 'Hello World!', :item => Smartfm::Item.matching('hello world').first)
+@sentence.add_image(auth, 'http://farm4.static.flickr.com/3276/3102381796_a33c1ffdf1.jpg')
+@sentence.add_sound(auth, 'http://matake.jp/download/hello_world.mp3')
View
38 iknow.gemspec
@@ -1,38 +0,0 @@
-# -*- encoding: utf-8 -*-
-
-Gem::Specification.new do |s|
- s.name = %q{iknow}
- s.version = "0.2.4"
-
- s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
- s.authors = ["nov"]
- s.date = %q{2009-01-03}
- s.description = %q{A rubygem for iKnow! APIs}
- s.email = %q{developer@iknow.co.jp}
- s.extra_rdoc_files = ["README", "ChangeLog"]
- s.files = ["README", "ChangeLog", "Rakefile", "test/iknow_test.rb", "test/test_helper.rb", "lib/ext", "lib/ext/hash.rb", "lib/iknow", "lib/iknow/core", "lib/iknow/core/auth.rb", "lib/iknow/core/config.rb", "lib/iknow/core/version.rb", "lib/iknow/core.rb", "lib/iknow/model", "lib/iknow/model/base.rb", "lib/iknow/model/item.rb", "lib/iknow/model/list.rb", "lib/iknow/model/sentence.rb", "lib/iknow/model/user.rb", "lib/iknow/model.rb", "lib/iknow/rest_client", "lib/iknow/rest_client/base.rb", "lib/iknow/rest_client/item.rb", "lib/iknow/rest_client/list.rb", "lib/iknow/rest_client/sentence.rb", "lib/iknow/rest_client/user.rb", "lib/iknow/rest_client.rb", "lib/iknow.rb", "examples/pure_ruby.rb"]
- s.has_rdoc = true
- s.homepage = %q{http://iknow.rubyforge.org}
- s.rdoc_options = ["--title", "iknow documentation", "--charset", "utf-8", "--opname", "index.html", "--line-numbers", "--main", "README", "--inline-source", "--exclude", "^(examples|extras)/"]
- s.require_paths = ["lib"]
- s.rubyforge_project = %q{iknow}
- s.rubygems_version = %q{1.3.1}
- s.summary = %q{A rubygem for iKnow! APIs}
- s.test_files = ["test/iknow_test.rb"]
-
- if s.respond_to? :specification_version then
- current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
- s.specification_version = 2
-
- if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
- s.add_runtime_dependency(%q<json>, [">= 0"])
- s.add_runtime_dependency(%q<oauth>, [">= 0"])
- else
- s.add_dependency(%q<json>, [">= 0"])
- s.add_dependency(%q<oauth>, [">= 0"])
- end
- else
- s.add_dependency(%q<json>, [">= 0"])
- s.add_dependency(%q<oauth>, [">= 0"])
- end
-end
View
16 lib/iknow.rb
@@ -1,16 +0,0 @@
-module Iknow
-end
-
-require 'date'
-require 'net/https'
-require 'uri'
-
-require 'rubygems'
-require 'json'
-
-require 'ext/hash'
-require 'iknow/core'
-require 'iknow/rest_client'
-require 'iknow/model'
-
-Iknow::Config.init
View
3 lib/iknow/core.rb
@@ -1,3 +0,0 @@
-require 'iknow/core/version'
-require 'iknow/core/config'
-require 'iknow/core/auth'
View
39 lib/iknow/core/auth.rb
@@ -1,39 +0,0 @@
-require 'oauth/consumer'
-
-class Iknow::Auth
- attr_accessor :mode, :auth_token
-
- class Basic
- attr_reader :username, :password
-
- def initialize(username, password)
- @username = username
- @password = password
- end
- end
-
- def initialize(options = {})
- if options[:username] && options[:password]
- @mode = :basic_auth
- @auth_token = Basic.new(options[:username], options[:password])
- elsif options[:token] && options[:secret]
- @mode = :oauth
- @auth_token = OAuth::AccessToken.new(Iknow::Auth.consumer, options[:token], options[:secret])
- else
- raise ArgumentError.new('{:auth => "oauth_access_token", :secret => "oauth_access_token_secret"} or {:username "iknow_username", :password => "iknow_password"} is needed')
- end
- end
-
- def self.consumer
- @@consumer ||= OAuth::Consumer.new(
- Iknow::Config.oauth_consumer_key,
- Iknow::Config.oauth_consumer_secret,
- :http_method => Iknow::Config.oauth_http_method,
- :scheme => Iknow::Config.oauth_scheme,
- :site => Iknow::Config.api_base_url,
- :authorize_url => "#{Iknow::Config.base_url}/oauth/authorize"
- )
- end
-
- alias_method :account, :auth_token
-end
View
51 lib/iknow/core/config.rb
@@ -1,51 +0,0 @@
-require 'singleton'
-
-class Iknow::Config
- include Singleton
- ATTRIBUTES = [ :protocol, :host, :port, :api_protocol, :api_host, :api_port, :api_key, :timeout,
- :oauth_consumer_key, :oauth_consumer_secret, :oauth_http_method, :oauth_scheme,
- :user_agent, :application_name, :application_version, :application_url ]
- attr_accessor *ATTRIBUTES
-
- def self.init(&block)
- conf = Iknow::Config.instance
- { :protocol => 'http',
- :host => 'www.iknow.co.jp',
- :port => 80,
- :api_protocol => 'http',
- :api_host => 'api.iknow.co.jp',
- :api_port => 80,
- :api_key => '',
- :timeout => 30,
- :oauth_consumer_key => '',
- :oauth_consumer_secret => '',
- :oauth_http_method => :post,
- :oauth_scheme => :header,
- :user_agent => 'default',
- :application_name => 'iKnow! Gem',
- :application_version => Iknow::Version.to_version,
- :application_url => 'http://github.com/nov/iknow'
- }.each do |key, value| conf.send("#{key}=", value) end
- yield conf if block_given?
- conf
- end
-
- def base_url
- port = self.port==80 ? nil : ":#{self.port}"
- "#{self.protocol}://#{self.host}#{port}"
- end
-
- def api_base_url
- port = self.api_port==80 ? nil : ":#{self.api_port}"
- "#{self.api_protocol}://#{self.api_host}#{port}"
- end
-
- # hack: Object.timeout is already defined..
- def self.timeout
- instance.timeout
- end
-
- def self.method_missing(method, *args)
- Iknow::Config.instance.send(method, *args)
- end
-end
View
14 lib/iknow/core/version.rb
@@ -1,14 +0,0 @@
-module Iknow::Version
- MAJOR = 0
- MINOR = 2
- REVISION = 4
- class << self
- def to_version
- "#{MAJOR}.#{MINOR}.#{REVISION}"
- end
-
- def to_name
- "#{MAJOR}_#{MINOR}_#{REVISION}"
- end
- end
-end
View
5 lib/iknow/model.rb
@@ -1,5 +0,0 @@
-require 'iknow/model/base'
-require 'iknow/model/user'
-require 'iknow/model/list'
-require 'iknow/model/item'
-require 'iknow/model/sentence'
View
26 lib/iknow/model/base.rb
@@ -1,26 +0,0 @@
-class Iknow::Base
-
- def self.attributes; self::ATTRIBUTES end
-
- def attributes; self.class.attributes end
-
- def self.deserialize(hash, params = {})
- return nil if hash.nil?
-
- klass = params[:as] ? params[:as] : self
- if hash.is_a?(Array)
- hash.inject([]) { |results, hash|
- hash.symbolize_keys!
- results << klass.new(hash)
- }
- else
- hash.symbolize_keys!
- klass.new(hash)
- end
- end
-
- def deserialize(hash, params = {})
- self.class.deserialize(hash, params)
- end
-
-end
View
172 lib/iknow/model/item.rb
@@ -1,172 +0,0 @@
-class Iknow::Item < Iknow::Base
- ATTRIBUTES = [:sentences, :responses, :cue, :id, :list]
- READONLY_ATTRIBUTES = [:sentences, :responses, :cue, :id]
- attr_accessor *(ATTRIBUTES - READONLY_ATTRIBUTES)
- attr_reader *READONLY_ATTRIBUTES
-
- class Response < Iknow::Base
- ATTRIBUTES = [:text, :text_with_character, :type, :language]
- READONLY_ATTRIBUTES = [:type]
- attr_accessor *(ATTRIBUTES - READONLY_ATTRIBUTES)
- attr_reader *READONLY_ATTRIBUTES
-
- def initialize(params = {})
- @text = params[:text]
- @type = params[:type]
- @language = params[:language]
- end
- end
-
- class Cue < Iknow::Base
- ATTRIBUTES = [:text, :sound, :part_of_speech, :language, :transliterations]
- READONLY_ATTRIBUTES = [:sound]
- attr_accessor *(ATTRIBUTES - READONLY_ATTRIBUTES)
- attr_reader *READONLY_ATTRIBUTES
-
- def initialize(params = {})
- @text = params[:text]
- @sound = params[:sound]
- @part_of_speech = params[:part_of_speech]
- @language = params[:language]
- @transliterations = params[:transliterations]
- end
- end
-
- def self.recent(params = {})
- hash = Iknow::RestClient::Item.recent(params)
- self.deserialize(hash) || []
- end
-
- def self.find(item_id, params = {})
- params[:id] = item_id
- hash = Iknow::RestClient::Item.find(params)
- self.deserialize(hash)
- end
-
- def self.matching(keyword, params = {})
- params[:keyword] = keyword
- hash = Iknow::RestClient::Item.matching(params)
- self.deserialize(hash) || []
- end
-
- def self.extract(text, params = {})
- params[:text] = text
- hash = Iknow::RestClient::Item.extract(params)
- self.deserialize(hash) || []
- end
-
- def self.create(iknow_auth, params = {})
- self.new(params).save(iknow_auth)
- end
-
- def initialize(params = {})
- params[:responses] = [params[:response]] if params[:response]
- @id = params[:id].to_i
- @list = params[:list]
- @cue = self.deserialize(params[:cue], :as => Iknow::Item::Cue)
- @responses = self.deserialize(params[:responses], :as => Iknow::Item::Response)
- @sentences = self.deserialize(params[:sentences], :as => Iknow::Sentence)
- end
-
- def save(iknow_auth)
- begin
- item_id = Iknow::RestClient::Item.create(iknow_auth, self.to_post_data)
- rescue
- return false
- end
- Iknow::Item.find(item_id)
- end
-
- def add_image(iknow_auth, params)
- post_params = if params.is_a?(String)
- { 'image[url]' => params }
- else
- image_params = {
- 'image[url]' => params[:url],
- 'image[list_id]' => params[:list_id]
- }
- if params[:attribution]
- attribution_params = {
- 'attribution[media_entity]' => params[:attribution][:media_entity],
- 'attribution[author]' => params[:attribution][:media_entity],
- 'attribution[author_url]' => params[:attribution][:media_entity],
- 'attribution[attribution_license_id]' => params[:attribution][:media_entity]
- }
- image_params.merge(attribution_params)
- else
- image_params
- end
- end
- Iknow::RestClient::Item.add_image(iknow_auth, post_params.merge(:id => self.id))
- end
-
- def add_sound(iknow_auth, params)
- post_params = if params.is_a?(String)
- { 'sound[url]' => params }
- else
- sound_params = {
- 'sound[url]' => params[:url],
- 'sound[list_id]' => params[:list_id]
- }
- if params[:attribution]
- attribution_params = {
- 'attribution[media_entity]' => params[:attribution][:media_entity],
- 'attribution[author]' => params[:attribution][:media_entity],
- 'attribution[author_url]' => params[:attribution][:media_entity],
- 'attribution[attribution_license_id]' => params[:attribution][:media_entity]
- }
- sound_params.merge(attribution_params)
- else
- sound_params
- end
- end
- Iknow::RestClient::Item.add_sound(iknow_auth, post_params.merge(:id => self.id))
- end
-
- def add_tags(iknow_auth, *tags)
- post_params = {}
- tags.each_with_index do |tag, idx|
- if tag.is_a?(String)
- post_params["semantic_tags[#{idx}][name]"] = tag
- else
- post_params["semantic_tags[#{idx}][name]"] = tag[:name]
- post_params["semantic_tags[#{idx}][disambiguation]"] = tag[:disambiguation]
- end
- end
- Iknow::RestClient::Item.add_tags(iknow_auth, post_params.merge(:id => self.id))
- end
-
- protected
-
- def to_post_data
- self.validate
- post_data = {
- 'cue[text]' => self.cue.text,
- 'cue[language]' => self.cue.language,
- 'cue[part_of_speech]' => self.cue.part_of_speech,
- 'response[text]' => self.response.text,
- 'response[language]' => self.response.language
- }
- # Optional attributes
- if self.list
- post_data['item[list_id]'] = self.list.id
- end
- if response.text_with_character
- post_data['character_response[text]'] = self.response.character_text
- end
- post_data
- end
-
- def validate
- raise ArgumentError.new("Item cue[text] is required.") if self.cue.text.nil? or self.cue.text.empty?
- raise ArgumentError.new("Item cue[language] is required.") if self.cue.language.nil? or self.cue.language.empty?
- raise ArgumentError.new("Item cue[part_of_speech] is required.") if self.cue.part_of_speech.nil? or self.cue.part_of_speech.empty?
- raise ArgumentError.new("Item response[text] is required.") if self.response.text.nil? or self.response.text.empty?
- raise ArgumentError.new("Item response[language] is required.") if self.response.language.nil? or self.response.language.empty?
- end
-
- def response
- self.responses.first
- end
-
-end
View
153 lib/iknow/model/list.rb
@@ -1,153 +0,0 @@
-# "iknow": true,
-# "description": "hogehoge",
-# "translation_language": "ja",
-# "dictation": true,
-# "icon": "http://www.iknow.co.jp/assets/courses/m4.jpg",
-# "brainspeed": true,
-# "language": "en",
-# "item_count": 117,
-# "author_id": "Cerego",
-# "user_count": 45056,
-# "author": "Team iKnow!",
-# "title": "\u65c5\u306b\u51fa\u3088\u3046\uff01\uff08\u51fa\u56fd\uff06\u8857\u3092\u6b69\u304f\uff09",
-# "id": 708,
-# "author_url": "http://www.iknow.co.jp/user/Cerego"
-
-class Iknow::List < Iknow::Base
- ATTRIBUTES = [:id, :title, :description, :icon, :square_icon, :item_count, :user_count, :iknow, :dictation, :brainspeed,
- :language, :translation_language, :list_type, :transcript, :embed,
- :tags, :media_entry, :author, :author_id, :author_url, :attribution_license_id,
- :items, :sentences]
- READONLY_ATTRIBUTES = [:id, :icon, :item_count, :user_count, :iknow, :dictation, :brainspeed]
- attr_accessor *(ATTRIBUTES - READONLY_ATTRIBUTES)
- attr_reader *READONLY_ATTRIBUTES
-
- class Application < Iknow::Base
- ATTRIBUTES = [:application, :list_id, :lang]
- attr_reader *ATTRIBUTES
-
- def initialize(params = {})
- @application = params[:application]
- @list_id = params[:list_id]
- @lang = params[:lang]
- end
- def url
- "http://www.iknow.co.jp/flash?swf=#{self.name}&course_id=#{self.list_id}&lang=#{self.lang}"
- end
- end
-
- def self.recent(params = {})
- hash = Iknow::RestClient::List.recent(params)
- self.deserialize(hash) || []
- end
-
- def self.find(list_id, params = {})
- params[:id] = list_id
- hash = Iknow::RestClient::List.find(params)
- self.deserialize(hash)
- end
-
- def self.matching(keyword, params = {})
- params[:keyword] = keyword
- hash = Iknow::RestClient::List.matching(params)
- self.deserialize(hash) || []
- end
-
- def self.create(iknow_auth, params = {})
- self.new(params).save(iknow_auth)
- end
-
- def self.delete(list_id)
- self.find(list_id).delete
- end
-
- def initialize(params = {})
- @id = (params[:id].to_i rescue nil)
- @title = params[:title]
- @description = params[:description]
- @icon = params[:icon]
- @square_icon = params[:square_icon]
- @item_count = (params[:item_count].to_i rescue nil)
- @user_count = (params[:user_count].to_i rescue nil)
- @language = params[:language]
- @translation_language = params[:translation_language]
- if @list_id and @translation_language
- common_settings = {:list_id => @id, :lang => @translation_language}
- @iknow = Application.new(common_settings.merge(:application => 'iknow')) if params[:iknow]
- @dictation = Application.new(common_settings.merge(:application => 'dictation')) if params[:dictation]
- @brainspeed = Application.new(common_settings.merge(:application => 'brainspeed')) if params[:brainspeed]
- end
- @author = params[:author] # display_name or username
- @author_id = params[:author_id] # username
- @author_url = params[:author_url]
- @list_type = params[:list_type] # for list creation
- @transcript = params[:transcript] # for list creation
- @embed = params[:embed] # for list creation
- @tags = params[:tags] # for list creation
- @media_entry = params[:media_entry] # for list creation
- @attribution_license_id = params[:attribution_license_id] # for list creation
- @items = self.deserialize(params[:items], :as => Iknow::Item)
- @sentences = self.deserialize(params[:sentences], :as => Iknow::Sentence)
- end
-
- def items(params = {})
- hash = Iknow::RestClient::List.items(params.merge(:id => self.id))
- self.deserialize(hash, :as => Iknow::Item) || []
- end
-
- def sentences(params = {})
- hash = Iknow::RestClient::List.sentences(params.merge(:id => self.id))
- self.deserialize(hash, :as => Iknow::Sentence) || []
- end
-
- def save(iknow_auth)
- begin
- list_id = Iknow::RestClient::List.create(iknow_auth, self.to_post_data)
- rescue
- return false
- end
- Iknow::List.find(list_id)
- end
-
- def delete(iknow_auth)
- Iknow::RestClient::List.delete(iknow_auth, {:id => self.id})
- end
- alias_method :destroy, :delete
-
- def add_item(iknow_auth, item)
- Iknow::RestClient::List.add_item(iknow_auth, {:list_id => self.id, :id => item.id})
- end
-
- def delete_item(iknow_auth, item)
- Iknow::RestClient::List.delete_item(iknow_auth, {:list_id => self.id, :id => item.id})
- end
-
- protected
-
- def to_post_data
- self.validate
- post_data = {
- 'list[name]' => self.title,
- 'list[description]' => self.description,
- 'list[language]' => self.language || 'en',
- 'list[translation_language]' => self.translation_language || 'ja'
- }
- # Optional attributes
- if self.list_type
- post_data['list[type]'] = self.list_type
- end
- [ :transcript, :embed, :tags, :media_entry,
- :author, :author_url, :attribution_license_id ].each do |key|
- if self.send("#{key}")
- post_data["list[#{key}]"] = self.send("#{key}")
- end
- end
- post_data
- end
-
- def validate
- raise ArgumentError.new("List title is required.") if self.title.nil? or self.title.empty?
- raise ArgumentError.new("List description is required.") if self.description.nil? or self.description.empty?
- end
-
-end
View
138 lib/iknow/model/sentence.rb
@@ -1,138 +0,0 @@
-class Iknow::Sentence < Iknow::Base
- ATTRIBUTES = [:sound, :image, :square_image, :text, :language, :id, :transliterations, :translations, :item, :list]
- READONLY_ATTRIBUTES = [:id]
- attr_accessor *(ATTRIBUTES - READONLY_ATTRIBUTES)
- attr_reader *READONLY_ATTRIBUTES
-
- def self.recent(params = {})
- hash = Iknow::RestClient::Sentence.recent(params)
- self.deserialize(hash) || []
- end
-
- def self.find(sentence_id, params = {})
- params[:id] = sentence_id
- hash = Iknow::RestClient::Sentence.find(params)
- self.deserialize(hash)
- end
-
- def self.matching(keyword, params = {})
- params[:keyword] = keyword
- hash = Iknow::RestClient::Sentence.matching(params)
- self.deserialize(hash) || []
- end
-
- def self.create(iknow_auth, params = {})
- self.new(params).save(iknow_auth)
- end
-
- def initialize(params = {})
- params[:translations] = [params[:translation]] if params[:translation]
- params[:transliterations] = [params[:transliteration]] if params[:transliteration]
- @id = params[:id]
- @item = params[:item]
- @list = params[:list]
- @sound = params[:sound]
- @image = params[:image]
- @square_image = params[:square_image]
- @text = params[:text]
- @language = params[:language]
- @transliterations = params[:transliterations]
- @translations = self.deserialize(params[:translations], :as => Iknow::Sentence)
- end
-
- def save(iknow_auth)
- begin
- sentence_id = Iknow::RestClient::Sentence.create(iknow_auth, self.to_post_data)
- # rescue
- # return false
- end
- Iknow::Sentence.find(sentence_id)
- end
-
- def add_image(iknow_auth, params)
- post_params = if params.is_a?(String)
- { 'image[url]' => params }
- else
- image_params = {
- 'image[url]' => params[:url],
- 'image[list_id]' => params[:list_id]
- }
- if params[:attribution]
- attribution_params = {
- 'attribution[media_entity]' => params[:attribution][:media_entity],
- 'attribution[author]' => params[:attribution][:media_entity],
- 'attribution[author_url]' => params[:attribution][:media_entity],
- 'attribution[attribution_license_id]' => params[:attribution][:media_entity]
- }
- image_params.merge(attribution_params)
- else
- image_params
- end
- end
- Iknow::RestClient::Sentence.add_image(iknow_auth, post_params.merge(:id => self.id))
- end
-
- def add_sound(iknow_auth, params)
- post_params = if params.is_a?(String)
- { 'sound[url]' => params }
- else
- sound_params = {
- 'sound[url]' => params[:url],
- 'sound[list_id]' => params[:list_id]
- }
- if params[:attribution]
- attribution_params = {
- 'attribution[media_entity]' => params[:attribution][:media_entity],
- 'attribution[author]' => params[:attribution][:media_entity],
- 'attribution[author_url]' => params[:attribution][:media_entity],
- 'attribution[attribution_license_id]' => params[:attribution][:media_entity]
- }
- sound_params.merge(attribution_params)
- else
- sound_params
- end
- end
- Iknow::RestClient::Sentence.add_sound(iknow_auth, post_params.merge(:id => self.id))
- end
-
- protected
-
- def to_post_data
- self.validate
- post_data = {
- 'item_id' => self.item.id,
- 'sentence[text]' => self.text
- }
- # Optional attributes
- if self.list
- post_data['sentence[list_id]'] = self.list.id
- end
- [:language, :transliteration].each do |key|
- if self.send("#{key}")
- post_data["sentence[#{key}]"] = self.send("#{key}")
- end
- end
- if self.translation
- [:text, :language, :transliteration].each do |key|
- if self.translation.send("#{key}")
- post_data["translation[#{key}]"] = self.translation.send("#{key}")
- end
- end
- end
- post_data
- end
-
- def validate
- raise ArgumentError.new("Item is required.") unless self.item
- raise ArgumentError.new("Sentence text is required.") if self.text.nil? or self.text.empty?
- end
-
- def translation
- self.translations.first rescue nil
- end
-
- def transliteration
- self.transliterations.first rescue nil
- end
-
-end
View
103 lib/iknow/model/user.rb
@@ -1,103 +0,0 @@
-class Iknow::User < Iknow::Base
- ATTRIBUTES = [:username, :profile]
- attr_reader *ATTRIBUTES
-
- class Profile < Iknow::Base
- ATTRIBUTES = [:name, :gender, :birthday, :description, :blog_url, :profile_url, :foaf_url, :icon_url]
- attr_reader *ATTRIBUTES
-
- def initialize(params = {})
- @name = params[:name]
- @gender = params[:gender]
- @birthday = (Date.parse(params[:birthday]) rescue nil)
- @description = params[:description]
- @blog_url = params[:blog_url]
- @profile_url = params[:profile_url]
- @foaf_url = params[:foaf_url]
- @icon_url = params[:icon_url]
- end
- end
-
- class Study < Iknow::Base
- ATTRIBUTES = [:today, :results, :total_summary]
- attr_reader *ATTRIBUTES
-
- class Result < Iknow::Base
- ATTRIBUTES = [:timestamp, :seconds, :totals, :seen, :completed, :date]
- attr_reader *ATTRIBUTES
-
- def initialize(params = {})
- @timestamp = (params[:timestamp].to_i rescue nil)
- @seconds = (params[:seconds].to_i rescue nil)
- @totals = {
- :seconds => (params[:totals][:seconds].to_i rescue nil),
- :seen => (params[:totals][:seen].to_i rescue nil),
- :completed => (params[:totals][:completed].to_i rescue nil)
- }
- @seen = (params[:seen].to_i rescue nil)
- @completed = (params[:completed].to_i rescue nil)
- @date = (Date.parse(params[:date]) rescue nil)
- end
- end
-
- class TotalSummary < Iknow::Base
- ATTRIBUTES = [:studied, :completed, :performance, :best_speed, :best_score]
- attr_reader *ATTRIBUTES
-
- def initialize(params = {})
- @studied = params[:studied]
- @completed = params[:completed]
- @performance = params[:performance]
- @best_speed = params[:best_speed]
- @best_score = params[:best_score]
- end
- end
-
- def initialize(params = {})
- @today = (Date.parse(params[:today]) rescue nil)
- @results = self.deserialize(params[:study_results], :as => Iknow::User::Study::Result)
- @total_summary = self.deserialize(params[:total_summary], :as => Iknow::User::Study::TotalSummary)
- end
-
- end
-
- def self.find(username, params = {})
- params[:username] = username
- hash = Iknow::RestClient::User.find(params)
- self.deserialize(hash)
- end
-
- def self.matching(keyword, params = {})
- params[:keyword] = keyword
- hash = Iknow::RestClient::User.matching(params)
- self.deserialize(hash) || []
- end
-
- def initialize(params)
- @profile = Profile.new(params[:profile])
- @username = params[:username]
- end
-
- def items(params = {})
- hash = Iknow::RestClient::User.items(params.merge(:username => self.username))
- self.deserialize(hash, :as => Iknow::Item) || []
- end
-
- def lists(params = {})
- hash = Iknow::RestClient::User.lists(params.merge(:username => self.username))
- self.deserialize(hash, :as => Iknow::List) || []
- end
-
- def friends(params = {})
- hash = Iknow::RestClient::User.friends(params.merge(:username => self.username))
- self.deserialize(hash) || []
- end
-
- def study(params = {})
- params[:application] ||= 'iknow'
- return nil unless ['iknow', 'dictation', 'brainspeed', ].include?(params[:application])
- hash = Iknow::RestClient::User.study_results(params.merge(:username => self.username))
- self.deserialize(hash, :as => Iknow::User::Study)
- end
-
-end
View
8 lib/iknow/rest_client.rb
@@ -1,8 +0,0 @@
-module Iknow::RestClient
-end
-
-require 'iknow/rest_client/base'
-require 'iknow/rest_client/user'
-require 'iknow/rest_client/list'
-require 'iknow/rest_client/item'
-require 'iknow/rest_client/sentence'
View
173 lib/iknow/rest_client/base.rb
@@ -1,173 +0,0 @@
-require 'timeout'
-
-class Iknow::RestClient::Base
-
- class RESTError < Exception
- attr_accessor :code, :message
-
- def initialize(params = {})
- self.code = params[:code]
- self.message = params[:message]
- end
-
- def to_s
- "HTTP #{@code}: #{@message}"
- end
- end
-
- def self.valid_action?(action) ; self::ACTIONS.keys.include? action.to_sym end
- def self.path(action) ; self::ACTIONS[action.to_sym][:path] end
- def self.http_method(action) ; self::ACTIONS[action.to_sym][:http_method] || :get end
-
- def self.method_missing(action, *args)
- # GET methods are handled here
- # POST and DELETE methods should be implemented in each class
- super unless self.valid_action?(action)
- case self.http_method(action)
- when :get
- path, params = path_with_params(self.path(action), args[0])
- http_get(path, params)
- when :post
- path, params = path_with_params(self.path(action), args[1])
- http_post(iknow_auth(args[0]), path, params)
- when :delete
- path, params = path_with_params(self.path(action), args[1])
- http_delete(iknow_auth(args[0]), path, params)
- end
- end
-
- private
-
- def self.config; Iknow::Config end
-
- def self.iknow_auth(iknow_auth)
- if iknow_auth.is_a?(Iknow::Auth)
- iknow_auth
- else
- raise ArgumentError.new("Authorized Iknow::Auth instance is required")
- end
- end
-
- def self.api_key_required
- raise ArgumentError.new("iKnow! API key is required") if self.config.api_key == ''
- end
-
- def self.raise_rest_error(response)
- raise RESTError.new(:code => response.code, :message => response.message)
- end
-
- def self.handle_rest_response(response, format)
- raise_rest_error(response) unless response.is_a?(Net::HTTPSuccess)
- case format
- when :json
- handle_json_response(response.body)
- when :nothing
- # success => nothing / failure => json error
- begin
- handle_json_response(response.body)
- rescue Exception => e
- e.is_a?(RESTError) ? raise(e) : :success
- end
- else
- begin
- handle_json_response(response.body)
- rescue Exception => e
- e.is_a?(RESTError) ? raise(e) : response.body
- end
- end
- end
-
- def self.handle_json_response(json_response)
- hash = JSON.parse(json_response)
- unless (hash['error'].nil? rescue :success) # success response may be Array, not Hash.
- if hash['error']['code'] == 404
- return nil
- else
- raise RESTError.new(:code => hash['error']['code'], :message => hash['error']['message'])
- end
- end
- hash
- end
-
- def self.http_header
- @@http_header ||= {
- 'User-Agent' => "#{self.config.application_name} v#{Iknow::Version.to_version} [#{self.config.user_agent}]",
- 'Accept' => 'text/x-json',
- 'X-iKnow-Gem-Client' => self.config.application_name,
- 'X-iKnow-Gem-Client-Version' => self.config.application_version,
- 'X-iKnow-Gem-Client-URL' => self.config.application_url,
- }
- end
-
- def self.http_connect
- http = Net::HTTP.new(self.config.api_host, self.config.api_port)
- http.start do |conn|
- request, format = yield
- begin
- timeout(self.config.timeout) do
- response = conn.request(request)
- handle_rest_response(response, format)
- end
- rescue
- raise RESTError.new(:code => 408, :message => "iKnow! Gem Timeout (#{self.config.timeout} [sec])")
- end
- end
- end
-
- def self.path_with_params(path, params = {})
- path_with_params = path.clone
- unless params.empty?
- params.each do |key, value|
- if path_with_params=~/__#{key}__/
- path_with_params.sub!(/__#{key}__/, URI.encode(value.to_s))
- params.delete(key)
- end
- end
- end
- return path_with_params, params
- end
-
- def self.http_get(path, params = {})
- http_connect do
- params.merge!(:api_key => self.config.api_key) unless self.config.api_key == ''
- path = (params.size > 0) ? "#{path}?#{params.to_http_str}" : path
- get_req = Net::HTTP::Get.new(path, http_header)
- [get_req, :json]
- end
- end
-
- def self.http_post(iknow_auth, path, params = {})
- self.api_key_required
- params.merge!(:api_key => self.config.api_key)
- case iknow_auth.mode
- when :oauth
- response = iknow_auth.auth_token.post(path, params, http_header)
- handle_rest_response(response, :text)
- when :basic_auth
- http_connect do
- post_req = Net::HTTP::Post.new(path, http_header)
- post_req.body = params.to_http_str
- post_req.basic_auth(iknow_auth.account.username, iknow_auth.account.password)
- [post_req, :text]
- end
- end
- end
-
- def self.http_delete(iknow_auth, path, params = {})
- self.api_key_required
- params.merge!(:api_key => self.config.api_key)
- case iknow_auth.mode
- when :oauth
- response = iknow_auth.auth_token.delete(path, params.stringfy_keys!.stringfy_values!)
- handle_rest_response(response, :nothing)
- when :basic_auth
- http_connect do
- delete_req = Net::HTTP::Post.new(path, http_header)
- delete_req.body = params.merge(:_method => 'DELETE').to_http_str
- delete_req.basic_auth(iknow_auth.account.username, iknow_auth.account.password)
- [delete_req, :nothing]
- end
- end
- end
-
-end
View
14 lib/iknow/rest_client/item.rb
@@ -1,14 +0,0 @@
-class Iknow::RestClient::Item < Iknow::RestClient::Base
-
- ACTIONS = {
- :recent => { :path => '/items' },
- :find => { :path => '/items/__id__' },
- :matching => { :path => '/items/matching/__keyword__' },
- :extract => { :path => '/items/extract', },
- :create => { :path => '/items', :http_method => :post },
- :add_image => { :path => '/items/__id__/images', :http_method => :post },
- :add_sound => { :path => '/items/__id__/sounds', :http_method => :post },
- :add_tags => { :path => '/items/__id__/tags', :http_method => :post }
- }
-
-end
View
15 lib/iknow/rest_client/list.rb
@@ -1,15 +0,0 @@
-class Iknow::RestClient::List < Iknow::RestClient::Base
-
- ACTIONS = {
- :recent => { :path => '/lists' },
- :find => { :path => '/lists/__id__' },
- :items => { :path => '/lists/__id__/items' },
- :sentences => { :path => '/lists/__id__/sentences' },
- :matching => { :path => '/lists/matching/__keyword__' },
- :create => { :path => '/lists', :http_method => :post },
- :delete => { :path => '/lists/__id__', :http_method => :delete },
- :add_item => { :path => '/lists/__list_id__/items', :http_method => :post },
- :delete_item => { :path => '/lists/__list_id__/items/__id__', :http_method => :delete }
- }
-
-end
View
12 lib/iknow/rest_client/sentence.rb
@@ -1,12 +0,0 @@
-class Iknow::RestClient::Sentence < Iknow::RestClient::Base
-
- ACTIONS = {
- :recent => { :path => '/sentences' },
- :find => { :path => '/sentences/__id__' },
- :matching => { :path => '/sentences/matching/__keyword__' },
- :create => { :path => '/sentences', :http_method => :post },
- :add_image => { :path => '/sentences/__id__/images', :http_method => :post },
- :add_sound => { :path => '/sentences/__id__/sounds', :http_method => :post }
- }
-
-end
View
12 lib/iknow/rest_client/user.rb
@@ -1,12 +0,0 @@
-class Iknow::RestClient::User < Iknow::RestClient::Base
-
- ACTIONS = {
- :find => { :path => '/users/__username__' },
- :lists => { :path => '/users/__username__/lists' },
- :items => { :path => '/users/__username__/items' },
- :friends => { :path => '/users/__username__/friends' },
- :study_results => { :path => '/users/__username__/study_results/__application__' },
- :matching => { :path => '/users/matching/__keyword__' }
- }
-
-end
View
8 test/iknow_test.rb
@@ -1,8 +0,0 @@
-require File.dirname(__FILE__) + '/test_helper.rb'
-
-require "test/unit"
-class IknowTest < Test::Unit::TestCase
- def test_truth
- true
- end
-end
View
2 test/test_helper.rb
@@ -1,3 +1,3 @@
require 'test/unit'
-require File.dirname(__FILE__) + '/../lib/iknow'
+require File.dirname(__FILE__) + '/../lib/smartfm'

0 comments on commit b59e610

Please sign in to comment.
Something went wrong with that request. Please try again.