Passed
Push — master ( 2baee7...d0526d )
by Jacob
01:42
created

yui/src/recording/js/audiomodule.js   A

Complexity

Total Complexity 35
Complexity/F 2.33

Size

Lines of Code 212
Function Count 15

Duplication

Duplicated Lines 212
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
nc 12
dl 212
loc 212
rs 9
c 1
b 0
f 0
wmc 35
mnd 5
bc 27
fnc 15
bpm 1.8
cpm 2.3333
noi 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A M.atto_recordrtc.audiomodule.capture_audio 21 21 1
A M.atto_recordrtc.audiomodule.stop_recording 54 54 1
B M.atto_recordrtc.audiomodule.init 127 127 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
//
16
17
/**
18
 * Atto recordrtc library functions
19
 *
20
 * @package    atto_recordrtc
21
 * @author     Jesus Federico (jesus [at] blindsidenetworks [dt] com)
22
 * @author     Jacob Prud'homme (jacob [dt] prudhomme [at] blindsidenetworks [dt] com)
23
 * @copyright  2017 Blindside Networks Inc.
24
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25
 */
26
27
// JSHint directives.
28
/*jshint es5: true */
29
/*jshint onevar: false */
30
/*jshint shadow: true */
31
/*global M */
32
33
// Scrutinizer CI directives.
34
/** global: M */
35
/** global: Y */
36
37 View Code Duplication
M.atto_recordrtc = M.atto_recordrtc || {};
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
38
39
// Shorten access to M.atto_recordrtc.commonmodule namespace.
40
var cm = M.atto_recordrtc.commonmodule;
41
42
M.atto_recordrtc.audiomodule = {
43
    init: function(scope) {
44
        // Assignment of global variables.
45
        cm.editorScope = scope; // Allows access to the editor's "this" context.
46
        cm.alertWarning = Y.one('div#alert-warning');
47
        cm.alertDanger = Y.one('div#alert-danger');
48
        cm.player = Y.one('audio#player');
49
        cm.playerDOM = document.querySelector('audio#player');
50
        cm.startStopBtn = Y.one('button#start-stop');
51
        cm.uploadBtn = Y.one('button#upload');
52
        cm.recType = 'audio';
53
        cm.olderMoodle = scope.get('oldermoodle');
54
        // Extract the numbers from the string, and convert to bytes.
55
        cm.maxUploadSize = window.parseInt(scope.get('maxrecsize').match(/\d+/)[0], 10) * Math.pow(1024, 2);
56
57
        // Show alert and redirect user if connection is not secure.
58
        cm.check_secure();
59
        // Show alert if using non-ideal browser.
60
        cm.check_browser();
61
62
        // Run when user clicks on "record" button.
63
        cm.startStopBtn.on('click', function() {
64
            cm.startStopBtn.set('disabled', true);
65
66
            // If button is displaying "Start Recording" or "Record Again".
67
            if ((cm.startStopBtn.get('textContent') === M.util.get_string('startrecording', 'atto_recordrtc')) ||
68
                (cm.startStopBtn.get('textContent') === M.util.get_string('recordagain', 'atto_recordrtc')) ||
69
                (cm.startStopBtn.get('textContent') === M.util.get_string('recordingfailed', 'atto_recordrtc'))) {
70
                // Make sure the audio player and upload button are not shown.
71
                cm.player.ancestor().ancestor().addClass('hide');
72
                cm.uploadBtn.ancestor().ancestor().addClass('hide');
73
74
                // Change look of recording button.
75
                if (!cm.olderMoodle) {
76
                    cm.startStopBtn.replaceClass('btn-outline-danger', 'btn-danger');
77
                }
78
79
                // Empty the array containing the previously recorded chunks.
80
                cm.chunks = [];
81
                cm.blobSize = 0;
82
83
                // Initialize common configurations.
84
                var commonConfig = {
85
                    // When the stream is captured from the microphone/webcam.
86
                    onMediaCaptured: function(stream) {
87
                        // Make audio stream available at a higher level by making it a property of the common module.
88
                        cm.stream = stream;
89
90
                        cm.start_recording(cm.recType, cm.stream);
91
                    },
92
93
                    // Revert button to "Record Again" when recording is stopped.
94
                    onMediaStopped: function(btnLabel) {
95
                        cm.startStopBtn.set('textContent', btnLabel);
96
                        cm.startStopBtn.set('disabled', false);
97
                        if (!cm.olderMoodle) {
98
                            cm.startStopBtn.replaceClass('btn-danger', 'btn-outline-danger');
99
                        }
100
                    },
101
102
                    // Handle recording errors.
103
                    onMediaCapturingFailed: function(error) {
104
                        var btnLabel = M.util.get_string('recordingfailed', 'atto_recordrtc');
105
                        var treatAsStopped = function() {
106
                            commonConfig.onMediaStopped(btnLabel);
107
                        };
108
109
                        // Handle getUserMedia-thrown errors.
110
                        // After alert, proceed to treat as stopped recording, or close dialogue.
111
                        switch (error.name) {
112
                            case 'AbortError':
113
                                cm.show_alert('gumabort', treatAsStopped);
114
115
                                break;
116
                            case 'NotAllowedError':
117
                                cm.show_alert('gumnotallowed', treatAsStopped);
118
119
                                break;
120
                            case 'NotFoundError':
121
                                cm.show_alert('gumnotfound', treatAsStopped);
122
123
                                break;
124
                            case 'NotReadableError':
125
                                cm.show_alert('gumnotreadable', treatAsStopped);
126
127
                                break;
128
                            case 'OverConstrainedError':
129
                                cm.show_alert('gumoverconstrained', treatAsStopped);
130
131
                                break;
132
                            case 'SecurityError':
133
                                cm.show_alert('gumsecurity', function() {
134
                                    cm.editorScope.closeDialogue(cm.editorScope);
135
                                });
136
137
                                break;
138
                            case 'TypeError':
139
                                cm.show_alert('gumtype', treatAsStopped);
140
141
                                break;
142
                            default:
143
                                break;
144
                        }
145
                    }
146
                };
147
148
                // Capture audio stream from microphone.
149
                M.atto_recordrtc.audiomodule.capture_audio(commonConfig);
150
            } else { // If button is displaying "Stop Recording".
151
                // First of all clears the countdownTicker.
152
                window.clearInterval(cm.countdownTicker);
153
154
                // Disable "Record Again" button for 1s to allow background processing (closing streams).
155
                window.setTimeout(function() {
156
                    cm.startStopBtn.set('disabled', false);
157
                }, 1000);
158
159
                // Stop recording.
160
                M.atto_recordrtc.audiomodule.stop_recording(cm.stream);
161
162
                // Change button to offer to record again.
163
                cm.startStopBtn.set('textContent', M.util.get_string('recordagain', 'atto_recordrtc'));
164
                if (!cm.olderMoodle) {
165
                    cm.startStopBtn.replaceClass('btn-danger', 'btn-outline-danger');
166
                }
167
            }
168
        });
169
    },
170
171
    // Setup to get audio stream from microphone.
172
    capture_audio: function(config) {
173
        cm.capture_user_media(
174
            // Media constraints.
175
            {
176
                audio: true
177
            },
178
179
            // Success callback.
180
            function(audioStream) {
181
                // Set audio player source to microphone stream.
182
                cm.playerDOM.srcObject = audioStream;
183
184
                config.onMediaCaptured(audioStream);
185
            },
186
187
            // Error callback.
188
            function(error) {
189
                config.onMediaCapturingFailed(error);
190
            }
191
        );
192
    },
193
194
    stop_recording: function(stream) {
195
        // Stop recording microphone stream.
196
        cm.mediaRecorder.stop();
197
198
        // Stop each individual MediaTrack.
199
        stream.getTracks().forEach(function(track) {
200
            track.stop();
201
        });
202
203
        // Set source of audio player.
204
        var blob = new window.Blob(cm.chunks, {type: cm.mediaRecorder.mimeType});
205
        cm.player.set('src', window.URL.createObjectURL(blob));
206
207
        // Show audio player with controls enabled, and unmute.
208
        cm.player.set('muted', false);
209
        cm.player.set('controls', true);
210
        cm.player.ancestor().ancestor().removeClass('hide');
211
212
        // Show upload button.
213
        cm.uploadBtn.ancestor().ancestor().removeClass('hide');
214
        cm.uploadBtn.set('textContent', M.util.get_string('attachrecording', 'atto_recordrtc'));
215
        cm.uploadBtn.set('disabled', false);
216
217
        // Handle when upload button is clicked.
218
        cm.uploadBtn.on('click', function() {
219
            // Trigger error if no recording has been made.
220
            if (!cm.player.get('src') || cm.chunks === []) {
221
                cm.show_alert('norecordingfound');
222
            } else {
223
                cm.uploadBtn.set('disabled', true);
224
225
                // Upload recording to server.
226
                cm.upload_to_server(cm.recType, function(progress, fileURLOrError) {
227
                    if (progress === 'ended') { // Insert annotation in text.
228
                        cm.uploadBtn.set('disabled', false);
229
                        cm.insert_annotation(cm.recType, fileURLOrError);
230
                    } else if (progress === 'upload-failed') { // Show error message in upload button.
231
                        cm.uploadBtn.set('disabled', false);
232
                        cm.uploadBtn.set('textContent',
233
                            M.util.get_string('uploadfailed', 'atto_recordrtc') + ' ' + fileURLOrError);
234
                    } else if (progress === 'upload-failed-404') { // 404 error = File too large in Moodle.
235
                        cm.uploadBtn.set('disabled', false);
236
                        cm.uploadBtn.set('textContent', M.util.get_string('uploadfailed404', 'atto_recordrtc'));
237
                    } else if (progress === 'upload-aborted') {
238
                        cm.uploadBtn.set('disabled', false);
239
                        cm.uploadBtn.set('textContent',
240
                            M.util.get_string('uploadaborted', 'atto_recordrtc') + ' ' + fileURLOrError);
241
                    } else {
242
                        cm.uploadBtn.set('textContent', progress);
243
                    }
244
                });
245
            }
246
        });
247
    }
248
};
249