Passed
Push — master ( 8f2b28...41c717 )
by Jacob
01:34
created

yui/src/recording/js/audiomodule.js   B

Complexity

Total Complexity 41
Complexity/F 1.86

Size

Lines of Code 254
Function Count 22

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
c 1
b 0
f 0
nc 12
dl 0
loc 254
rs 8.2769
wmc 41
mnd 5
bc 34
fnc 22
bpm 1.5454
cpm 1.8636
noi 19

3 Functions

Rating   Name   Duplication   Size   Complexity  
A M.atto_recordrtc.audiomodule.capture_audio 0 21 1
A M.atto_recordrtc.audiomodule.stop_recording 0 57 1
B M.atto_recordrtc.audiomodule.init 0 166 1

How to fix   Complexity   

Complexity

Complex classes like yui/src/recording/js/audiomodule.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
// Atto recordrtc library functions.
2
// @package    atto_recordrtc.
3
// @author     Jesus Federico (jesus [at] blindsidenetworks [dt] com).
4
// @copyright  2016 to present, Blindside Networks Inc.
5
// @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
6
7
/*jshint es5: true */
8
/*jshint onevar: false */
9
/*jshint shadow: true */
10
/*global M */
11
/*global MediaRecorder */
12
/*global URL */
13
/*global InstallTrigger */
14
15
M.atto_recordrtc = M.atto_recordrtc || {};
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
16
17
// Shorten access to M.atto_recordrtc.commonmodule namespace.
18
var cm = M.atto_recordrtc.commonmodule;
19
20
M.atto_recordrtc.audiomodule = {
21
    init: function(scope) {
22
        // Assignment of global variables.
23
        cm.editorScope = scope; // Allows access to the editor's "this" context.
24
        cm.alertWarning = Y.one('div#alert-warning');
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
25
        cm.alertDanger = Y.one('div#alert-danger');
26
        cm.player = Y.one('audio#player');
27
        cm.playerDOM = document.querySelector('audio#player');
28
        cm.startStopBtn = Y.one('button#start-stop');
29
        cm.uploadBtn = Y.one('button#upload');
30
        cm.recType = 'audio';
31
        cm.olderMoodle = scope.get('oldermoodle');
32
        // Extract the numbers from the string, and convert to bytes.
33
        cm.maxUploadSize = parseInt(scope.get('maxrecsize').match(/\d+/)[0], 10) * Math.pow(1024, 2);
34
35
        // Show alert and redirect user if connection is not secure.
36
        cm.check_secure();
37
        // Show alert if using non-ideal browser.
38
        cm.check_browser();
39
40
        // Run when user clicks on "record" button.
41
        cm.startStopBtn.on('click', function() {
42
            cm.startStopBtn.set('disabled', true);
43
44
            // If button is displaying "Start Recording" or "Record Again".
45
            if ((cm.startStopBtn.get('textContent') === M.util.get_string('startrecording', 'atto_recordrtc')) ||
46
                (cm.startStopBtn.get('textContent') === M.util.get_string('recordagain', 'atto_recordrtc')) ||
47
                (cm.startStopBtn.get('textContent') === M.util.get_string('recordingfailed', 'atto_recordrtc'))) {
48
                // Make sure the audio player and upload button are not shown.
49
                cm.player.ancestor().ancestor().addClass('hide');
50
                cm.uploadBtn.ancestor().ancestor().addClass('hide');
51
52
                // Change look of recording button.
53
                if (!cm.olderMoodle) {
54
                    cm.startStopBtn.replaceClass('btn-outline-danger', 'btn-danger');
55
                }
56
57
                // Empty the array containing the previously recorded chunks.
58
                cm.chunks = [];
59
                cm.blobSize = 0;
60
61
                // Initialize common configurations.
62
                var commonConfig = {
63
                    // When the stream is captured from the microphone/webcam.
64
                    onMediaCaptured: function(stream) {
65
                        // Make audio stream available at a higher level by making it a property of the common module.
66
                        cm.stream = stream;
67
68
                        if (cm.startStopBtn.mediaCapturedCallback) {
69
                            cm.startStopBtn.mediaCapturedCallback();
70
                        }
71
                    },
72
73
                    // Revert button to "Record Again" when recording is stopped.
74
                    onMediaStopped: function(btnLabel) {
75
                        cm.startStopBtn.set('textContent', btnLabel);
76
                    },
77
78
                    // Handle recording errors.
79
                    onMediaCapturingFailed: function(error) {
80
                        var btnLabel = null;
81
82
                        // Handle getUserMedia-thrown errors.
83
                        switch (error.name) {
0 ignored issues
show
Coding Style introduced by
As per coding-style, switch statements should have a default case.
Loading history...
84
                            case 'AbortError':
85
                                Y.use('moodle-core-notification-alert', function() {
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
86
                                    new M.core.alert({
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new M.core.alert({Identi...ode(atto_recordrtc)))}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
87
                                        title: M.util.get_string('gumabort_title', 'atto_recordrtc'),
88
                                        message: M.util.get_string('gumabort', 'atto_recordrtc')
89
                                    });
90
                                });
91
92
                                btnLabel = M.util.get_string('recordingfailed', 'atto_recordrtc');
93
                                break;
94
                            case 'NotAllowedError':
95
                                Y.use('moodle-core-notification-alert', function() {
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
96
                                    new M.core.alert({
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new M.core.alert({Identi...ode(atto_recordrtc)))}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
97
                                        title: M.util.get_string('gumnotallowed_title', 'atto_recordrtc'),
98
                                        message: M.util.get_string('gumnotallowed', 'atto_recordrtc')
99
                                    });
100
                                });
101
102
                                btnLabel = M.util.get_string('recordingfailed', 'atto_recordrtc');
103
                                break;
104
                            case 'NotFoundError':
105
                                Y.use('moodle-core-notification-alert', function() {
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
106
                                    new M.core.alert({
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new M.core.alert({Identi...ode(atto_recordrtc)))}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
107
                                        title: M.util.get_string('gumnotfound_title', 'atto_recordrtc'),
108
                                        message: M.util.get_string('gumnotfound', 'atto_recordrtc')
109
                                    });
110
                                });
111
112
                                btnLabel = M.util.get_string('recordingfailed', 'atto_recordrtc');
113
                                break;
114
                            case 'NotReadableError':
115
                                Y.use('moodle-core-notification-alert', function() {
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
116
                                    new M.core.alert({
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new M.core.alert({Identi...ode(atto_recordrtc)))}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
117
                                        title: M.util.get_string('gumnotreadable_title', 'atto_recordrtc'),
118
                                        message: M.util.get_string('gumnotreadable', 'atto_recordrtc')
119
                                    });
120
                                });
121
122
                                btnLabel = M.util.get_string('recordingfailed', 'atto_recordrtc');
123
                                break;
124
                            case 'OverConstrainedError':
125
                                Y.use('moodle-core-notification-alert', function() {
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
126
                                    new M.core.alert({
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new M.core.alert({Identi...ode(atto_recordrtc)))}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
127
                                        title: M.util.get_string('gumoverconstrained_title', 'atto_recordrtc'),
128
                                        message: M.util.get_string('gumoverconstrained', 'atto_recordrtc')
129
                                    });
130
                                });
131
132
                                btnLabel = M.util.get_string('recordingfailed', 'atto_recordrtc');
133
                                break;
134
                            case 'SecurityError':
135
                                Y.use('moodle-core-notification-alert', function() {
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
136
                                    new M.core.alert({
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new M.core.alert({Identi...ode(atto_recordrtc)))}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
137
                                        title: M.util.get_string('gumsecurity_title', 'atto_recordrtc'),
138
                                        message: M.util.get_string('gumsecurity', 'atto_recordrtc')
139
                                    });
140
                                });
141
142
                                cm.editorScope.closeDialogue(cm.editorScope);
143
                                break;
144
                            case 'TypeError':
145
                                Y.use('moodle-core-notification-alert', function() {
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
146
                                    new M.core.alert({
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new M.core.alert({Identi...ode(atto_recordrtc)))}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
147
                                        title: M.util.get_string('gumtype_title', 'atto_recordrtc'),
148
                                        message: M.util.get_string('gumtype', 'atto_recordrtc')
149
                                    });
150
                                });
151
152
                                btnLabel = M.util.get_string('recordingfailed', 'atto_recordrtc');
153
                        }
