Skip to content

Commit

Permalink
port tootsuite#11123 to monsterfork: Add audio uploads
Browse files Browse the repository at this point in the history
* Add audio uploads

Fix mastodon#4827

Accept uploads of OGG, WAV, FLAC, OPUS and MP3 files, and converts
them to OGG. Media attachments get a new `audio` type. In the UI,
audio uploads are displayed identically to video uploads.

* Improve code style
  • Loading branch information
Gargron authored and multiple creatures committed Feb 21, 2020
1 parent b956d46 commit 480a83e
Show file tree
Hide file tree
Showing 11 changed files with 80 additions and 56 deletions.
12 changes: 10 additions & 2 deletions app/controllers/media_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ class MediaController < ApplicationController
before_action :authenticate_user!, if: :whitelist_mode?
before_action :set_media_attachment
before_action :verify_permitted_status!
before_action :check_playable, only: :player
before_action :allow_iframing, only: :player

content_security_policy only: :player do |p|
p.frame_ancestors(false)
Expand All @@ -20,8 +22,6 @@ def show

def player
@body_classes = 'player'
response.headers['X-Frame-Options'] = 'ALLOWALL'
raise ActiveRecord::RecordNotFound unless @media_attachment.video? || @media_attachment.gifv?
end

private
Expand All @@ -35,4 +35,12 @@ def verify_permitted_status!
rescue Mastodon::NotPermittedError
raise ActiveRecord::RecordNotFound
end

def check_playable
not_found unless @media_attachment.larger_media_format?
end

