video-model.test.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. // Video Model Tests (Task 7)
  2. import { describe, it, expect, beforeEach } from 'vitest';
  3. describe('Video Model and Utility Functions', () => {
  4. let Video, URLValidator, FormatHandler;
  5. beforeEach(() => {
  6. // Define Video class for testing (matching the implementation)
  7. Video = class {
  8. constructor(url, options = {}) {
  9. this.id = this.generateId();
  10. this.url = this.validateUrl(url);
  11. this.title = options.title || 'Loading...';
  12. this.thumbnail = options.thumbnail || 'assets/icons/placeholder.svg';
  13. this.duration = options.duration || '00:00';
  14. this.quality = options.quality || '1080p';
  15. this.format = options.format || 'None';
  16. this.status = options.status || 'ready';
  17. this.progress = options.progress || 0;
  18. this.filename = options.filename || '';
  19. this.error = options.error || null;
  20. this.createdAt = new Date();
  21. this.updatedAt = new Date();
  22. }
  23. generateId() {
  24. return 'video_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  25. }
  26. validateUrl(url) {
  27. if (!url || typeof url !== 'string') {
  28. throw new Error('Invalid URL provided');
  29. }
  30. const trimmedUrl = url.trim();
  31. if (!URLValidator.isValidVideoUrl(trimmedUrl)) {
  32. throw new Error('Invalid video URL format');
  33. }
  34. return trimmedUrl;
  35. }
  36. update(properties) {
  37. const allowedProperties = [
  38. 'title', 'thumbnail', 'duration', 'quality', 'format',
  39. 'status', 'progress', 'filename', 'error'
  40. ];
  41. Object.keys(properties).forEach(key => {
  42. if (allowedProperties.includes(key)) {
  43. this[key] = properties[key];
  44. }
  45. });
  46. this.updatedAt = new Date();
  47. return this;
  48. }
  49. getDisplayName() {
  50. return this.title !== 'Loading...' ? this.title : this.url;
  51. }
  52. isDownloadable() {
  53. return this.status === 'ready' && !this.error;
  54. }
  55. isProcessing() {
  56. return ['downloading', 'converting'].includes(this.status);
  57. }
  58. getFormattedDuration() {
  59. if (!this.duration || this.duration === '00:00') {
  60. return 'Unknown';
  61. }
  62. return this.duration;
  63. }
  64. toJSON() {
  65. return {
  66. id: this.id,
  67. url: this.url,
  68. title: this.title,
  69. thumbnail: this.thumbnail,
  70. duration: this.duration,
  71. quality: this.quality,
  72. format: this.format,
  73. status: this.status,
  74. progress: this.progress,
  75. filename: this.filename,
  76. error: this.error,
  77. createdAt: this.createdAt.toISOString(),
  78. updatedAt: this.updatedAt.toISOString()
  79. };
  80. }
  81. static fromJSON(data) {
  82. const video = new Video(data.url, {
  83. title: data.title,
  84. thumbnail: data.thumbnail,
  85. duration: data.duration,
  86. quality: data.quality,
  87. format: data.format,
  88. status: data.status,
  89. progress: data.progress,
  90. filename: data.filename,
  91. error: data.error
  92. });
  93. video.id = data.id;
  94. video.createdAt = new Date(data.createdAt);
  95. video.updatedAt = new Date(data.updatedAt);
  96. return video;
  97. }
  98. };
  99. // Define URLValidator for testing
  100. URLValidator = class {
  101. static youtubeRegex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
  102. static youtubePlaylistRegex = /(?:https?:\/\/)?(?:www\.)?youtube\.com\/playlist\?list=([a-zA-Z0-9_-]+)/;
  103. static vimeoRegex = /(?:https?:\/\/)?(?:www\.)?(?:vimeo\.com\/|player\.vimeo\.com\/video\/)(\d+)/;
  104. static isValidVideoUrl(url) {
  105. if (!url || typeof url !== 'string') {
  106. return false;
  107. }
  108. const trimmedUrl = url.trim();
  109. return this.isYouTubeUrl(trimmedUrl) ||
  110. this.isVimeoUrl(trimmedUrl) ||
  111. this.isYouTubePlaylist(trimmedUrl);
  112. }
  113. static isYouTubeUrl(url) {
  114. return this.youtubeRegex.test(url);
  115. }
  116. static isYouTubePlaylist(url) {
  117. return this.youtubePlaylistRegex.test(url);
  118. }
  119. static isVimeoUrl(url) {
  120. return this.vimeoRegex.test(url);
  121. }
  122. static extractYouTubeId(url) {
  123. const match = url.match(this.youtubeRegex);
  124. return match ? match[1] : null;
  125. }
  126. static extractVimeoId(url) {
  127. const match = url.match(this.vimeoRegex);
  128. return match ? match[1] : null;
  129. }
  130. static extractPlaylistId(url) {
  131. const match = url.match(this.youtubePlaylistRegex);
  132. return match ? match[1] : null;
  133. }
  134. static getVideoPlatform(url) {
  135. if (this.isYouTubeUrl(url) || this.isYouTubePlaylist(url)) {
  136. return 'youtube';
  137. }
  138. if (this.isVimeoUrl(url)) {
  139. return 'vimeo';
  140. }
  141. return 'unknown';
  142. }
  143. static normalizeUrl(url) {
  144. if (!url) return url;
  145. const trimmedUrl = url.trim();
  146. if (!/^https?:\/\//.test(trimmedUrl)) {
  147. return 'https://' + trimmedUrl;
  148. }
  149. return trimmedUrl;
  150. }
  151. static extractUrlsFromText(text) {
  152. if (!text || typeof text !== 'string') {
  153. return [];
  154. }
  155. const urls = [];
  156. const urlRegex = /https?:\/\/[^\s]+/g;
  157. // Extract all potential URLs from the text
  158. const matches = text.match(urlRegex) || [];
  159. matches.forEach(url => {
  160. // Clean up the URL (remove trailing punctuation)
  161. const cleanUrl = url.replace(/[.,;!?]+$/, '');
  162. if (this.isValidVideoUrl(cleanUrl)) {
  163. urls.push(this.normalizeUrl(cleanUrl));
  164. }
  165. });
  166. return [...new Set(urls)];
  167. }
  168. };
  169. // Define FormatHandler for testing
  170. FormatHandler = class {
  171. static qualityOptions = [
  172. { value: '4K', label: '4K (2160p)', ytdlpFormat: 'best[height<=2160]' },
  173. { value: '1440p', label: '1440p (QHD)', ytdlpFormat: 'best[height<=1440]' },
  174. { value: '1080p', label: '1080p (Full HD)', ytdlpFormat: 'best[height<=1080]' },
  175. { value: '720p', label: '720p (HD)', ytdlpFormat: 'best[height<=720]' },
  176. { value: '480p', label: '480p (SD)', ytdlpFormat: 'best[height<=480]' },
  177. { value: 'best', label: 'Best Available', ytdlpFormat: 'best' }
  178. ];
  179. static formatOptions = [
  180. { value: 'None', label: 'No Conversion', ffmpegArgs: null },
  181. { value: 'H264', label: 'H.264 (MP4)', ffmpegArgs: ['-c:v', 'libx264', '-c:a', 'aac'] },
  182. { value: 'ProRes', label: 'Apple ProRes', ffmpegArgs: ['-c:v', 'prores', '-c:a', 'pcm_s16le'] },
  183. { value: 'DNxHR', label: 'Avid DNxHR', ffmpegArgs: ['-c:v', 'dnxhd', '-c:a', 'pcm_s16le'] },
  184. { value: 'Audio only', label: 'Audio Only (M4A)', ffmpegArgs: ['-vn', '-c:a', 'aac'] }
  185. ];
  186. static getYtdlpFormat(quality) {
  187. const option = this.qualityOptions.find(opt => opt.value === quality);
  188. return option ? option.ytdlpFormat : 'best[height<=720]';
  189. }
  190. static getFFmpegArgs(format) {
  191. const option = this.formatOptions.find(opt => opt.value === format);
  192. return option ? option.ffmpegArgs : null;
  193. }
  194. static requiresConversion(format) {
  195. return format && format !== 'None' && this.getFFmpegArgs(format) !== null;
  196. }
  197. static getFileExtension(format) {
  198. switch (format) {
  199. case 'H264':
  200. return 'mp4';
  201. case 'ProRes':
  202. return 'mov';
  203. case 'DNxHR':
  204. return 'mov';
  205. case 'Audio only':
  206. return 'm4a';
  207. default:
  208. return 'mp4';
  209. }
  210. }
  211. static isValidQuality(quality) {
  212. return this.qualityOptions.some(opt => opt.value === quality);
  213. }
  214. static isValidFormat(format) {
  215. return this.formatOptions.some(opt => opt.value === format);
  216. }
  217. };
  218. });
  219. describe('Video Model Core Functionality', () => {
  220. it('should create video with unique ID', () => {
  221. const video1 = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  222. const video2 = new Video('https://vimeo.com/123456789');
  223. expect(video1.id).not.toBe(video2.id);
  224. expect(video1.id).toMatch(/^video_\d+_[a-z0-9]+$/);
  225. expect(video2.id).toMatch(/^video_\d+_[a-z0-9]+$/);
  226. });
  227. it('should handle URL validation correctly', () => {
  228. // Valid URLs should work
  229. expect(() => new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ')).not.toThrow();
  230. expect(() => new Video('https://vimeo.com/123456789')).not.toThrow();
  231. // Invalid URLs should throw
  232. expect(() => new Video('')).toThrow('Invalid URL provided');
  233. expect(() => new Video(null)).toThrow('Invalid URL provided');
  234. expect(() => new Video('invalid-url')).toThrow('Invalid video URL format');
  235. });
  236. it('should set default values correctly', () => {
  237. const video = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  238. expect(video.title).toBe('Loading...');
  239. expect(video.thumbnail).toBe('assets/icons/placeholder.svg');
  240. expect(video.duration).toBe('00:00');
  241. expect(video.quality).toBe('1080p');
  242. expect(video.format).toBe('None');
  243. expect(video.status).toBe('ready');
  244. expect(video.progress).toBe(0);
  245. expect(video.filename).toBe('');
  246. expect(video.error).toBe(null);
  247. });
  248. it('should accept custom options', () => {
  249. const options = {
  250. title: 'Custom Title',
  251. thumbnail: 'custom-thumb.jpg',
  252. duration: '05:30',
  253. quality: '720p',
  254. format: 'H264',
  255. status: 'downloading',
  256. progress: 25,
  257. filename: 'custom-file.mp4',
  258. error: 'Test error'
  259. };
  260. const video = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ', options);
  261. expect(video.title).toBe(options.title);
  262. expect(video.thumbnail).toBe(options.thumbnail);
  263. expect(video.duration).toBe(options.duration);
  264. expect(video.quality).toBe(options.quality);
  265. expect(video.format).toBe(options.format);
  266. expect(video.status).toBe(options.status);
  267. expect(video.progress).toBe(options.progress);
  268. expect(video.filename).toBe(options.filename);
  269. expect(video.error).toBe(options.error);
  270. });
  271. it('should update properties correctly', () => {
  272. const video = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  273. const originalUpdatedAt = video.updatedAt;
  274. // Wait a bit to ensure timestamp difference
  275. setTimeout(() => {
  276. const result = video.update({
  277. title: 'New Title',
  278. status: 'downloading',
  279. progress: 50,
  280. invalidProperty: 'should be ignored'
  281. });
  282. expect(result).toBe(video); // Should return self for chaining
  283. expect(video.title).toBe('New Title');
  284. expect(video.status).toBe('downloading');
  285. expect(video.progress).toBe(50);
  286. expect(video.invalidProperty).toBeUndefined();
  287. expect(video.updatedAt).not.toBe(originalUpdatedAt);
  288. }, 10);
  289. });
  290. it('should provide correct display name', () => {
  291. const video = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  292. // Should return URL when title is default
  293. expect(video.getDisplayName()).toBe('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  294. // Should return title when set
  295. video.update({ title: 'Actual Video Title' });
  296. expect(video.getDisplayName()).toBe('Actual Video Title');
  297. });
  298. it('should check downloadable status correctly', () => {
  299. const video = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  300. // Ready status with no error should be downloadable
  301. expect(video.isDownloadable()).toBe(true);
  302. // Not ready status should not be downloadable
  303. video.update({ status: 'downloading' });
  304. expect(video.isDownloadable()).toBe(false);
  305. // Ready with error should not be downloadable
  306. video.update({ status: 'ready', error: 'Some error' });
  307. expect(video.isDownloadable()).toBe(false);
  308. });
  309. it('should check processing status correctly', () => {
  310. const video = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  311. expect(video.isProcessing()).toBe(false);
  312. video.update({ status: 'downloading' });
  313. expect(video.isProcessing()).toBe(true);
  314. video.update({ status: 'converting' });
  315. expect(video.isProcessing()).toBe(true);
  316. video.update({ status: 'completed' });
  317. expect(video.isProcessing()).toBe(false);
  318. video.update({ status: 'error' });
  319. expect(video.isProcessing()).toBe(false);
  320. });
  321. it('should format duration correctly', () => {
  322. const video = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  323. expect(video.getFormattedDuration()).toBe('Unknown');
  324. video.update({ duration: '05:30' });
  325. expect(video.getFormattedDuration()).toBe('05:30');
  326. video.update({ duration: '' });
  327. expect(video.getFormattedDuration()).toBe('Unknown');
  328. });
  329. it('should serialize to JSON correctly', () => {
  330. const video = new Video('https://www.youtube.com/watch?v=dQw4w9WgXcQ', {
  331. title: 'Test Video',
  332. quality: '720p'
  333. });
  334. const json = video.toJSON();
  335. expect(json.id).toBe(video.id);
  336. expect(json.url).toBe(video.url);
  337. expect(json.title).toBe('Test Video');
  338. expect(json.quality).toBe('720p');
  339. expect(json.createdAt).toBe(video.createdAt.toISOString());
  340. expect(json.updatedAt).toBe(video.updatedAt.toISOString());
  341. });
  342. it('should deserialize from JSON correctly', () => {
  343. const jsonData = {
  344. id: 'video_123_abc',
  345. url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
  346. title: 'Test Video',
  347. thumbnail: 'test-thumb.jpg',
  348. duration: '05:30',
  349. quality: '720p',
  350. format: 'H264',
  351. status: 'completed',
  352. progress: 100,
  353. filename: 'test.mp4',
  354. error: null,
  355. createdAt: '2024-01-01T00:00:00.000Z',
  356. updatedAt: '2024-01-01T01:00:00.000Z'
  357. };
  358. const video = Video.fromJSON(jsonData);
  359. expect(video.id).toBe(jsonData.id);
  360. expect(video.url).toBe(jsonData.url);
  361. expect(video.title).toBe(jsonData.title);
  362. expect(video.quality).toBe(jsonData.quality);
  363. expect(video.createdAt).toEqual(new Date(jsonData.createdAt));
  364. expect(video.updatedAt).toEqual(new Date(jsonData.updatedAt));
  365. });
  366. });
  367. describe('URLValidator Advanced Features', () => {
  368. it('should extract YouTube video IDs', () => {
  369. expect(URLValidator.extractYouTubeId('https://www.youtube.com/watch?v=dQw4w9WgXcQ')).toBe('dQw4w9WgXcQ');
  370. expect(URLValidator.extractYouTubeId('https://youtu.be/dQw4w9WgXcQ')).toBe('dQw4w9WgXcQ');
  371. expect(URLValidator.extractYouTubeId('invalid-url')).toBe(null);
  372. });
  373. it('should extract Vimeo video IDs', () => {
  374. expect(URLValidator.extractVimeoId('https://vimeo.com/123456789')).toBe('123456789');
  375. expect(URLValidator.extractVimeoId('https://player.vimeo.com/video/123456789')).toBe('123456789');
  376. expect(URLValidator.extractVimeoId('invalid-url')).toBe(null);
  377. });
  378. it('should extract YouTube playlist IDs', () => {
  379. expect(URLValidator.extractPlaylistId('https://www.youtube.com/playlist?list=PLrAXtmRdnEQy6nuLMHjMZOz59Oq8HmPME')).toBe('PLrAXtmRdnEQy6nuLMHjMZOz59Oq8HmPME');
  380. expect(URLValidator.extractPlaylistId('invalid-url')).toBe(null);
  381. });
  382. it('should identify video platforms', () => {
  383. expect(URLValidator.getVideoPlatform('https://www.youtube.com/watch?v=dQw4w9WgXcQ')).toBe('youtube');
  384. expect(URLValidator.getVideoPlatform('https://youtu.be/dQw4w9WgXcQ')).toBe('youtube');
  385. expect(URLValidator.getVideoPlatform('https://www.youtube.com/playlist?list=PLrAXtmRdnEQy6nuLMHjMZOz59Oq8HmPME')).toBe('youtube');
  386. expect(URLValidator.getVideoPlatform('https://vimeo.com/123456789')).toBe('vimeo');
  387. expect(URLValidator.getVideoPlatform('https://example.com')).toBe('unknown');
  388. });
  389. it('should normalize URLs', () => {
  390. expect(URLValidator.normalizeUrl('www.youtube.com/watch?v=dQw4w9WgXcQ')).toBe('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  391. expect(URLValidator.normalizeUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ')).toBe('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  392. expect(URLValidator.normalizeUrl('')).toBe('');
  393. expect(URLValidator.normalizeUrl(null)).toBe(null);
  394. });
  395. it('should handle complex text extraction', () => {
  396. const complexText = `
  397. Check out these videos:
  398. 1. https://www.youtube.com/watch?v=dQw4w9WgXcQ - Rick Roll
  399. 2. Some random text here
  400. 3. https://vimeo.com/123456789
  401. Also this one: https://youtu.be/abcdefghijk
  402. And this playlist: https://www.youtube.com/playlist?list=PLrAXtmRdnEQy6nuLMHjMZOz59Oq8HmPME
  403. Invalid: https://example.com/not-a-video
  404. `;
  405. const urls = URLValidator.extractUrlsFromText(complexText);
  406. expect(urls).toHaveLength(4);
  407. expect(urls).toContain('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
  408. expect(urls).toContain('https://vimeo.com/123456789');
  409. expect(urls).toContain('https://youtu.be/abcdefghijk');
  410. expect(urls).toContain('https://www.youtube.com/playlist?list=PLrAXtmRdnEQy6nuLMHjMZOz59Oq8HmPME');
  411. });
  412. });
  413. describe('FormatHandler Functionality', () => {
  414. it('should provide correct yt-dlp format strings', () => {
  415. expect(FormatHandler.getYtdlpFormat('720p')).toBe('best[height<=720]');
  416. expect(FormatHandler.getYtdlpFormat('1080p')).toBe('best[height<=1080]');
  417. expect(FormatHandler.getYtdlpFormat('4K')).toBe('best[height<=2160]');
  418. expect(FormatHandler.getYtdlpFormat('best')).toBe('best');
  419. expect(FormatHandler.getYtdlpFormat('invalid')).toBe('best[height<=720]'); // fallback
  420. });
  421. it('should provide correct FFmpeg arguments', () => {
  422. expect(FormatHandler.getFFmpegArgs('None')).toBe(null);
  423. expect(FormatHandler.getFFmpegArgs('H264')).toEqual(['-c:v', 'libx264', '-c:a', 'aac']);
  424. expect(FormatHandler.getFFmpegArgs('ProRes')).toEqual(['-c:v', 'prores', '-c:a', 'pcm_s16le']);
  425. expect(FormatHandler.getFFmpegArgs('Audio only')).toEqual(['-vn', '-c:a', 'aac']);
  426. });
  427. it('should check if conversion is required', () => {
  428. expect(FormatHandler.requiresConversion('None')).toBe(false);
  429. expect(FormatHandler.requiresConversion('H264')).toBe(true);
  430. expect(FormatHandler.requiresConversion('ProRes')).toBe(true);
  431. expect(FormatHandler.requiresConversion('Audio only')).toBe(true);
  432. });
  433. it('should provide correct file extensions', () => {
  434. expect(FormatHandler.getFileExtension('None')).toBe('mp4');
  435. expect(FormatHandler.getFileExtension('H264')).toBe('mp4');
  436. expect(FormatHandler.getFileExtension('ProRes')).toBe('mov');
  437. expect(FormatHandler.getFileExtension('DNxHR')).toBe('mov');
  438. expect(FormatHandler.getFileExtension('Audio only')).toBe('m4a');
  439. });
  440. it('should validate quality and format options', () => {
  441. expect(FormatHandler.isValidQuality('720p')).toBe(true);
  442. expect(FormatHandler.isValidQuality('1080p')).toBe(true);
  443. expect(FormatHandler.isValidQuality('invalid')).toBe(false);
  444. expect(FormatHandler.isValidFormat('None')).toBe(true);
  445. expect(FormatHandler.isValidFormat('H264')).toBe(true);
  446. expect(FormatHandler.isValidFormat('invalid')).toBe(false);
  447. });
  448. });
  449. });