diff --git a/db/migrations/0001_create_database.rb b/db/migrations/0001_create_database.rb index 0dbf88b..9280dbc 100644 --- a/db/migrations/0001_create_database.rb +++ b/db/migrations/0001_create_database.rb @@ -8,6 +8,7 @@ Sequel.migration do create_table(:movies) do primary_key :id String :data, text: true, null: false + FalseClass :added, null: false, default: false FalseClass :viewed, null: false, default: false FalseClass :downloaded, null: false, default: false end diff --git a/lib/librarix/application.rb b/lib/librarix/application.rb index 6abfbbb..6472263 100644 --- a/lib/librarix/application.rb +++ b/lib/librarix/application.rb @@ -18,11 +18,9 @@ module Librarix end def json_params - begin - JSON.parse(request.body.read) - rescue - halt 400, { message:'Invalid JSON' }.to_json - end + JSON.parse(request.body.read) + rescue + halt 400, { message:'Invalid JSON' }.to_json end end @@ -38,24 +36,27 @@ module Librarix namespace '/movies' do get '' do - Librarix::Filter.new(params).movies.to_json + Librarix::Models::Movie.where(added: true).all.to_json end - post '' do - id = json_params['tmdb_id'].to_i - movie = Tmdb::Movie.detail(id) + get '/popular' do + Librarix::Models::Movie.popular.to_json + end - if movie['status_code'] != 34 && !Librarix::Redis::Movie.new(id).added? - Librarix::Redis::Movie.new(id).add.to_json - end + get '/search' do end get '/:id' do |id| - Librarix::Models::Movie.find(id: id).to_json + Librarix::Models::Movie.find_or_fetch(id).to_json + end + + post '/:id' do + Librarix::Models::Movie.find_or_fetch(id).add! + {success: true}.to_json end get '/:id/fetch' do |id| - Librarix::Models::Movie.fetch(85).to_json + Librarix::Models::Movie.fetch(id).to_json end patch '/:id/view' do |id| diff --git a/lib/librarix/models/movie.rb b/lib/librarix/models/movie.rb index 50c48be..0a4685e 100644 --- a/lib/librarix/models/movie.rb +++ b/lib/librarix/models/movie.rb @@ -1,4 +1,16 @@ class Librarix::Models::Movie < Sequel::Model + def self.popular + unrestrict_primary_key + + Tmdb::Search.new('/movie/popular').fetch.map do |m| + find_or_create(id: m['id']) { |movie| movie.data = m } + end + end + + def self.find_or_fetch(id) + find(id: id) || fetch(id) + end + def self.fetch(id) unrestrict_primary_key @@ -14,10 +26,15 @@ class Librarix::Models::Movie < Sequel::Model def fetch! tmdb_data = Tmdb::Movie.detail(id) + return if tmdb_data['status_code'] == 34 + self.data = tmdb_data save genres_id = data['genres'].map { |g| g['id'] } + + Librarix::Models::Genre.fetch if Librarix::Models::Genre.empty? + Librarix::Models::Genre.where(id: genres_id).all.each do |genre| add_genre(genre) unless genres.include?(genre) end @@ -25,6 +42,11 @@ class Librarix::Models::Movie < Sequel::Model self end + def add! + self.added = true + save + end + def download! self.downloaded = !downloaded save