#14 作成は完了
This commit is contained in:
@@ -36,37 +36,16 @@ class PostsController < ApplicationController
|
|||||||
|
|
||||||
# POST /posts
|
# POST /posts
|
||||||
def create
|
def create
|
||||||
|
logger.info ">>> thumbnail: #{params[:thumbnail]&.content_type}"
|
||||||
|
logger.info ">>> filename: #{params[:thumbnail]&.original_filename}"
|
||||||
|
|
||||||
return head :unauthorized unless current_user
|
return head :unauthorized unless current_user
|
||||||
return head :forbidden unless ['admin', 'member'].include?(current_user.role)
|
return head :forbidden unless ['admin', 'member'].include?(current_user.role)
|
||||||
|
|
||||||
# TODO: URL が正規のものがチェック,不正ならエラー
|
# TODO: URL が正規のものがチェック,不正ならエラー
|
||||||
title = params[:title]
|
title = params[:title]
|
||||||
unless title.present?
|
|
||||||
# TODO: # 既知サイトなら決まったフォーマットで title 取得するやぅに.
|
|
||||||
begin
|
|
||||||
html = URI.open(params[:url], open_timeout: 5, read_timeout: 5).read
|
|
||||||
doc = Nokogiri::HTML.parse(html)
|
|
||||||
title = doc.at('title')&.text&.strip || ''
|
|
||||||
rescue
|
|
||||||
title = ''
|
|
||||||
end
|
|
||||||
end
|
|
||||||
post = Post.new(title: title, url: params[:url], thumbnail_base: '', uploaded_user: current_user)
|
post = Post.new(title: title, url: params[:url], thumbnail_base: '', uploaded_user: current_user)
|
||||||
if params[:thumbnail].present?
|
post.thumbnail.attach(params[:thumbnail])
|
||||||
post.thumbnail.attach(params[:thumbnail])
|
|
||||||
else
|
|
||||||
# TODO: 既知ドメインであれば指定のアドレスからサムネールを取得するやぅにする.
|
|
||||||
path = Rails.root.join('tmp', "thumb_#{ SecureRandom.hex }.png")
|
|
||||||
system("node #{ Rails.root }/lib/screenshot.js #{ Shellwords.escape(params[:url]) } #{ path }")
|
|
||||||
if File.exist?(path)
|
|
||||||
image = MiniMagick::Image.open(path)
|
|
||||||
image.resize '180x180'
|
|
||||||
post.thumbnail.attach(io: File.open(image.path),
|
|
||||||
filename: 'thumbnail.png',
|
|
||||||
content_type: 'image/png')
|
|
||||||
File.delete(path) rescue nil
|
|
||||||
end
|
|
||||||
end
|
|
||||||
if post.save
|
if post.save
|
||||||
post.resized_thumbnail!
|
post.resized_thumbnail!
|
||||||
if params[:tags].present?
|
if params[:tags].present?
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
class PreviewController < ApplicationController
|
||||||
|
def title
|
||||||
|
# TODO: # 既知サイトなら決まったフォーマットで title 取得するやぅに.
|
||||||
|
return head :unauthorized unless current_user
|
||||||
|
|
||||||
|
url = params[:url]
|
||||||
|
return head :bad_request unless url.present?
|
||||||
|
|
||||||
|
html = URI.open(url, open_timeout: 5, read_timeout: 5).read
|
||||||
|
doc = Nokogiri::HTML.parse(html)
|
||||||
|
title = doc.at('title')&.text&.strip
|
||||||
|
|
||||||
|
render json: { title: title }
|
||||||
|
rescue => e
|
||||||
|
render json: { error: e.message }, status: :bad_request
|
||||||
|
end
|
||||||
|
|
||||||
|
def thumbnail
|
||||||
|
# TODO: 既知ドメインであれば指定のアドレスからサムネールを取得するやぅにする.
|
||||||
|
return head :unauthorized unless current_user
|
||||||
|
|
||||||
|
url = params[:url]
|
||||||
|
return head :bad_request unless url.present?
|
||||||
|
|
||||||
|
path = Rails.root.join('tmp', "thumb_#{ SecureRandom.hex }.png")
|
||||||
|
system("node #{ Rails.root }/lib/screenshot.js #{ Shellwords.escape(url) } #{ path }")
|
||||||
|
|
||||||
|
if File.exist?(path)
|
||||||
|
image = MiniMagick::Image.open(path)
|
||||||
|
image.resize '180x180'
|
||||||
|
File.delete(path) rescue nil
|
||||||
|
send_file image.path, type: 'image/png', disposition: 'inline'
|
||||||
|
else
|
||||||
|
render json: { error: 'Failed to generate thumbnail' }, status: :internal_server_error
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -52,6 +52,8 @@ Rails.application.routes.draw do
|
|||||||
get "ip_addresses/create"
|
get "ip_addresses/create"
|
||||||
get "ip_addresses/update"
|
get "ip_addresses/update"
|
||||||
get "ip_addresses/destroy"
|
get "ip_addresses/destroy"
|
||||||
|
get 'preview/title', to: 'preview#title'
|
||||||
|
get 'preview/thumbnail', to: 'preview#thumbnail'
|
||||||
root 'home#index'
|
root 'home#index'
|
||||||
|
|
||||||
resources :posts
|
resources :posts
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ void (async () => {
|
|||||||
|
|
||||||
const page = await browser.newPage ()
|
const page = await browser.newPage ()
|
||||||
await page.setViewport ({ width: 960, height: 960 })
|
await page.setViewport ({ width: 960, height: 960 })
|
||||||
await page.goto (url, { waitUntil: 'networkidle2', timeout: 10000 })
|
await page.goto (url, { waitUntil: 'networkidle2', timeout: 15000 })
|
||||||
|
|
||||||
await page.screenshot ({ path: output })
|
await page.screenshot ({ path: output })
|
||||||
await browser.close ()
|
await browser.close ()
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
require "test_helper"
|
||||||
|
|
||||||
|
class PreviewControllerTest < ActionDispatch::IntegrationTest
|
||||||
|
# test "the truth" do
|
||||||
|
# assert true
|
||||||
|
# end
|
||||||
|
end
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useEffect, useState } from 'react'
|
import React, { useEffect, useState, useRef } from 'react'
|
||||||
import { Link, useLocation, useParams, useNavigate } from 'react-router-dom'
|
import { Link, useLocation, useParams, useNavigate } from 'react-router-dom'
|
||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import { API_BASE_URL, SITE_TITLE } from '../config'
|
import { API_BASE_URL, SITE_TITLE } from '../config'
|
||||||
@@ -28,21 +28,22 @@ const PostNewPage = () => {
|
|||||||
|
|
||||||
const [title, setTitle] = useState ('')
|
const [title, setTitle] = useState ('')
|
||||||
const [titleAutoFlg, setTitleAutoFlg] = useState (true)
|
const [titleAutoFlg, setTitleAutoFlg] = useState (true)
|
||||||
|
const [titleLoading, setTitleLoading] = useState (false)
|
||||||
const [url, setURL] = useState ('')
|
const [url, setURL] = useState ('')
|
||||||
const [thumbnailFile, setThumbnailFile] = useState<File | null> (null)
|
const [thumbnailFile, setThumbnailFile] = useState<File | null> (null)
|
||||||
const [thumbnailPreview, setThumbnailPreview] = useState<string> ('')
|
const [thumbnailPreview, setThumbnailPreview] = useState<string> ('')
|
||||||
const [thumbnailAutoFlg, setThumbnailAutoFlg] = useState (true)
|
const [thumbnailAutoFlg, setThumbnailAutoFlg] = useState (true)
|
||||||
|
const [thumbnailLoading, setThumbnailLoading] = useState (false)
|
||||||
const [tags, setTags] = useState<Tag[]> ([])
|
const [tags, setTags] = useState<Tag[]> ([])
|
||||||
const [tagIds, setTagIds] = useState<number[]> ([])
|
const [tagIds, setTagIds] = useState<number[]> ([])
|
||||||
|
const previousURLRef = useRef ('')
|
||||||
|
|
||||||
const handleSubmit = () => {
|
const handleSubmit = () => {
|
||||||
const formData = new FormData ()
|
const formData = new FormData ()
|
||||||
if (title)
|
formData.append ('title', title)
|
||||||
formData.append ('title', title)
|
|
||||||
formData.append ('url', url)
|
formData.append ('url', url)
|
||||||
formData.append ('tags', JSON.stringify (tagIds))
|
formData.append ('tags', JSON.stringify (tagIds))
|
||||||
if (!(thumbnailAutoFlg) && thumbnailFile)
|
formData.append ('thumbnail', thumbnailFile)
|
||||||
formData.append ('thumbnail', thumbnailFile)
|
|
||||||
|
|
||||||
void (axios.post (`${ API_BASE_URL }/posts`, formData, { headers: {
|
void (axios.post (`${ API_BASE_URL }/posts`, formData, { headers: {
|
||||||
'Content-Type': 'multipart/form-data',
|
'Content-Type': 'multipart/form-data',
|
||||||
@@ -63,6 +64,61 @@ const PostNewPage = () => {
|
|||||||
.catch (() => toast ({ title: 'タグ一覧の取得失敗' })))
|
.catch (() => toast ({ title: 'タグ一覧の取得失敗' })))
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (titleAutoFlg && url)
|
||||||
|
fetchTitle ()
|
||||||
|
}, [titleAutoFlg])
|
||||||
|
|
||||||
|
useEffect (() => {
|
||||||
|
if (thumbnailAutoFlg && url)
|
||||||
|
fetchThumbnail ()
|
||||||
|
}, [thumbnailAutoFlg])
|
||||||
|
|
||||||
|
const handleURLBlur = () => {
|
||||||
|
if (!(url) || url === previousURLRef.current)
|
||||||
|
return
|
||||||
|
|
||||||
|
if (titleAutoFlg)
|
||||||
|
fetchTitle ()
|
||||||
|
if (thumbnailAutoFlg)
|
||||||
|
fetchThumbnail ()
|
||||||
|
previousURLRef.current = url
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchTitle = () => {
|
||||||
|
setTitle ('')
|
||||||
|
setTitleLoading (true)
|
||||||
|
void (axios.get (`${ API_BASE_URL }/preview/title`, {
|
||||||
|
params: { url },
|
||||||
|
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' } })
|
||||||
|
.then (res => {
|
||||||
|
setTitle (res.data.title || '')
|
||||||
|
setTitleLoading (false)
|
||||||
|
})
|
||||||
|
.finally (() => setTitleLoading (false)))
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchThumbnail = () => {
|
||||||
|
setThumbnailPreview ('')
|
||||||
|
setThumbnailFile (null)
|
||||||
|
setThumbnailLoading (true)
|
||||||
|
if (thumbnailPreview)
|
||||||
|
URL.revokeObjectURL (thumbnailPreview)
|
||||||
|
void (axios.get (`${ API_BASE_URL }/preview/thumbnail`, {
|
||||||
|
params: { url },
|
||||||
|
headers: { 'X-Transfer-Code': localStorage.getItem ('user_code') || '' },
|
||||||
|
responseType: 'blob' })
|
||||||
|
.then (res => {
|
||||||
|
const imageURL = URL.createObjectURL (res.data)
|
||||||
|
setThumbnailPreview (imageURL)
|
||||||
|
setThumbnailFile (new File ([res.data],
|
||||||
|
'thumbnail.png',
|
||||||
|
{ type: res.data.type || 'image/png' }))
|
||||||
|
setThumbnailLoading (false)
|
||||||
|
})
|
||||||
|
.finally (() => setThumbnailLoading (false)))
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-xl mx-auto p-4 space-y-4">
|
<div className="max-w-xl mx-auto p-4 space-y-4">
|
||||||
<h1 className="text-2xl font-bold mb-2">広場に投稿を追加する</h1>
|
<h1 className="text-2xl font-bold mb-2">広場に投稿を追加する</h1>
|
||||||
@@ -74,7 +130,8 @@ const PostNewPage = () => {
|
|||||||
placeholder="例:https://www.nicovideo.jp/watch/..."
|
placeholder="例:https://www.nicovideo.jp/watch/..."
|
||||||
value={url}
|
value={url}
|
||||||
onChange={e => setURL (e.target.value)}
|
onChange={e => setURL (e.target.value)}
|
||||||
className="w-full border p-2 rounded" />
|
className="w-full border p-2 rounded"
|
||||||
|
onBlur={handleURLBlur} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* タイトル */}
|
{/* タイトル */}
|
||||||
@@ -91,6 +148,7 @@ const PostNewPage = () => {
|
|||||||
<input type="text"
|
<input type="text"
|
||||||
className="w-full border rounded p-2"
|
className="w-full border rounded p-2"
|
||||||
value={title}
|
value={title}
|
||||||
|
placeholder={titleLoading ? 'Loading...' : ''}
|
||||||
onChange={e => setTitle (e.target.value)}
|
onChange={e => setTitle (e.target.value)}
|
||||||
disabled={titleAutoFlg} />
|
disabled={titleAutoFlg} />
|
||||||
</div>
|
</div>
|
||||||
@@ -107,27 +165,27 @@ const PostNewPage = () => {
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
{thumbnailAutoFlg
|
{thumbnailAutoFlg
|
||||||
? (
|
? (thumbnailLoading
|
||||||
<p className="text-gray-500 text-sm">
|
? <p className="text-gray-500 text-sm">Loading...</p>
|
||||||
URL から自動取得されます。
|
: !(thumbnailPreview) && (
|
||||||
</p>)
|
<p className="text-gray-500 text-sm">
|
||||||
|
URL から自動取得されます。
|
||||||
|
</p>))
|
||||||
: (
|
: (
|
||||||
<>
|
<input type="file"
|
||||||
<input type="file"
|
accept="image/*"
|
||||||
accept="image/*"
|
onChange={e => {
|
||||||
onChange={e => {
|
const file = e.target.files?.[0]
|
||||||
const file = e.target.files?.[0]
|
if (file)
|
||||||
if (file)
|
{
|
||||||
{
|
setThumbnailFile (file)
|
||||||
setThumbnailFile (file)
|
setThumbnailPreview (URL.createObjectURL (file))
|
||||||
setThumbnailPreview (URL.createObjectURL (file))
|
}
|
||||||
}
|
}} />)}
|
||||||
}} />
|
{thumbnailPreview && (
|
||||||
{thumbnailPreview && (
|
<img src={thumbnailPreview}
|
||||||
<img src={thumbnailPreview}
|
alt="preview"
|
||||||
alt="preview"
|
className="mt-2 max-h-48 rounded border" />)}
|
||||||
className="mt-2 max-h-48 rounded border" />)}
|
|
||||||
</>)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* タグ */}
|
{/* タグ */}
|
||||||
@@ -149,7 +207,8 @@ const PostNewPage = () => {
|
|||||||
|
|
||||||
{/* 送信 */}
|
{/* 送信 */}
|
||||||
<button onClick={handleSubmit}
|
<button onClick={handleSubmit}
|
||||||
className="px-4 py-2 bg-blue-600 text-white rounded">
|
className="px-4 py-2 bg-blue-600 text-white rounded disabled:bg-gray-400"
|
||||||
|
disabled={titleLoading || thumbnailLoading}>
|
||||||
追加
|
追加
|
||||||
</button>
|
</button>
|
||||||
</div>)
|
</div>)
|
||||||
|
|||||||
Reference in New Issue
Block a user