summaryrefslogtreecommitdiff
blob: 5daac4f436b0555d7ee710e138b968382ddd14c2 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/* jshint onevar: false, smarttabs: true, devel: true */
/* global VideoPressAdminSettings, setUserSetting, JSON */

/**
 * VideoPress Admin
 *
 * @todo i18n
 */
(function($) {
	var media = wp.media;
	var VideoPress = VideoPress || {};

	VideoPress.caps = VideoPressAdminSettings.caps;
	VideoPress.l10n = VideoPressAdminSettings.l10n;

	/**
	 * Create a new controller that simply adds a videopress key
	 * to the library query
	 */
	media.controller.VideoPress = media.controller.Library.extend({
		defaults: _.defaults({
			id:         'videopress',
			router:     'videopress',
			toolbar:    'videopress-toolbar',
			title:      'VideoPress',
			priority:   200,
			searchable: true,
			sortable:   false
		}, media.controller.Library.prototype.defaults ),

		initialize: function() {
			if ( ! this.get('library') ) {
				this.set( 'library', media.query({ videopress: true }) );
			}

			media.controller.Library.prototype.initialize.apply( this, arguments );
		},

		/**
		 * The original function saves content for the browse router only,
		 * so we hi-jack it a little bit.
		 */
		saveContentMode: function() {
			if ( 'videopress' !== this.get('router') ) {
				return;
			}

			var mode = this.frame.content.mode(),
				view = this.frame.router.get();

			if ( view && view.get( mode ) ) {

				// Map the Upload a Video back to the regular Upload Files.
				if ( 'upload_videopress' === mode ) {
					mode = 'upload';
				}

				setUserSetting( 'libraryContent', mode );
			}
		}
	});

	/**
	 * VideoPress Uploader
	 */
	media.view.VideoPressUploader = media.View.extend({
		tagName:   'div',
		className: 'uploader-videopress',
		template:  media.template('videopress-uploader'),

		events: {
			'submit .videopress-upload-form': 'submitForm'
		},

		initialize: function() {
			var that = this;

			if ( ! window.addEventListener ) {
				window.attachEvent( 'onmessage', function() { return that.messageHandler.apply( that, arguments ); } );
			} else {
				window.addEventListener( 'message', function() { return that.messageHandler.apply( that, arguments ); }, false );
			}

			return media.View.prototype.initialize.apply( this, arguments );
		},

		submitForm: function() {
			var data = false;

			this.clearErrors();

			if ( this.$( 'input[name="videopress_file"]').val().length < 1 ) {
				this.error( VideoPress.l10n.selectVideoFile );
				return false;
			}

			// Prevent multiple submissions.
			this.$( '.videopress-upload-form .button' ).prop( 'disabled', true );

			// A non-async request for an upload token.
			media.ajax( 'videopress-get-upload-token', { async: false } ).done( function( response ) {
				data = response;
				data.success = true;
			}).fail( function( response ) {
				data = response;
				data.success = false;
			});

			if ( ! data.success ) {
				// Re-enable form elements.
				this.$( '.videopress-upload-form .button' ).prop( 'disabled', false );

				// Display an error message and cancel form submission.
				this.error( data.message );
				return false;
			}

			this.error( VideoPress.l10n.videoUploading, 'updated' );

			// Set the form token.
			this.$( 'input[name="videopress_blog_id"]' ).val( data.videopress_blog_id );
			this.$( 'input[name="videopress_token"]' ).val( data.videopress_token );
			this.$( '.videopress-upload-form' ).attr( 'action', data.videopress_action_url );
			return true;
		},

		error: function( message, type ) {
			type = type || 'error';
			var div = $( '<div />' ).html( $( '<p />' ).text( message ) ).addClass( type );
			this.$( '.videopress-errors' ).html( div );
			return this;
		},

		success: function( message ) {
			return this.error( message, 'updated' );
		},

		clearErrors: function() {
			this.$( '.videopress-errors' ).html('');
			return this;
		},

		messageHandler: function( event ) {
			if ( ! event.origin.match( /\.wordpress\.com$/ ) ) {
				return;
			}

			if ( event.data.indexOf && event.data.indexOf( 'vpUploadResult::' ) === 0 ) {
				var result = JSON.parse( event.data.substr( 16 ) );

				if ( ! result || ! result.code ) {
					this.error( VideoPress.l10n.unknownError );
					this.$( '.videopress-upload-form .button' ).prop( 'disabled', false );
					return;
				}

				if ( 'success' === result.code && result.data ) {
					var that = this, controller = this.controller,
					    state = controller.states.get( 'videopress' );

					// Our new video has been added, so we need to reset the library.
					// Since the Media API caches all queries, we add a random attribute
					// to avoid the cache, then call more() to actually fetch the data.

					state.set( 'library', media.query({ videopress:true, vp_random:Math.random() }) );
					state.get( 'library' ).more().done(function(){
						var model = state.get( 'library' ).get( result.data.attachment_id );

						// Clear errors and select the uploaded item.
						that.clearErrors();
						state.get( 'selection' ).reset([ model ]);
						controller.content.mode( 'browse' );
					});
				} else {
					this.error( result.code );

					// Re-enable form elements.
					this.$( '.videopress-upload-form .button' ).prop( 'disabled', false );
				}
			}
		}
	});

	/**
	 * Add a custom sync function that would add a few extra
	 * options for models which are VideoPress videos.
	 */
	var attachmentSync = media.model.Attachment.prototype.sync;
	media.model.Attachment.prototype.sync = function( method, model, options ) {
		if ( model.get( 'vp_isVideoPress' ) ) {
			console.log( 'syncing ' + model.get( 'vp_guid' ) );
			options.data = _.extend( options.data || {}, {
				is_videopress: true,
				vp_nonces: model.get( 'vp_nonces' )
			} );
		}

		// Call the original sync routine.
		return attachmentSync.apply( this, arguments );
	};

	/**
	 * Extend the default Attachment Details view. Check for vp_isVideoPress before
	 * adding anything to these methods.
	 */
	var AttachmentDetails = media.view.Attachment.Details;
	media.view.Attachment.Details = AttachmentDetails.extend({

		initialize: function() {
			if ( this.model.get( 'vp_isVideoPress' ) ) {
				_.extend( this.events, {
					'click a.videopress-preview': 'vpPreview',
					'change .vp-radio': 'vpRadioChange',
					'change .vp-checkbox': 'vpCheckboxChange'
				});
			}
			return AttachmentDetails.prototype.initialize.apply( this, arguments );
		},

		render: function() {
			var r = AttachmentDetails.prototype.render.apply( this, arguments );
			if ( this.model.get( 'vp_isVideoPress' ) ) {
				var template = media.template( 'videopress-attachment' );
				var options = this.model.toJSON();

				options.can = {};
				options.can.save = !! options.nonces.update;

				this.$el.append( template( options ) );
			}
			return r;
		},

		// Handle radio buttons
		vpRadioChange: function(e) {
			$( e.target ).parents( '.vp-setting' ).find( '.vp-radio-text' ).val( e.target.value ).change();
		},

		// And checkboxes
		vpCheckboxChange: function(e) {
			$( e.target ).parents( '.vp-setting' ).find( '.vp-checkbox-text' ).val( Number( e.target.checked ) ).change();
		},

		vpPreview: function() {
			VideoPressModal.render( this );
			return this;
		}
	});

	/**
	 * Don't display the uploader dropzone for the VideoPress router.
	 */
	var UploaderWindow = media.view.UploaderWindow;
	media.view.UploaderWindow = UploaderWindow.extend({
		show: function() {
			if ( 'videopress' !== this.controller.state().get('id') ) {
				UploaderWindow.prototype.show.apply( this, arguments );
			}

			return this;
		}
	});

	/**
	 * Don't display the uploader in the attachments browser.
	 */
	var AttachmentsBrowser = media.view.AttachmentsBrowser;
	media.view.AttachmentsBrowser = AttachmentsBrowser.extend({
		/**
		 * Snag the Core 3.9.2 versions as a quick fix to avoid
		 * the breakage introduced by r29364-core
		 */
		updateContent: function() {
			var view = this;

			if( ! this.attachments ) {
				this.createAttachments();
			}

			if ( ! this.collection.length ) {
				this.toolbar.get( 'spinner' ).show();
				this.collection.more().done(function() {
					if ( ! view.collection.length ) {
						view.createUploader();
					}
					view.toolbar.get( 'spinner' ).hide();
				});
			} else {
				view.toolbar.get( 'spinner' ).hide();
			}
		},
		/**
		 * Empty out to avoid breakage.
		 */
		toggleUploader: function() {},
		createUploader: function() {
			if ( 'videopress' !== this.controller.state().get('id') ) {
				return AttachmentsBrowser.prototype.createUploader.apply( this, arguments );
			}
		}
	});

	/**
	 * Add VideoPress-specific methods for all frames.
	 */
	_.extend( media.view.MediaFrame.prototype, { VideoPress: { // this.VideoPress.method()

		// When the VideoPress router is activated.
		activate: function() {
			var view = _.first( this.views.get( '.media-frame-router' ) ),
			    viewSettings = {};

			if ( VideoPress.caps.read_videos ) {
				viewSettings.browse = { text: VideoPress.l10n.VideoPressLibraryRouter, priority: 40 };
			}

			if ( VideoPress.caps.upload_videos ) {
				viewSettings.upload_videopress = { text: VideoPress.l10n.uploadVideoRouter, priority: 20 };
			}

			view.set( viewSettings );

			// Intercept and clear all incoming uploads
			wp.Uploader.queue.on( 'add', this.VideoPress.disableUpload, this );

			// Map the Upload Files view to the Upload a Video one (upload_videopress vs. upload)
			if ( 'upload' === this.content.mode() && VideoPress.caps.upload_videos ) {
				this.content.mode( 'upload_videopress' );
			} else {
				this.content.mode( 'browse' );
			}
		},

		// When navigated away from the VideoPress router.
		deactivate: function( /*view*/ ) {
			wp.Uploader.queue.off( 'add', this.VideoPress.disableUpload );
		},

		// Disable dragdrop uploads in the VideoPress router.
		disableUpload: function( attachment ) {
			var uploader = this.uploader.uploader.uploader;
			uploader.stop();
			uploader.splice();
			attachment.destroy();
		},

		// Runs on videopress:insert event fired by our custom toolbar
		insert: function( selection ) {
			var guid = selection.models[0].get( 'vp_guid' ).replace( /[^a-zA-Z0-9]+/, '' );
			media.editor.insert( '[wpvideo ' + guid + ']' );
			return this;
		},

		// Triggered by the upload_videopress router item.
		uploadVideo: function() {
			this.content.set( new media.view.VideoPressUploader({
				controller: this
			}) );
			return this;
		},

		// Create a custom toolbar
		createToolbar: function( /*toolbar*/ ) {
			// Alow an option to hide the toolbar.
			if ( this.options.VideoPress && this.options.VideoPress.hideToolbar ) {
				return this;
			}

			var controller = this;
			this.toolbar.set( new media.view.Toolbar({
				controller: this,
				items: {
					insert: {
						style:    'primary',
						text:     VideoPress.l10n.insertVideoButton,
						priority: 80,
						requires: {
							library: true,
							selection: true
						},

						click: function() {
							var state = controller.state(),
								selection = state.get('selection');

							controller.close();
							state.trigger( 'videopress:insert', selection ).reset();
						}
					}
				}
			}) );
		}
	}});

	var MediaFrame = {};

	/**
	 * Extend the selection media frame
	 */
	MediaFrame.Select = media.view.MediaFrame.Select;
	media.view.MediaFrame.Select = MediaFrame.Select.extend({
		bindHandlers: function() {
			MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );

			this.on( 'router:create:videopress', this.createRouter, this );
			this.on( 'router:activate:videopress', this.VideoPress.activate, this );
			this.on( 'router:deactivate:videopress', this.VideoPress.deactivate, this );

			this.on( 'content:render:upload_videopress', this.VideoPress.uploadVideo, this );
			this.on( 'toolbar:create:videopress-toolbar', this.VideoPress.createToolbar, this );
			this.on( 'videopress:insert', this.VideoPress.insert, this );
		}
	});

	/**
	 * Extend the post editor media frame with our own
	 */
	MediaFrame.Post = media.view.MediaFrame.Post;
	media.view.MediaFrame.Post = MediaFrame.Post.extend({
		createStates: function() {
			MediaFrame.Post.prototype.createStates.apply( this, arguments );
			this.states.add([ new media.controller.VideoPress() ]);
		}
	});

	/**
	 * A VideoPress Modal view that we can use to preview videos.
	 * Expects a controller object on render.
	 */
	var VideoPressModalView = Backbone.View.extend({
		'className': 'videopress-modal-container',
		'template': wp.media.template( 'videopress-media-modal' ),

		// Render the VideoPress modal with a video object by guid.
		render: function( controller ) {
			this.delegateEvents( {
				'click .videopress-modal-close': 'closeModal',
				'click .videopress-modal-backdrop': 'closeModal'
			} );

			this.model = controller.model;
			this.guid = this.model.get( 'vp_guid' );

			if ( ! this.$frame ) {
				this.$frame = $( '.media-frame-content' );
			}

			this.$el.html( this.template( { 'video' : this.model.get( 'vp_embed' ) } ) );
			this.$modal = this.$( '.videopress-modal' );
			this.$modal.hide();

			this.$frame.append( this.$el );
			this.$modal.slideDown( 'fast' );

			return this;
		},

		closeModal: function() {
			var view = this;
			this.$modal.slideUp( 'fast', function() { view.remove(); } );
			return this;
		}
	});

	var VideoPressModal = new VideoPressModalView();

	// Configuration screen behavior
	$(document).on( 'ready', function() {
		var $form = $( '#videopress-settings' );

		// Not on a configuration screen
		if ( ! $form.length ) {
			return;
		}

		var $access = $form.find( 'input[name="videopress-access"]' ),
		    $upload = $form.find( 'input[name="videopress-upload"]' );

		$access.on( 'change', function() {
			var access = $access.filter( ':checked' ).val();
			$upload.attr( 'disabled', ! access );

			if ( ! access ) {
				$upload.attr( 'checked', false );
			}
		});

		$access.trigger( 'change' );
	});

	// Media -> VideoPress menu
	$(document).on( 'click', '#videopress-browse', function() {

		wp.media({
			state: 'videopress',
			states: [ new media.controller.VideoPress() ],
			VideoPress: { hideToolbar: true }
		}).open();

		return false;
	});
})(jQuery);