video-factory.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /**
  2. * @fileoverview Video factory with validation and creation patterns
  3. * @author GrabZilla Development Team
  4. * @version 2.1.0
  5. * @since 2024-01-01
  6. */
  7. import { URLValidator } from '../utils/url-validator.js';
  8. import { APP_CONFIG, VIDEO_STATUS, ERROR_TYPES } from '../constants/config.js';
  9. /**
  10. * Video Model - Core data structure for video management
  11. *
  12. * Represents a single video in the download queue with all metadata
  13. * and state information required for processing
  14. */
  15. export class Video {
  16. /**
  17. * Creates new Video instance (use VideoFactory.create instead)
  18. * @param {string} id - Unique video identifier
  19. * @param {string} url - Validated video URL
  20. * @param {Object} properties - Video properties
  21. * @private
  22. */
  23. constructor(id, url, properties = {}) {
  24. this.id = id;
  25. this.url = url;
  26. this.title = properties.title || 'Loading...';
  27. this.thumbnail = properties.thumbnail || 'assets/icons/placeholder.svg';
  28. this.duration = properties.duration || '00:00';
  29. this.quality = properties.quality || APP_CONFIG.DEFAULT_QUALITY;
  30. this.format = properties.format || APP_CONFIG.DEFAULT_FORMAT;
  31. this.status = properties.status || VIDEO_STATUS.READY;
  32. this.progress = properties.progress || 0;
  33. this.filename = properties.filename || '';
  34. this.error = properties.error || null;
  35. this.createdAt = properties.createdAt || new Date();
  36. this.updatedAt = properties.updatedAt || new Date();
  37. }
  38. /**
  39. * Update video properties with validation
  40. * @param {Object} properties - Properties to update
  41. * @returns {Video} This video instance for chaining
  42. */
  43. update(properties) {
  44. const allowedProperties = [
  45. 'title', 'thumbnail', 'duration', 'quality', 'format',
  46. 'status', 'progress', 'filename', 'error'
  47. ];
  48. Object.keys(properties).forEach(key => {
  49. if (allowedProperties.includes(key)) {
  50. this[key] = properties[key];
  51. }
  52. });
  53. this.updatedAt = new Date();
  54. return this;
  55. }
  56. /**
  57. * Get video display name
  58. * @returns {string} Display-friendly video name
  59. */
  60. getDisplayName() {
  61. return this.title !== 'Loading...' ? this.title : this.url;
  62. }
  63. /**
  64. * Check if video is downloadable
  65. * @returns {boolean} True if video can be downloaded
  66. */
  67. isDownloadable() {
  68. return this.status === VIDEO_STATUS.READY && !this.error;
  69. }
  70. /**
  71. * Check if video is currently processing
  72. * @returns {boolean} True if video is being processed
  73. */
  74. isProcessing() {
  75. return [VIDEO_STATUS.DOWNLOADING, VIDEO_STATUS.CONVERTING].includes(this.status);
  76. }
  77. /**
  78. * Get formatted duration for display
  79. * @returns {string} Formatted duration or 'Unknown'
  80. */
  81. getFormattedDuration() {
  82. if (!this.duration || this.duration === '00:00') {
  83. return 'Unknown';
  84. }
  85. return this.duration;
  86. }
  87. /**
  88. * Convert to JSON for storage/transmission
  89. * @returns {Object} Serializable video object
  90. */
  91. toJSON() {
  92. return {
  93. id: this.id,
  94. url: this.url,
  95. title: this.title,
  96. thumbnail: this.thumbnail,
  97. duration: this.duration,
  98. quality: this.quality,
  99. format: this.format,
  100. status: this.status,
  101. progress: this.progress,
  102. filename: this.filename,
  103. error: this.error,
  104. createdAt: this.createdAt.toISOString(),
  105. updatedAt: this.updatedAt.toISOString()
  106. };
  107. }
  108. }
  109. /**
  110. * Video Factory - Creates and validates Video instances
  111. *
  112. * Handles video creation with proper validation, error handling,
  113. * and metadata extraction using the Factory pattern
  114. */
  115. export class VideoFactory {
  116. /**
  117. * Create new Video instance with validation
  118. * @param {string} url - Video URL to create from
  119. * @param {Object} options - Optional video properties
  120. * @returns {Video} New video instance
  121. * @throws {Error} When URL is invalid or creation fails
  122. */
  123. static create(url, options = {}) {
  124. // Validate URL
  125. const validation = URLValidator.validateUrlWithDetails(url);
  126. if (!validation.valid) {
  127. throw new Error(`Invalid video URL: ${validation.error}`);
  128. }
  129. // Normalize URL
  130. const normalizedUrl = URLValidator.normalizeUrl(url);
  131. // Generate unique ID
  132. const id = this.generateId();
  133. // Extract basic info from URL
  134. const basicInfo = this.extractBasicInfo(normalizedUrl);
  135. // Merge options with basic info
  136. const properties = {
  137. ...basicInfo,
  138. ...options,
  139. status: options.status || VIDEO_STATUS.READY
  140. };
  141. return new Video(id, normalizedUrl, properties);
  142. }
  143. /**
  144. * Create Video from JSON data
  145. * @param {Object} data - JSON data from toJSON()
  146. * @returns {Video} Restored video instance
  147. * @throws {Error} When data is invalid
  148. */
  149. static fromJSON(data) {
  150. if (!data || typeof data !== 'object') {
  151. throw new Error('Invalid JSON data for video creation');
  152. }
  153. // Validate required fields
  154. const requiredFields = ['id', 'url'];
  155. for (const field of requiredFields) {
  156. if (!data[field]) {
  157. throw new Error(`Missing required field: ${field}`);
  158. }
  159. }
  160. // Create video with restored properties
  161. const properties = {
  162. title: data.title,
  163. thumbnail: data.thumbnail,
  164. duration: data.duration,
  165. quality: data.quality,
  166. format: data.format,
  167. status: data.status,
  168. progress: data.progress,
  169. filename: data.filename,
  170. error: data.error,
  171. createdAt: data.createdAt ? new Date(data.createdAt) : new Date(),
  172. updatedAt: data.updatedAt ? new Date(data.updatedAt) : new Date()
  173. };
  174. return new Video(data.id, data.url, properties);
  175. }
  176. /**
  177. * Create multiple videos from text input
  178. * @param {string} text - Text containing video URLs
  179. * @param {Object} defaultOptions - Default options for all videos
  180. * @returns {Object} Creation results with success/error arrays
  181. */
  182. static createFromText(text, defaultOptions = {}) {
  183. const result = {
  184. videos: [],
  185. errors: [],
  186. duplicateUrls: []
  187. };
  188. if (!text || typeof text !== 'string') {
  189. result.errors.push({
  190. url: '',
  191. error: 'No input text provided',
  192. type: ERROR_TYPES.INVALID_URL
  193. });
  194. return result;
  195. }
  196. // Extract URLs from text
  197. const urls = URLValidator.extractUrlsFromText(text);
  198. if (urls.length === 0) {
  199. result.errors.push({
  200. url: text.trim(),
  201. error: 'No valid video URLs found in text',
  202. type: ERROR_TYPES.INVALID_URL
  203. });
  204. return result;
  205. }
  206. // Track URLs to prevent duplicates within this batch
  207. const seenUrls = new Set();
  208. // Create videos from extracted URLs
  209. urls.forEach(url => {
  210. try {
  211. // Check for duplicates within this batch
  212. if (seenUrls.has(url)) {
  213. result.duplicateUrls.push(url);
  214. return;
  215. }
  216. seenUrls.add(url);
  217. // Create video
  218. const video = this.create(url, defaultOptions);
  219. result.videos.push(video);
  220. } catch (error) {
  221. result.errors.push({
  222. url,
  223. error: error.message,
  224. type: ERROR_TYPES.INVALID_URL
  225. });
  226. }
  227. });
  228. return result;
  229. }
  230. /**
  231. * Generate unique video ID
  232. * @returns {string} Unique identifier
  233. * @private
  234. */
  235. static generateId() {
  236. return `video_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  237. }
  238. /**
  239. * Extract basic video information from URL
  240. * @param {string} url - Normalized video URL
  241. * @returns {Object} Basic video information
  242. * @private
  243. */
  244. static extractBasicInfo(url) {
  245. const platform = URLValidator.getVideoPlatform(url);
  246. const info = {
  247. title: 'Loading...',
  248. thumbnail: 'assets/icons/placeholder.svg'
  249. };
  250. switch (platform) {
  251. case 'youtube': {
  252. const videoId = URLValidator.extractYouTubeId(url);
  253. if (videoId) {
  254. info.title = `YouTube Video (${videoId})`;
  255. info.thumbnail = URLValidator.getYouTubeThumbnail(videoId);
  256. }
  257. break;
  258. }
  259. case 'vimeo': {
  260. const videoId = URLValidator.extractVimeoId(url);
  261. if (videoId) {
  262. info.title = `Vimeo Video (${videoId})`;
  263. // Vimeo thumbnails require async API call
  264. }
  265. break;
  266. }
  267. }
  268. return info;
  269. }
  270. /**
  271. * Validate video object structure
  272. * @param {Object} video - Video object to validate
  273. * @returns {boolean} True if valid video object
  274. */
  275. static isValidVideo(video) {
  276. return video instanceof Video &&
  277. typeof video.id === 'string' &&
  278. typeof video.url === 'string' &&
  279. URLValidator.isValidVideoUrl(video.url);
  280. }
  281. }