154
155
                        // Proceed to treat as a stopped recording.
156
                        commonConfig.onMediaStopped(btnLabel);
157
                    }
158
                };
159
160
                // Capture audio stream from microphone.
161
                M.atto_recordrtc.audiomodule.capture_audio(commonConfig);
162
163
                // When audio stream is successfully captured, start recording.
164
                cm.startStopBtn.mediaCapturedCallback = function() {
165
                    cm.start_recording(cm.recType, cm.stream);
166
                };
167
            } else { // If button is displaying "Stop Recording".
168
                // First of all clears the countdownTicker.
169
                clearInterval(cm.countdownTicker);
170
171
                // Disable "Record Again" button for 1s to allow background processing (closing streams).
172
                setTimeout(function() {
173
                    cm.startStopBtn.set('disabled', false);
174
                }, 1000);
175
176
                // Stop recording.
177
                M.atto_recordrtc.audiomodule.stop_recording(cm.stream);
178
179
                // Change button to offer to record again.
180
                cm.startStopBtn.set('textContent', M.util.get_string('recordagain', 'atto_recordrtc'));
181
                if (!cm.olderMoodle) {
182
                    cm.startStopBtn.replaceClass('btn-danger', 'btn-outline-danger');
183
                }
184
            }
185
        });
186
    },
