Add more methods to manage movies through API

master
Guillaume Dott 2019-06-28 12:54:44 +02:00
parent eef60a8420
commit 3a969d5344
3 changed files with 38 additions and 14 deletions

View File

@ -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

View File

@ -18,13 +18,11 @@ module Librarix
end
def json_params
begin
JSON.parse(request.body.read)
rescue
halt 400, { message:'Invalid JSON' }.to_json
end
end
end
before do
content_type 'application/json'
@ -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)
if movie['status_code'] != 34 && !Librarix::Redis::Movie.new(id).added?
Librarix::Redis::Movie.new(id).add.to_json
get '/popular' do
Librarix::Models::Movie.popular.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|

View File

@ -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