-
-
Notifications
You must be signed in to change notification settings - Fork 82
/
admin.js
1030 lines (868 loc) · 34 KB
/
admin.js
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var PODLOVE = PODLOVE || {};
(function($){
var AuphonicWebhookAuthkey = Math.random().toString(36).substring(5);
/**
* Adds loading indicator to a button.
*
* Expects the following HTML:
*
* <span id="my_button">
* <span class="state_idle"><i class="some-icon-class"></i></span>
* <span class="state_working"><i class="podlove-icon-spinner rotate"></i></span>
* <span class="state_success"><i class="podlove-icon-ok"></i></span>
* <span class="state_fail"><i class="podlove-icon-remove"></i></span>
* </span>
*
* Usage:
*
* $("#my_button").button_with_loading_indicator();
* $("#my_button").trigger('start');
* $("#my_button").trigger('stop');
*/
$.fn.button_with_loading_indicator = function(options) {
return this.each(function() {
var $button = $(this),
$htmlButton = $button.closest("button"),
$idle = $button.find(".state_idle"),
$working = $button.find(".state_working"),
$fail = $button.find(".state_fail"),
$success = $button.find(".state_success");
var start = function() {
$idle.hide();
$working.show();
$htmlButton.attr('disabled', 'disabled');
};
var stop = function() {
$working.hide();
$success.show().delay(750).fadeOut(200);
$idle.delay(750).fadeIn(200);
$htmlButton.removeAttr('disabled');
};
var fail = function() {
$working.hide();
$fail.show().delay(750).fadeOut(200);
$idle.delay(750).fadeIn(200);
$htmlButton.removeAttr('disabled');
}
$button.bind('start', start);
$button.bind('stop', stop);
$button.bind('fail', fail);
});
};
function update_production_warning(message) {
$status = $("#auphonic-production-warning");
svg = '<div style="flex-shrink: 0"><svg style="display: block; width: 16px; height: 16px; margin-top: 2px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" /></svg></div>'
if (!message) {
$status.hide();
return;
}
$status.html(svg + "<div>" + message + "</div>");
$status.show();
}
function update_production_status(text, number) {
var css_classes = "status-progress status-ok status-info status-error",
$status = $("#auphonic-production-status");
$status.html(text);
$status.removeClass(css_classes);
switch (number) {
case 0: // "0": "File Upload",
case 1: // "1": "Waiting",
case 4: // "4": "Audio Processing",
case 5: // "5": "Audio Encoding",
case 6: // "6": "Outgoing File Transfer",
case 7: // "7": "Audio Mono Mixdown",
case 8: // "8": "Splitting Audio On Chapter Marks",
case 12: // "12": "Incoming File Transfer",
case 13: // "13": "Stopping the Production"
$status.addClass('status-progress');
break;
case 3: // "3": "Done",
$status.addClass('status-ok');
break;
case 9: // "9": "Incomplete Form",
case 10: // "10": "Production Not Started Yet",
case 11: // "11": "Production Outdated",
$status.addClass('status-info');
break;
case 2: // "2": "Error",
$status.addClass('status-error');
break;
}
}
PODLOVE.AuphonicPresetFetcher = function () {
function getPresetForShow(showSlug) {
const params = new URLSearchParams({
showSlug: showSlug,
episodeId: podlove_vue.episode_id,
action: 'podlove-get-auphonic-preset'
});
fetch(ajaxurl + '?' + params.toString())
.then((response) => response.json())
.then((data) => {
let preset = {key: data.preset_key, name: data.preset_name};
// update "data store"
$("#auphonic").data('presetuuid', preset.key)
});
}
function initPresetFetching() {
const showWidget = document.getElementById("showschecklist")
if (!showWidget) {
return;
}
const items = showWidget.querySelectorAll('li input');
const currentItem = showWidget.querySelector('li input:checked')
for (const item of items) {
item.addEventListener('click', (e) => {
const input = item;
getPresetForShow(input.value)
})
}
if (currentItem) {
getPresetForShow(currentItem.value)
}
}
if (document.readyState !== 'loading') {
initPresetFetching();
} else {
document.addEventListener('DOMContentLoaded', initPresetFetching);
}
};
PODLOVE.AuphonicImport = function () {
var statusTimeoutId;
function get_chapters_string_from_data (production) {
var chapters_entry = "";
var chapters = production.chapters.sort(function(a, b) {
return a.start_sec - b.start_sec;
});
$.each(chapters, function(index, value) {
chapters_entry = chapters_entry + value.start_output + " " + value.title;
if (value.url == "") {
} else {
chapters_entry = chapters_entry + " <" + value.url + ">";
}
chapters_entry = chapters_entry + '\n';
});
return chapters_entry;
}
function get_result_fields(production) {
return [
{ field: '#_podlove_meta_duration', value: production.length_timestring },
{ field: '#_podlove_meta_slug' , value: production.output_basename }
];
}
function get_metadata_fields(production, chapter_asset_assignment) {
var fields = [
{ field: '#title' , value: production.metadata.title },
{ field: '#_podlove_meta_subtitle' , value: production.metadata.subtitle },
{ field: '#_podlove_meta_summary' , value: production.metadata.summary },
{ field: '#new-tag-post_tag' , value: production.metadata.tags.join(" , ") },
{ field: '#_podlove_meta_license_name' , value: production.metadata.license },
{ field: '#_podlove_meta_license_url' , value: production.metadata.license_url },
{ field: '#_podlove_meta_cover_art' , value: production.image }
];
if (chapter_asset_assignment == 'manual') {
fields.push({ field: '#_podlove_meta_chapters', value: get_chapters_string_from_data(production) });
}
return fields;
}
/**
* Import and override existing fields.
*/
function do_force_import(fields) {
$.each(fields, function (index, field) {
if (field.field == '#_podlove_meta_chapters') {
try {
window.chaptersApp.$children[0].doImportChapters(field.value);
} catch (e) {
console.log("Could not import chapters from Auphonic", e);
}
} else {
$(field.field).val(field.value);
}
});
}
/**
* Import but do not override existing fields.
*/
function do_simple_import(fields) {
$.each(fields, function (index, field) {
if ($(field.field).val() == "") {
$(field.field).val(field.value);
}
});
}
function import_production_results(e, production) {
do_force_import(get_result_fields(production));
$.publish("/auphonic/production/status/results_imported", [production]);
}
function fetch_auphonic_production_status(production_uuid) {
var api_url = "https://auphonic.com/api/production/{uuid}.json".replace("{uuid}",production_uuid),
production;
window.clearTimeout(statusTimeoutId); // in case there are multiple running
$.getJSON(api_url, { bearer_token: PODLOVE.Auphonic.get_token() }, function(data) {
if (data && data.status_code == 200) {
production = data.data;
update_production_status(production.status_string, production.status);
update_production_warning(production.warning_message);
if (production.status_string === "Done") {
$("#start_auphonic_production_button, #stop_auphonic_production_button").toggle();
$.publish("/auphonic/production/status/done", [production]);
} else {
statusTimeoutId = window.setTimeout(function() { fetch_auphonic_production_status(production_uuid); }, 5000);
}
}
});
}
/**
* Extract Auphonic relevant data from WordPress web form.
*
* @param {string} mode "init" or "update". Default: "init". Update ignores presets and output files.
*
* @return json In the correct format for the Auphonic API.
*/
function extract_auphonic_data_from_form(mode) {
mode = typeof mode !== 'undefined' ? mode : 'init';
var presetuuid = $("#auphonic").data('presetuuid'),
chapter_asset_assignment = $("#auphonic").data('assignment-chapter'),
cover_art_url = $("#auphonic").data('episode-image') ||
($("#auphonic").data('assignment-image') == 'post-thumbnail' && $('#set-post-thumbnail > img').attr('src')),
podcast_cover_art_url = $("#auphonic").data("podcast-image"),
site_url = $("#auphonic").data('site-url'),
raw_chapters = $("#_podlove_meta_chapters").val(),
chapters = [],
data = {};
data.metadata = {};
if (mode === "init") {
if(typeof presetuuid !== undefined && presetuuid !== "") {
data.preset = presetuuid;
} else {
// no preset? add some output files
data.output_files = [
{"format":"aac", "bitrate":"128", "ending":"m4a"},
{"format":"mp3", "bitrate":"128", "ending":"mp3"},
{"format":"opus", "bitrate":"96", "ending":"opus"}
]
}
}
var service = $("#auphonic_services").val(),
input_file = $("#auphonic_production_files").val(),
input_url = $("#auphonic_http_upload_url").val(),
tags_raw = $(".the-tags").val()
;
if (service === "url") {
data.input_file = input_url;
} else if (service == "file") {
// do nothing
} else {
data.service = service;
data.input_file = input_file;
}
data.length_timestring = $("#_podlove_meta_duration").val();
data.output_basename = $("#_podlove_meta_slug").val();
data.metadata.title = $("#_podlove_meta_title").val() || $("#title").val();
data.metadata.subtitle = $("#_podlove_meta_subtitle").val();
data.metadata.track = parseInt($("#_podlove_meta_number").val(), 10);
data.metadata.summary = $("#_podlove_meta_summary").val();
data.metadata.year = $("#aa").val() || (new Date()).getFullYear();
data.metadata.license = $("#_podlove_meta_license_name").val();
data.metadata.license_url = $("#_podlove_meta_license_url").val();
data.webhook = site_url + "/?podlove-auphonic-production=" + $("#post_ID").val() + "&authkey=" + AuphonicWebhookAuthkey;
data.image = $("#_podlove_meta_cover_art").val() || cover_art_url || podcast_cover_art_url;
if (tags_raw) {
data.metadata.tags = tags_raw.split(',').concat($("#new-tag-post_tag").val().split(','));
} else {
data.metadata.tags = [];
}
if(typeof chapter_asset_assignment !== 'undefined') {
if (chapter_asset_assignment == 'manual' && raw_chapters !== "") {
// todo: replace with https://www.npmjs.com/package/podcast-chapter-parser-mp4chaps
$(raw_chapters.split('\n')).each(function (index, value) {
if(value !== "\n" && value !== "") {
var chapter = new Object();
chapter.start = value.substring(0, value.indexOf(" "));
if(value.indexOf("<") == -1) {
chapter.title = value.substring(value.indexOf(" ") + 1, value.length);
chapter.url = "";
} else {
chapter.title = value.substring(value.indexOf(" ") + 1, value.lastIndexOf(" "));
chapter.url = value.substring(value.lastIndexOf(" "), value.length).substring(2, value.substring(value.lastIndexOf(" "), value.length).length - 1);
}
chapters[index] = chapter;
delete chapter;
}
});
data.chapters = chapters;
}
}
return data;
}
function update_auphonic_production(production_uuid, callback) {
// Delete chapters before adding them again (avoid doubling of chapters)
var url = 'https://auphonic.com/api/production/{uuid}/chapters.json',
production_uuid = $("#auphonic_productions option:selected").val();
var xhr = PODLOVE.Auphonic.createCORSRequest("DELETE", url.replace("{uuid}", production_uuid));
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Authorization","Bearer " + PODLOVE.Auphonic.get_token());
xhr.onloadend = function() {
// Once chapters are deleted update the auphonic production
var url = 'https://auphonic.com/api/production/{uuid}.json'
data = extract_auphonic_data_from_form("update");
var xhr = PODLOVE.Auphonic.createCORSRequest("POST", url.replace("{uuid}", production_uuid));
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Authorization","Bearer " + PODLOVE.Auphonic.get_token());
xhr.onload = function(e) {
callback();
};
xhr.send(JSON.stringify(data));
};
xhr.send();
}
function stop_auphonic_production() {
var url = 'https://auphonic.com/api/production/{uuid}/stop.json',
production_uuid = $("#auphonic_productions option:selected").val();
var xhr = PODLOVE.Auphonic.createCORSRequest("POST", url.replace("{uuid}", production_uuid));
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Authorization","Bearer " + PODLOVE.Auphonic.get_token());
xhr.onload = function(e) {
fetch_auphonic_production_status(production_uuid);
};
xhr.send();
}
function start_auphonic_production() {
var url = 'https://auphonic.com/api/production/{uuid}/start.json',
production_uuid = $("#auphonic_productions option:selected").val();
var xhr = PODLOVE.Auphonic.createCORSRequest("POST", url.replace("{uuid}", production_uuid));
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Authorization","Bearer " + PODLOVE.Auphonic.get_token());
xhr.onload = function(e) {
fetch_auphonic_production_status(production_uuid);
};
xhr.send();
}
/**
* Create Auphonic production.
*/
function create_auphonic_production() {
$button = $("#create_auphonic_production_button span").button_with_loading_indicator();
$button.trigger('start');
var fail = function() {
$button.trigger('fail');
console.warn("Auphonic Production Creation failed. If you are sending images but the image is not publicly available, that might be the reason.");
}
$.publish('/auphonic/createproduction/before');
$.ajax({
dataType: "json",
url: ajaxurl,
data: { action: 'podlove-podcast' },
success: function(publisher_podcast) {
var auphonic_production_data = extract_auphonic_data_from_form();
auphonic_production_data.metadata.publisher = publisher_podcast.publisher_name;
auphonic_production_data.metadata.url = publisher_podcast.publisher_url;
auphonic_production_data.metadata.license = publisher_podcast.license_name;
auphonic_production_data.metadata.license_url = publisher_podcast.license_url;
axios
.post("https://auphonic.com/api/productions.json", auphonic_production_data, {
headers: {
'Authorization': 'Bearer ' + PODLOVE.Auphonic.get_token(),
'Content-type': 'application/json'
}
})
.then(function (response) {
var production = response.data.data,
file = document.querySelector('#auphonic_local_upload_url').files[0];
$.publish('/auphonic/createproduction/success', [production]);
if ($("#auphonic_services").val() == "file" && file) {
$.publish('/auphonic/fileupload', [production, $button] );
} else {
$button.trigger('stop');
$.publish('/auphonic/createproduction/done', [production]);
}
})
.catch(function (error) {
console.log("Auphonic Error when creating production:", error);
fail()
})
}
});
}
/**
* Fetch data from the production and put it into the episode.
*
* @param string import_mode Set to "metadata" to override all data from production result.
* Otherwise set to production results only.
*/
function fetch_production_data(button, import_mode) {
var uuid = $("#auphonic_productions option:selected").val(),
chapter_asset_assignment = $("#auphonic").data("assignment-chapter")
$button = $(" > span", button).button_with_loading_indicator();
$button.trigger('start');
var url = 'https://auphonic.com/api/production/{uuid}.json?bearer_token={token}'
.replace('{uuid}', uuid)
.replace('{token}', PODLOVE.Auphonic.get_token());
$.getJSON(url, function(data) {
if (data && data.data) {
// hide prompt label which usually is placed above the title field
$('#title-prompt-text').addClass('screen-reader-text');
do_force_import(get_result_fields(data.data));
if (import_mode === 'metadata') {
do_force_import(get_metadata_fields(data.data, chapter_asset_assignment));
}
// activate all assets if no asset is active
if ($(".media_file_row input[type=checkbox]:checked").length === 0) {
$(".media_file_row input[type=checkbox]:not(:checked)").click();
}
}
}).fail(function() {
$button.trigger('fail');
}).done(function() {
$button.trigger('stop');
});
}
function fetch_files_for_current_service() {
var uuid = $("#auphonic_services").val(),
api_url = "https://auphonic.com/api/service/{uuid}/ls.json".replace("{uuid}",uuid),
$files = $("#auphonic_production_files"),
$button = $("#fetch_auphonic_production_files").button_with_loading_indicator();
if (uuid == "url") {
$("#auphonic_http_upload_url").show();
$("#auphonic_production_files, #auphonic_local_upload_url").hide();
} else if (uuid == "file") {
$("#auphonic_local_upload_url").show();
$("#auphonic_production_files, #auphonic_http_upload_url").hide();
} else {
$("#auphonic_http_upload_url, #auphonic_local_upload_url").hide();
$("#auphonic_production_files").show();
$button.trigger('start');
$.getJSON(api_url, { bearer_token: PODLOVE.Auphonic.get_token() }, function(data) {
if (data && data.status_code == 200) {
$files.empty();
$.each(data.data, function(index, file) {
$files.append("<option>" + file + "</option>");
});
}
}).fail(function() {
$button.trigger('fail');
$files.empty().append("<option>Unable to load files</option>");
}).done(function() {
$button.trigger('stop');
});
}
}
function fetch_incoming_services() {
var api_url = "https://auphonic.com/api/services.json",
$services = $("#auphonic_services");
$services.empty();
$services.append('<option value="file">Upload from computer</option>')
$services.append('<option value="url">From URL</option>')
$.getJSON(api_url, { bearer_token: PODLOVE.Auphonic.get_token() }, function(data) {
if (data.status_code == 200) {
$.each(data.data, function(index, service) {
if (service.incoming) {
$services.append("<option value='" + service.uuid + "'>" + service.display_name + " (" + service.type + ")</option>");
}
});
fetch_files_for_current_service();
}
}).fail(function() {
$services.empty().append("<option>Unable to load Services</option>");
}).done(function() {
// console.log("fetch service: succeeded");
});
}
function fetch_processing_time() {
var api_url = "https://auphonic.com/api/user.json",
$credits = $("#auphonic-credits"),
$credits_container = $("#auphonic-credits-status");
$.getJSON(api_url, { bearer_token: PODLOVE.Auphonic.get_token() }, function(data) {
if (data.status_code == 200) {
var hours = parseInt(data.data.credits, 10),
minutes = parseInt((data.data.credits - hours) * 60, 10),
status = hours + "h" + (minutes ? (" " + minutes + "m") : "");
$credits.html(status);
$credits_container.show();
}
}).fail(function() {
$credits_container.hide();
});
}
function fetch_flag() {
if ( $("#auphonic_publish_after_finishing").is(":checked") ) {
return 'publish';
} else {
return 'update';
}
}
/**
* Start an Auphonic production process.
*
* - handle button states
* - update production with current episode data
* - start the actual production
*/
function do_auphonic_production() {
$("#start_auphonic_production_button, #stop_auphonic_production_button").toggle();
update_auphonic_production($("#auphonic_productions option:selected").val(), function(){
start_auphonic_production();
});
}
if ($("#auphonic").length) {
// automatically import production results when production is done
$.subscribe("/auphonic/production/status/done", import_production_results);
// Automatically publish after results are imported (if flag is set).
// Wait a second in case stuff is still going on after the results
// were imported — like media file checking.
$.subscribe("/auphonic/production/status/results_imported", function(e, production) {
if ($("#start_auphonic_production_button").is(":checked")) {
setTimeout(function() {
$("#publish").click();
}, 1000);
}
});
$.subscribe('/auphonic/createdproduction/added', function(e, production) {
if ($("#auphonic_start_after_creation").is(":checked")) {
do_auphonic_production();
}
});
var register_auphonic_webhook = function(e) {
$.ajax({
url: ajaxurl,
data: {
action: "podlove-add-production-for-auphonic-webhook",
flag: fetch_flag(),
authkey: AuphonicWebhookAuthkey,
post_id: $("#post_ID").val()
},
dataType: 'json'
});
};
// Create Auphonic webhook events for publishing and saving
$("#start_auphonic_production_button").on('click', register_auphonic_webhook);
$("#auphonic_productions").chosen({ width: "50%", search_contains: true });
$("#auphonic_productions").change(function(e) {
var $production = $("option:selected", this),
production = $production.data();
if ($production.val() !== "0") {
// remove "choose production" option
$("#auphonic_productions option[value=0]").remove();
// update "chosen"
$("#auphonic_productions").trigger("chosen:updated");
$("#_auphonic_production").val($production.val());
update_production_status(production.status, production.status_number);
update_production_warning(production.warning_message);
$("#auphonic-selected-production button").attr("disabled", false);
$("#open_production_button").attr("disabled", false);
} else {
$("#auphonic-selected-production").attr("disabled", true);
$("#open_production_button").attr("disabled", true);
}
});
$("#fetch_production_data_button").click(function (e) {
e.preventDefault();
fetch_production_data($(this), 'metadata');
});
$("#fetch_production_results_button").click(function (e) {
e.preventDefault();
fetch_production_data($(this), 'results');
});
$("#create_auphonic_production_button").click(function (e) {
e.preventDefault();
create_auphonic_production();
});
$("#start_auphonic_production_button").click(function(e) {
e.preventDefault();
do_auphonic_production();
});
$("#stop_auphonic_production_button").click(function(e) {
e.preventDefault();
$("#start_auphonic_production_button, #stop_auphonic_production_button").toggle();
stop_auphonic_production();
});
$("#open_production_button").click(function (e) {
e.preventDefault();
window.open('https://auphonic.com/engine/upload/edit/' + $("#auphonic_productions").find(":selected").val());
});
$("#fetch_auphonic_production_files").click(function(){
fetch_files_for_current_service();
});
$("#auphonic_services").change(function(){
fetch_files_for_current_service();
});
$(document).ready(function() {
fetch_incoming_services();
fetch_processing_time();
});
}
}
/**
* Starting below are tidy logic-modules.
* Above is "JS Spaghetti Blurb" that works but should be modularized, too.
*/
/**
* Auphonic Helper Methods
*/
PODLOVE.Auphonic = (function(){
return {
get_token: function() {
return $("#auphonic").data('api-key');
},
createCORSRequest: function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true); // XHR for Chrome/Firefox/Opera/Safari
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest(); // XDomainRequest for IE
xhr.open(method, url);
} else {
xhr = null; // CORS not supported
}
return xhr;
},
pad_number: function (n, p, c) {
var pad_char = typeof c !== 'undefined' ? c : '0';
var pad = new Array(1 + p).join(pad_char);
return (pad + n).slice(-pad.length);
},
refresh_preset_list: function( that ) {
var data = {
action: 'podlove-refresh-auphonic-presets'
};
var selected_preset = $("#podlove_module_auphonic_auphonic_production_preset").val();
$(that).html('<i class="podlove-icon-spinner rotate"></i>');
$.ajax({
url: ajaxurl,
data: data,
dataType: 'json',
success: function(result) {
$("#podlove_module_auphonic_auphonic_production_preset").children( 'option:not(:first)' ).remove();
$.each( result.data, function( index, value) {
$("#podlove_module_auphonic_auphonic_production_preset").append("<option value='" + value.uuid + "'>" + value.preset_name + "</option>");
});
$("#podlove_module_auphonic_auphonic_production_preset").val( selected_preset );
$(that).html('<i class="podlove-icon-repeat"></i>');
}
});
}
}
}());
/**
* Auphonic Production Fethcer
*
* This module fills the list of available productions.
* It ensures it's always up to date.
*/
PODLOVE.AuphonicProductionFetcher = (function(){
var $productions, $button, url;
var init = function() {
$(document).ready(function () {
$productions = $("#auphonic_productions");
if (!$productions.length) return;
$button = $("#reload_productions_button").button_with_loading_indicator();
url = 'https://auphonic.com/api/productions.json?bearer_token={token}'
.replace('{token}', PODLOVE.Auphonic.get_token());
$("#reload_productions_button").on('click', fetch);
$.subscribe('/auphonic/createproduction/done', addCreatedProduction);
fetch();
});
};
var refreshSelectUI = function() {
jQuery("#auphonic_productions")
.change()
.trigger("chosen:updated"); // for "chosen"
};
var fetch = function(e, production) {
$button.trigger('start');
$.getJSON(url, function(data) {
if (!data) return;
var production_list = [],
auphonic_productions = data.data;
$("#auphonic_productions").empty();
$("#auphonic_productions").append('<option value="0">Select existing Production</option>\n');
$(auphonic_productions).each(function(key, auphonic_production) {
$("#auphonic_productions").append(productionOptionTag(auphonic_production, production));
});
refreshSelectUI();
}).fail(function() {
$button.trigger('fail');
}).done(function() {
$button.trigger('stop');
});
};
var addCreatedProduction = function(e, production) {
// deselect currently selected
$("#auphonic_productions option:selected").removeAttr("selected");
// add new option and select it
$("#auphonic_productions").prepend(productionOptionTag(production, production));
refreshSelectUI();
$.publish('/auphonic/createdproduction/added', [production]);
};
/**
* Generates <option> tag for production selector.
*
* @param object production Production object as it is returned from Auphonic.
* @return jQuery wrapped <option> tag
*/
var productionOptionTag = function(production, current_production) {
var date = new Date(production.change_time),
output_basename = $.trim(production.output_basename),
saved_production_uuid = $("#_auphonic_production").val(),
production_title, option_title;
// title
if (production.metadata.title) {
production_title = production.metadata.title;
} else if (output_basename.length) {
production_title = output_basename;
} else {
production_title = '(no title)';
}
option_title = production_title + ' (' + date.getFullYear() + '-' + PODLOVE.Auphonic.pad_number(date.getMonth()+1,2) + '-' + PODLOVE.Auphonic.pad_number(date.getDate(),2) + ')';
// check if it should be selected
selected = "";
if (current_production) {
if (current_production.uuid == production.uuid) {
selected = "selected";
}
} else if (saved_production_uuid == production.uuid) {
selected = "selected";
}
// generate html
$option = $('<option value="' + production.uuid + '" ' + selected + '>' + option_title + '</option>\n');
$option.data({
"title": production_title,
"date": date,
"datestring": timeSince(date),
"status": production.status_string,
"status_number": production.status,
"warning_message": production.warning_message
});
return $option;
};
var timeSince = function (date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + " years ago";
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + " months ago";
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + " days ago";
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + " hours ago";
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + " minutes ago";
}
return "just now";
};
init();
return {};
}());
/**
* Auphonic File Uploader
*
* This module handles the file upload of media files to Auphonic.
*/
PODLOVE.AuphonicFileUploader = (function() {
var $service;
var init = function() {
$(document).ready(function () {
$service = $("#auphonic_services");
$.subscribe('/auphonic/fileupload', doUpload);
});
};
var isFileUpload = function() {
return $service.val() === "file" && typeof getFile() === "object";
};
var getFile = function() {
return document.querySelector('#auphonic_local_upload_url').files[0];
};
var doUpload = function(event, production, button) {
$.publish('/auphonic/fileupload/before', [production])
var url = 'https://auphonic.com/api/production/{uuid}/upload.json'.replace('{uuid}', production.uuid),
xhr2 = PODLOVE.Auphonic.createCORSRequest("POST", url),
formData = new FormData(),
fail = function() { button.trigger('fail'); };
xhr2.addEventListener("error", fail, false);
xhr2.addEventListener("abort", fail, false);
xhr2.upload.addEventListener("progress", function(e) {
var percent = (e.loaded / e.total) * 100;
$.publish('/auphonic/fileupload/progress', [production, percent])
}, false);
xhr2.onload = function(e) {
var response = JSON.parse(e.target.response),
production = production = response.data;
update_production_status(production.status_string, production.status);
update_production_warning(production.warning_message);
$.publish('/auphonic/fileupload/done', [production])
$.publish('/auphonic/createproduction/done', [production]);
button.trigger('stop');
};
formData.append('input_file', getFile());
xhr2.setRequestHeader("Authorization", "Bearer " + PODLOVE.Auphonic.get_token());
xhr2.send(formData);
};
init();
return {
isFileUpload: isFileUpload
};
}());
/**
* Auphonic CreateProduction Status
*
* This module handles the status text for production creation
* and file upload.
*/
PODLOVE.AuphonicCreateProductionStatus = (function() {
var $status;
var init = function() {
$(document).ready(function () {
$status = $("#auphonic-production-status");
$status.html('Please select a File').show();
// upload
$.subscribe('/auphonic/fileupload/before', updateUploadBefore)
$.subscribe('/auphonic/fileupload/progress', updateUploadProgress)
$.subscribe('/auphonic/fileupload/done', updateUploadDone);
$.subscribe('/auphonic/createproduction/before', updateProductionStart)
// create production
$.subscribe('/auphonic/createproduction/success', updateProductionSuccess)
$.subscribe('/auphonic/createproduction/done', updateProductionDone)
});
};
var updateProductionDone = function(e) {
// $status.delay(1500).slideUp(300);
};
var updateProductionSuccess = function(e) {
$status.html("Production created").removeClass('status-progress').addClass('status-ok').show();
};
var updateProductionStart = function(e) {
$status.html("Creating production").addClass('status-progress').removeClass('status-ok').css("display", "block");
};