187
188
    // Setup to get audio stream from microphone.
189
    capture_audio: function(config) {
190
        cm.capture_user_media(
191
            // Media constraints.
192
            {
193
                audio: true
194
            },
195
196
            // Success callback.
197
            function(audioStream) {
198
                // Set audio player source to microphone stream.
199
                cm.playerDOM.srcObject = audioStream;
200
201
                config.onMediaCaptured(audioStream);
202
            },
203
204
            // Error callback.
205
            function(error) {
206
                config.onMediaCapturingFailed(error);
207
            }
208
        );
209
    },
210
211
    stop_recording: function(stream) {
212
        // Stop recording microphone stream.
213
        cm.mediaRecorder.stop();
214
215
        // Stop each individual MediaTrack.
216
        stream.getTracks().forEach(function(track) {
217
            track.stop();
218
        });
219
220
        // Set source of audio player.
221
        var blob = new Blob(cm.chunks, {type: cm.mediaRecorder.mimeType});
0 ignored issues
show
Bug introduced by
The variable Blob seems to be never declared. If this is a global, consider adding a /** global: Blob */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
222
        cm.player.set('src', URL.createObjectURL(blob));
223
224
        // Show audio player with controls enabled, and unmute.
225
        cm.player.set('muted', false);
226
        cm.player.set('controls', true);
227
        cm.player.ancestor().ancestor().removeClass('hide');
228
229
        // Show upload button.
230
        cm.uploadBtn.ancestor().ancestor().removeClass('hide');
231
        cm.uploadBtn.set('textContent', M.util.get_string('attachrecording', 'atto_recordrtc'));
232
        cm.uploadBtn.set('disabled', false);
233
234
        // Handle when upload button is clicked.
235
        cm.uploadBtn.on('click', function() {
236
            // Trigger error if no recording has been made.
237
            if (!cm.player.getAttribute('src') || cm.chunks === []) {
238
                Y.use('moodle-core-notification-alert', function() {
0 ignored issues
show
Bug introduced by
The variable Y seems to be never declared. If this is a global, consider adding a /** global: Y */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
239
                    new M.core.alert({
0 ignored issues
show
Unused Code Best Practice introduced by
The object created with new M.core.alert({Identi...ode(atto_recordrtc)))}) is not used but discarded. Consider invoking another function instead of a constructor if you are doing this purely for side effects.
Loading history...
240
                        title: M.util.get_string('norecordingfound_title', 'atto_recordrtc'),
241
                        message: M.util.get_string('norecordingfound', 'atto_recordrtc')
242
                    });
243
                });
244
            } else {
245
                cm.uploadBtn.set('disabled', true);
246
247
                // Upload recording to server.
248
                cm.upload_to_server(cm.recType, function(progress, fileURLOrError) {
249
                    if (progress === 'ended') { // Insert annotation in text.
250
                        cm.uploadBtn.set('disabled', false);
251
                        cm.insert_annotation(cm.recType, fileURLOrError);
252
                    } else if (progress === 'upload-failed') { // Show error message in upload button.
253
                        cm.uploadBtn.set('disabled', false);
254
                        cm.uploadBtn.set('textContent', M.util.get_string('uploadfailed', 'atto_recordrtc') + ' ' + fileURLOrError);
255
                    } else if (progress === 'upload-failed-404') { // 404 error = File too large in Moodle.
256
                        cm.uploadBtn.set('disabled', false);
257
                        cm.uploadBtn.set('textContent', M.util.get_string('uploadfailed404', 'atto_recordrtc'));
258
                    } else if (progress === 'upload-aborted') {
259
                        cm.uploadBtn.set('disabled', false);
260
                        cm.uploadBtn.set('textContent', M.util.get_string('uploadaborted', 'atto_recordrtc') + ' ' + fileURLOrError);
261
                    } else {
262
                        cm.uploadBtn.set('textContent', progress);
263
                    }
264
                });
265
            }
266
        });
267
    }
268
};
269