summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/video_link_filter.rb
blob: 4dfbff8ec864639c2967807ae816f8fccea9fd62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module Banzai
  module Filter

    # HTML Filter that handles video uploads.

    class VideoLinkFilter < HTML::Pipeline::Filter
      include ActionView::Helpers::TagHelper
      include ActionView::Context

      def call
        doc.xpath(query).each do |el|
          el.replace(video_node(doc, el))
        end

        doc
      end

      private

      def query
        @query ||= begin
          src_query = UploaderHelper::VIDEO_EXT.map do |ext|
            "'.#{ext}' = substring(@src, string-length(@src) - #{ext.size})"
          end

          "descendant-or-self::img[not(ancestor::a) and (#{src_query.join(' or ')})]"
        end
      end

      # Return a video tag Nokogiri node
      #
      def video_node(doc, element)
        container = doc.document.create_element(
          'div',
          class: 'video-container'
        )

        video = doc.document.create_element(
          'video',
          src: element['src'],
          class: 'video-js vjs-sublime-skin',
          controls: true,
          "data-setup": '{}')

        link = doc.document.create_element(
          'a',
          element['title'] || element['alt'],
          href: element['src'],
          target: '_blank',
          title: "Downlad '#{element['title'] || element['alt']}'")
        download_paragraph = doc.document.create_element('p')
        download_paragraph.children = link

        container.add_child(video)
        container.add_child(download_paragraph)

        container
      end
    end

  end
end