lib/nowtv/client.rb in nowtv-0.0.2 vs lib/nowtv/client.rb in nowtv-0.0.3
- old
+ new
@@ -4,58 +4,60 @@
require 'time'
require 'nkf'
module Nowtv
class Client
- API_URL = 'http://asp.tvguide.or.jp/api/broadcasting?region_code='
- REGION_URL = 'http://asp.tvguide.or.jp/api/regions'
+ API_URL = 'http://www.tvguide.or.jp/TXML301PG.php?type=TVG®ionId='
- def get_program_list(region)
- programs = get_programs(region)
-
- unless programs.length > 1
- region_code_by_name = get_region_code(region)
-
- unless region_code_by_name
- $stderr.puts 'Failed to get programs!'
- return nil
- end
-
- programs = get_programs(region_code_by_name)
- end
-
+ def get_program_list(region_id)
+ programs = get_programs(region_id)
restruct_program_list(programs)
+ rescue
+ raise ParseError, "Failed to parse program data"
end
- def get_programs(region_code)
- url = API_URL + region_code
- JSON.parse(open(url).read.sub(/^\(/, '').sub(/\)$/, ''))['programs']
- rescue
- []
+ private
+
+ def get_programs(region_id)
+ url = API_URL + region_id.to_s
+ JSON.parse(open(url).read)["ProgramScheduleInfomartion"]["MediaLocation"]["StationLocation"]
end
def restruct_program_list(programs)
programs.map do |program|
+ info = program["ProgramInformation"]
+
{
- station: NKF.nkf("-wZ0", program["station_name"]),
- title: NKF.nkf("-wZ0", program["title"]).gsub(" ", " "),
- start_time: Time.parse(program["start"]).strftime("%H:%M"),
- end_time: Time.parse(program["end"]).strftime("%H:%M")
+ station: half_width(program["stationDispName"]),
+ title: half_width(info["programTitle"]),
+ start_time: parse_datetime(info["startDateTime"]),
+ end_time: parse_datetime(info["endDateTime"])
}
end
end
- def get_region_list
- regions = JSON.parse(open(REGION_URL).read.sub(/^\(/, '').sub(/\)$/, ''))['regions']
- result = {}
- regions.each { |region| result[region["name"].to_sym] = region["code"] }
- result
- rescue
- {}
+ def half_width(str)
+ NKF.nkf("-wZ0", str).gsub(" ", " ")
end
- def get_region_code(region_name)
- region_list = get_region_list
- region_list[region_name.to_sym]
+ def parse_datetime(datetime)
+ date, time = datetime.split(" ")
+ hour, minute = time.split(":").map(&:to_i)
+
+ hour >= 24 ? parse_midnight_time(date, hour, minute) : Time.parse(datetime)
end
+
+ def parse_midnight_time(date_str, hour, minute)
+ day_add = hour / 24
+ hour %= 24
+
+ datetime = Time.parse(date_str)
+ datetime += day_add * 60 * 60 * 24
+ datetime += hour * 60 * 60
+ datetime += minute * 60
+
+ datetime
+ end
end
+
+ class ParseError < StandardError; end
end