View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html;
16  
17  import java.net.MalformedURLException;
18  import java.util.Map;
19  
20  import org.htmlunit.SgmlPage;
21  import org.htmlunit.html.csp.ContentSecurityPolicy;
22  import org.htmlunit.javascript.PostponedAction;
23  import org.htmlunit.javascript.host.event.Event;
24  import org.htmlunit.util.StringUtils;
25  
26  /**
27   * HTML Media element, e.g. {@link HtmlAudio} or {@link HtmlVideo}.
28   *
29   * @author Ahmed Ashour
30   * @author Frank Danek
31   * @author Ronald Brill
32   */
33  public abstract class HtmlMedia extends HtmlElement {
34  
35      private boolean childrenChecked_;
36      private String checkedSrc_;
37  
38      /**
39       * Creates an instance.
40       *
41       * @param qualifiedName the qualified name of the element type to instantiate
42       * @param page the HtmlPage that contains this element
43       * @param attributes the initial attributes
44       */
45      HtmlMedia(final String qualifiedName, final SgmlPage page,
46              final Map<String, DomAttr> attributes) {
47          super(qualifiedName, page, attributes);
48      }
49  
50      /**
51       * {@inheritDoc}
52       * Checks the url against the Content-Security-Policy (media-src); the source and track
53       * children are checked after they are added.
54       */
55      @Override
56      protected void onAddedToPage() {
57          super.onAddedToPage();
58          childrenChecked_ = false;
59          final String src = getAttributeDirect(SRC_ATTRIBUTE);
60          // the src may be checked already (set by script before the element was added)
61          if (ATTRIBUTE_NOT_DEFINED != src && !src.equals(checkedSrc_)) {
62              checkSrc(src);
63          }
64          if (getFirstElementChild() != null) {
65              checkChildrenContentSecurityPolicy();
66          }
67      }
68  
69      /**
70       * {@inheritDoc}
71       */
72      @Override
73      public void onAllChildrenAddedToPage(final boolean postponed) {
74          super.onAllChildrenAddedToPage(postponed);
75          if (!childrenChecked_) {
76              checkChildrenContentSecurityPolicy();
77          }
78      }
79  
80      /**
81       * {@inheritDoc}
82       * Checks the new src url against the Content-Security-Policy (media-src); like the browsers,
83       * also if the element is not attached to the page.
84       */
85      @Override
86      protected void setAttributeNS(final String namespaceURI, final String qualifiedName, final String value,
87              final boolean notifyAttributeChangeListeners, final boolean notifyMutationObservers) {
88          final String qualifiedNameLC = StringUtils.toRootLowerCase(qualifiedName);
89          final boolean changed = SRC_ATTRIBUTE.equals(qualifiedNameLC)
90                  && !getAttributeNS(namespaceURI, qualifiedNameLC).equals(value);
91  
92          super.setAttributeNS(namespaceURI, qualifiedName, value,
93                  notifyAttributeChangeListeners, notifyMutationObservers);
94  
95          if (changed) {
96              checkSrc(value);
97          }
98      }
99  
100     private void checkSrc(final String src) {
101         checkedSrc_ = src;
102         if (!ContentSecurityPolicy.allowsMedia(this, src)) {
103             fireErrorEvent(this);
104         }
105     }
106 
107     /**
108      * Fires the error event (async) at the element blocked by the Content-Security-Policy.
109      */
110     private static void fireErrorEvent(final HtmlElement element) {
111         final HtmlPage page = element.getHtmlPageOrNull();
112         if (page == null || !page.getWebClient().isJavaScriptEngineEnabled()) {
113             return;
114         }
115 
116         final PostponedAction action = new PostponedAction(page, "HtmlMedia.blocked") {
117             @Override
118             public void execute() {
119                 element.fireEvent(Event.TYPE_ERROR);
120             }
121         };
122         if (READY_STATE_LOADING.equals(page.getReadyState())) {
123             page.addAfterLoadAction(action);
124         }
125         else {
126             page.getWebClient().getJavaScriptEngine().addPostponedAction(action);
127         }
128     }
129 
130     /**
131      * Checks the urls of the children against the Content-Security-Policy (media-src): without
132      * a src attribute the source children (in order, until the first allowed one) and the default track.
133      */
134     private void checkChildrenContentSecurityPolicy() {
135         childrenChecked_ = true;
136         final HtmlPage page = getHtmlPageOrNull();
137         if (page == null || page.getContentSecurityPolicy() == null) {
138             return;
139         }
140 
141         if (!hasAttribute(SRC_ATTRIBUTE)) {
142             for (final DomNode child : getChildren()) {
143                 if (child instanceof HtmlSource source) {
144                     final String sourceSrc = source.getAttributeDirect(SRC_ATTRIBUTE);
145                     if (!StringUtils.isBlank(sourceSrc)) {
146                         if (ContentSecurityPolicy.allowsMedia(source, sourceSrc)) {
147                             break;
148                         }
149                         fireErrorEvent(source);
150                     }
151                 }
152             }
153         }
154 
155         for (final DomNode child : getChildren()) {
156             if (child instanceof HtmlTrack track && track.hasAttribute("default")) {
157                 if (!ContentSecurityPolicy.allowsMedia(track, track.getAttributeDirect(SRC_ATTRIBUTE))) {
158                     fireErrorEvent(track);
159                 }
160                 break;
161             }
162         }
163     }
164 
165     /**
166      * Returns the value of the attribute {@code src}. Refer to the
167      * <a href="http://www.w3.org/TR/html401/">HTML 4.01</a>
168      * documentation for details on the use of this attribute.
169      *
170      * @return the value of the attribute {@code src} or an empty string if that attribute isn't defined
171      */
172     public final String getSrcAttribute() {
173         return getSrcAttributeNormalized();
174     }
175 
176     /**
177      * Returns the fully qualified source URL.
178      *
179      * @return the fully qualified value of the {@code src} attribute
180      */
181     public String getSrc() {
182         final String src = getSrcAttribute();
183         if (StringUtils.isEmptyString(src)) {
184             return src;
185         }
186         try {
187             final HtmlPage page = (HtmlPage) getPage();
188             return page.getFullyQualifiedUrl(src).toExternalForm();
189         }
190         catch (final MalformedURLException e) {
191             final String msg = "Unable to create fully qualified URL for src attribute of media " + e.getMessage();
192             throw new RuntimeException(msg, e);
193         }
194     }
195 
196     /**
197      * Sets the value of the {@code src} attribute.
198      * @param src the value of the {@code src} attribute
199      */
200     public void setSrc(final String src) {
201         setAttribute(SRC_ATTRIBUTE, src);
202     }
203 
204     /**
205      * Returns the absolute URL of the chosen media resource.
206      * This could happen, for example, if the web server selects a
207      * media file based on the resolution of the user's display.
208      * The value is an empty string if the networkState property is EMPTY.
209      * @return the absolute URL of the chosen media resource
210      */
211     public String getCurrentSrc() {
212         return "";
213     }
214 }