def allow_iframing
response.headers['X-Frame-Options'] = 'ALLOWALL'
end
end
12 changes: 6 additions & 6 deletions app/javascript/mastodon/components/status.js
Original file line number Diff line number Diff line change
Expand Up @@ -327,17 +327,17 @@ class Status extends ImmutablePureComponent {
media={status.get('media_attachments')}
/>
);
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
const video = status.getIn(['media_attachments', 0]);
} else if (['video', 'audio'].includes(status.getIn(['media_attachments', 0, 'type']))) {
const attachment = status.getIn(['media_attachments', 0]);

media = (
<Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
{Component => (
<Component
preview={video.get('preview_url')}
blurhash={video.get('blurhash')}
src={video.get('url')}
alt={video.get('description')}
preview={attachment.get('preview_url')}
blurhash={attachment.get('blurhash')}
src={attachment.get('url')}
alt={attachment.get('description')}
width={this.props.cachedMediaWidth}
height={110}
inline
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';

const messages = defineMessages({
upload: { id: 'upload_button.label', defaultMessage: 'Add media (JPEG, PNG, GIF, WebM, MP4, MOV)' },
upload: { id: 'upload_button.label', defaultMessage: 'Add media ({formats})' },
});

const SUPPORTED_FORMATS = 'JPEG, PNG, GIF, WebM, MP4, MOV, OGG, WAV, MP3, FLAC';

const makeMapStateToProps = () => {
const mapStateToProps = state => ({
acceptContentTypes: state.getIn(['media_attachments', 'accept_content_types']),
Expand Down Expand Up @@ -60,9 +62,9 @@ class UploadButton extends ImmutablePureComponent {

return (
<div className='compose-form__upload-button'>
<IconButton icon='camera' title={intl.formatMessage(messages.upload)} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} />
<IconButton icon='camera' title={intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} />
<label>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.upload)}</span>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.upload, { formats: SUPPORTED_FORMATS })}</span>
<input
key={resetFileKey}
ref={this.setRef}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import UploadButton from '../components/upload_button';
import { uploadCompose } from '../../../actions/compose';

const mapStateToProps = state => ({
disabled: state.getIn(['compose', 'is_uploading']) || (state.getIn(['compose', 'media_attachments']).size > 3 || state.getIn(['compose', 'media_attachments']).some(m => m.get('type') === 'video')),
disabled: state.getIn(['compose', 'is_uploading']) || (state.getIn(['compose', 'media_attachments']).size > 3 || state.getIn(['compose', 'media_attachments']).some(m => ['video', 'audio'].includes(m.get('type')))),
unavailable: state.getIn(['compose', 'poll']) !== null,
resetFileKey: state.getIn(['compose', 'resetFileKey']),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,15 +107,15 @@ export default class DetailedStatus extends ImmutablePureComponent {
}

if (status.get('media_attachments').size > 0) {
if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
const video = status.getIn(['media_attachments', 0]);
if (['video', 'audio'].includes(status.getIn(['media_attachments', 0, 'type']))) {
const attachment = status.getIn(['media_attachments', 0]);

media = (
<Video
preview={video.get('preview_url')}
blurhash={video.get('blurhash')}
src={video.get('url')}
alt={video.get('description')}
preview={attachment.get('preview_url')}
blurhash={attachment.get('blurhash')}
src={attachment.get('url')}
alt={attachment.get('description')}
width={300}
height={150}
inline
Expand Down
2 changes: 1 addition & 1 deletion app/javascript/mastodon/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@
"trends.count_by_accounts": "{count} {rawCount, plural, one {person} other {people}} talking",
"ui.beforeunload": "Your draft will be lost if you leave Monsterpit.",
"upload_area.title": "Drag & drop to upload",
"upload_button.label": "Add media (JPEG, PNG, GIF, WebM, MP4, MOV)",
"upload_button.label": "Add media ({formats})",
"upload_error.limit": "File upload limit exceeded.",
"upload_error.poll": "File upload not allowed with polls.",
"upload_form.description": "Describe for the visually impaired",
Expand Down
80 changes: 47 additions & 33 deletions app/models/media_attachment.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,16 @@
class MediaAttachment < ApplicationRecord
self.inheritance_column = nil

enum type: [:image, :gifv, :video, :audio, :unknown]
enum type: [:image, :gifv, :video, :unknown, :audio]

MAX_DESCRIPTION_LENGTH = 6666
IMAGE_FILE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif'].freeze
VIDEO_FILE_EXTENSIONS = ['.webm', '.mp4', '.m4v', '.mov'].freeze
AUDIO_FILE_EXTENSIONS = ['.ogg', '.oga', '.mp3', '.wav', '.flac', '.opus'].freeze

IMAGE_FILE_EXTENSIONS = %w(.jpg .jpeg .png .gif).freeze
VIDEO_FILE_EXTENSIONS = %w(.webm .mp4 .m4v .mov).freeze
AUDIO_FILE_EXTENSIONS = %w(.ogg .oga .mp3 .wav .flac .opus .aac .m4a .3gp).freeze

IMAGE_MIME_TYPES = %w(image/jpeg image/png image/gif).freeze
VIDEO_MIME_TYPES = %w(video/webm video/mp4 video/quicktime video/ogg).freeze
VIDEO_CONVERTIBLE_MIME_TYPES = %w(video/webm video/quicktime).freeze
AUDIO_MIME_TYPES = %w(audio/wave audio/wav audio/x-wav audio/x-pn-wave audio/ogg audio/mpeg audio/mp3 audio/webm audio/flac audio/aac audio/m4a audio/3gpp).freeze
IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
VIDEO_MIME_TYPES = ['video/webm', 'video/mp4', 'video/quicktime'].freeze
VIDEO_CONVERTIBLE_MIME_TYPES = ['video/webm', 'video/quicktime'].freeze
AUDIO_MIME_TYPES = ['audio/wave', 'audio/wav', 'audio/x-wav', 'audio/x-pn-wave', 'audio/ogg', 'audio/mpeg', 'audio/webm', 'audio/flac'].freeze

BLURHASH_OPTIONS = {
x_comp: 4,
Expand Down Expand Up @@ -86,6 +84,13 @@ class MediaAttachment < ApplicationRecord
},
}.freeze

AUDIO_STYLES = {
original: {
format: 'ogg',
convert_options: {},
},
}.freeze

VIDEO_FORMAT = {
format: 'mp4',
convert_options: {
Expand All @@ -103,6 +108,11 @@ class MediaAttachment < ApplicationRecord
},
}.freeze

VIDEO_CONVERTED_STYLES = {
small: VIDEO_STYLES[:small],
original: VIDEO_FORMAT,
}.freeze

IMAGE_LIMIT = (ENV['MAX_IMAGE_SIZE'] || 8.megabytes).to_i
VIDEO_LIMIT = (ENV['MAX_VIDEO_SIZE'] || 40.megabytes).to_i

Expand All @@ -116,8 +126,8 @@ class MediaAttachment < ApplicationRecord
convert_options: { all: '-quality 90 -strip' }

validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES + AUDIO_MIME_TYPES
validates_attachment_size :file, less_than: IMAGE_LIMIT, unless: :video_or_gifv?
validates_attachment_size :file, less_than: VIDEO_LIMIT, if: :video_or_gifv?
validates_attachment_size :file, less_than: IMAGE_LIMIT, unless: :larger_media_format?
validates_attachment_size :file, less_than: VIDEO_LIMIT, if: :larger_media_format?
remotable_attachment :file, VIDEO_LIMIT

include Attachmentable
Expand All @@ -141,8 +151,12 @@ def needs_redownload?
(file.blank? || (Paperclip::Attachment.default_options[:storage] == :filesystem && !File.exist?(file.path))) && remote_url.present?
end

def video_or_gifv?
video? || gifv?
def larger_media_format?
video? || gifv? || audio?
end

def audio_or_video?
audio? || video?
end

def blocked?
Expand Down Expand Up @@ -199,32 +213,24 @@ class << self
private

def file_styles(f)
if f.instance.file_content_type == 'image/gif'
{
small: IMAGE_STYLES[:small],
original: VIDEO_FORMAT,
}
elsif IMAGE_MIME_TYPES.include? f.instance.file_content_type
if f.instance.file_content_type == 'image/gif' || VIDEO_CONVERTIBLE_MIME_TYPES.include?(f.instance.file_content_type)
VIDEO_CONVERTED_STYLES
elsif IMAGE_MIME_TYPES.include?(f.instance.file_content_type)
IMAGE_STYLES
elsif AUDIO_MIME_TYPES.include? f.instance.file_content_type
AUDIO_STYLES
elsif VIDEO_CONVERTIBLE_MIME_TYPES.include?(f.instance.file_content_type)
{
small: VIDEO_STYLES[:small],
original: VIDEO_FORMAT,
}
else
elsif VIDEO_MIME_TYPES.include?(f.instance.file_content_type)
VIDEO_STYLES
else
AUDIO_STYLES
end
end

def file_processors(f)
if f.file_content_type == 'image/gif'
[:gif_transcoder, :blurhash_transcoder]
elsif VIDEO_MIME_TYPES.include? f.file_content_type
elsif VIDEO_MIME_TYPES.include?(f.file_content_type)
[:video_transcoder, :blurhash_transcoder]
elsif AUDIO_MIME_TYPES.include? f.file_content_type
[:audio_transcoder]
elsif AUDIO_MIME_TYPES.include?(f.file_content_type)
[:transcoder]
else
[:lazy_thumbnail, :blurhash_transcoder]
end
Expand All @@ -249,7 +255,15 @@ def prepare_description
end

def set_type_and_extension
self.type = VIDEO_MIME_TYPES.include?(file_content_type) ? :video : AUDIO_MIME_TYPES.include?(file_content_type) ? :audio : :image
self.type = begin
if VIDEO_MIME_TYPES.include?(file_content_type)
:video
elsif AUDIO_MIME_TYPES.include?(file_content_type)
:audio
else
:image
end
end
end

def set_meta
Expand Down Expand Up @@ -292,7 +306,7 @@ def video_metadata(file)
frame_rate: movie.frame_rate,
duration: movie.duration,
bitrate: movie.bitrate,
}
}.compact
end

def reset_parent_cache
Expand Down
2 changes: 1 addition & 1 deletion app/serializers/initial_state_serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def accounts
end

def media_attachments
{ accept_content_types: [] }
{ accept_content_types: MediaAttachment::IMAGE_FILE_EXTENSIONS + MediaAttachment::VIDEO_FILE_EXTENSIONS + MediaAttachment::AUDIO_FILE_EXTENSIONS + MediaAttachment::IMAGE_MIME_TYPES + MediaAttachment::VIDEO_MIME_TYPES + MediaAttachment::AUDIO_MIME_TYPES }
end

private
Expand Down
2 changes: 1 addition & 1 deletion app/services/post_status_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ def validate_media!

@media = @account.media_attachments.where(status_id: nil).where(id: @options[:media_ids].take(6).map(&:to_i))

raise Mastodon::ValidationError, I18n.t('media_attachments.validations.images_and_video') if @media.size > 1 && @media.find(&:video?)
raise Mastodon::ValidationError, I18n.t('media_attachments.validations.images_and_video') if @media.size > 1 && @media.find(&:audio_or_video?)
end

def process_bangtags
Expand Down
2 changes: 1 addition & 1 deletion app/views/statuses/_detailed_status.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
= render partial: 'statuses/poll', locals: { status: status, poll: status.preloadable_poll, autoplay: autoplay }

- if !status.media_attachments.empty?
- if status.media_attachments.first.video?
- if status.media_attachments.first.audio_or_video?
- video = status.media_attachments.first
= react_component :video, src: video.file.url(:original), preview: video.file.url(:small), blurhash: video.blurhash, sensitive: !current_account&.user&.show_all_media? && status.sensitive? || current_account&.user&.hide_all_media?, width: 670, height: 380, detailed: true, inline: true, alt: video.description do
= render partial: 'statuses/attachment_list', locals: { attachments: status.media_attachments }
Expand Down
2 changes: 1 addition & 1 deletion app/views/statuses/_simple_status.html.haml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
= render partial: 'statuses/poll', locals: { status: status, poll: status.preloadable_poll, autoplay: autoplay }

- if !status.media_attachments.empty?
- if status.media_attachments.first.video?
- if status.media_attachments.first.audio_or_video?
- video = status.media_attachments.first
= react_component :video, src: video.file.url(:original), preview: video.file.url(:small), blurhash: video.blurhash, sensitive: !current_account&.user&.show_all_media? && status.sensitive? || current_account&.user&.hide_all_media?, width: 610, height: 343, inline: true, alt: video.description do
= render partial: 'statuses/attachment_list', locals: { attachments: status.media_attachments }
Expand Down

0 comments on commit 480a83e

Please sign in to comment.