lib/commands/screenshot.js

Maintainability

65.05

Lines of code

253

Created with Raphaël 2.1.002550751002015-4-23

2015-4-23
Maintainability: 65.05

Created with Raphaël 2.1.00751502253002015-4-23

2015-4-23
Lines of Code: 253

Difficulty

33.76

Estimated Errors

1.83

Function weight

By Complexity

Created with Raphaël 2.1.0_parseDatetime6

By SLOC

Created with Raphaël 2.1.0_parseDatetime38
1
/*!
2
 *
3
 * Copyright (c) 2013 Sebastian Golasch
4
 *
5
 * Permission is hereby granted, free of charge, to any person obtaining a
6
 * copy of this software and associated documentation files (the "Software"),
7
 * to deal in the Software without restriction, including without limitation
8
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9
 * and/or sell copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be included
13
 * in all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21
 * DEALINGS IN THE SOFTWARE.
22
 *
23
 */
24
 
25
'use strict';
26
 
27
// ext. libs
28
var Q = require('q');
29
var fs = require('fs');
30
 
31
/**
32
 * Screenshot related methods
33
 *
34
 * @module Driver
35
 * @class Screenshot
36
 * @namespace Dalek.DriverNative.Commands
37
 */
38
 
39
var Screenshot = {
40
 
41
  /**
42
   * Makes an screenshot of the current page
43
   *
44
   * @method screenshot
45
   * @param {string} path Root directory path
46
   * @param {string} pathname Pathname of the screenshot path
47
   * @param {string} hash Unique hash of that fn call
48
   * @param {string} uuid Unique hash of that fn call
49
   * @chainable
50
   */
51
 
52
  screenshot: function (path, pathname, hash, uuid) {
53
    this.actionQueue.push(this.webdriverClient.screenshot.bind(this.webdriverClient));
54
    this.actionQueue.push(this._screenshotCb.bind(this, path, pathname, hash, uuid));
55
    return this;
56
  },
57
 
58
  /**
59
   * Sends out an event with the results of the `screenshot` call
60
   * and stores the screenshot in the filesystem
61
   *
62
   * @method _screenshotCb
63
   * @param {string} path Root directory path
64
   * @param {string} pathname Pathname of the screenshot path
65
   * @param {string} hash Unique hash of that fn call
66
   * @param {string} uuid Unique hash of that fn call
67
   * @param {string} result Serialized JSON result of the screenshot call
68
   * @return {object} promise Screenshot promise
69
   * @private
70
   */
71
 
72
  _screenshotCb: function (path, pathname, hash, uuid, result) {
73
    var deferred = Q.defer();
74
    // replace base64 metadata
75
    var base64Data = JSON.parse(result).value.replace(/^data:image\/png;base64,/,'');
76
    // replace placeholders
77
    var realpath = this._replacePathPlaceholder(path + pathname);
78
    // check if we need to add a new directory
79
    this._recursiveMakeDirSync(realpath.substring(0, realpath.lastIndexOf('/')));
80
    // write the screenshot
81
    fs.writeFileSync(realpath, base64Data, 'base64');
82
    this.events.emit('driver:message', {key: 'screenshot', value: realpath, uuid: hash, hash: hash});
83
    deferred.resolve();
84
    return deferred.promise;
85
  },
86
 
87
  /**
88
   * Recursige mkdir helper
89
   *
90
   * @method _recursiveMakeDirSync
91
   * @param {string} path Path to create
92
   * @private
93
   */
94
 
95
  _recursiveMakeDirSync: function (path) {
96
    var normalizedPath = require('path').normalize(path);
97
    var pathSep = require('path').sep;
98
    var dirs = normalizedPath.split(pathSep);
99
    var root = '';
100
 
101
    while (dirs.length > 0) {
102
      var dir = dirs.shift();
103
      if (dir === '') {
104
        root = pathSep;
105
      }
106
      if (!fs.existsSync(root + dir)) {
107
        fs.mkdirSync(root + dir);
108
      }
109
      root += dir + pathSep;
110
    }
111
  },
112
 
113
  /**
114
   * Return the formatted os name
115
   *
116
   * @method _parseOS
117
   * @param {string} Pathname 
118
   * @return {string} Formatted pathname
119
   * @private
120
   */
121
 
122
  _replacePathPlaceholder: function (pathname) {
123
    pathname = pathname.replace(':browser', this.browserName);
124
    pathname = pathname.replace(':version', this._parseBrowserVersion(this.sessionStatus.version));
125
    pathname = pathname.replace(':timestamp', Math.round(new Date().getTime() / 1000));
126
    pathname = pathname.replace(':osVersion', this._parseOSVersion(this.driverStatus.os.version));
127
    pathname = pathname.replace(':os', this._parseOS(this.driverStatus.os.name));
128
    pathname = pathname.replace(':datetime', this._parseDatetime());
129
    pathname = pathname.replace(':date', this._parseDate());
130
    pathname = pathname.replace(':viewport', this._parseViewport());
131
    return pathname;
132
  },
133
 
134
  /**
135
   * Return the formatted os name
136
   *
137
   * @method _parseOS
138
   * @return {string} OS name
139
   * @private
140
   */
141
 
142
  _parseOS: function (os) {
143
    var mappings = {
144
      'mac': 'OSX',
145
      'Mac OS X': 'OSX'
146
    };
147
    return mappings[os] || 'unknown';
148
  },
149
 
150
  /**
151
   * Return the formatted os version
152
   *
153
   * @method _parseOSVersion
154
   * @return {string} OS version
155
   * @private
156
   */
157
 
158
  _parseOSVersion: function (version) {
159
    var vs = version.replace(/[^0-9\\.]/g, '');
160
    vs = vs.replace(/\./g, '_');
161
    return vs;
162
  },
163
 
164
  /**
165
   * Return the formatted browser version
166
   *
167
   * @method _parseBrowserVersion
168
   * @return {string} Browser version
169
   * @private
170
   */
171
  
172
  _parseBrowserVersion: function (version) {
173
    return version.replace(/\./g, '_');
174
  },
175
 
176
  /**
177
   * Return the ISO 8601 formatted date
178
   *
179
   * @method _parseDate
180
   * @param {object} optional A javascript date object. If undefined, the current date is used.
181
   * @return {string} Date
182
   * @private
183
   */
184
 
185
  _parseDate: function (date) {
186
    date = date ? date : new Date();
187
    var day = date.getDate();
188
    var month = date.getMonth() + 1;
189
    var year = date.getFullYear();
190
 
191
    month = ('0' + month).slice(-2);
192
    day = ('0' + day).slice(-2);
193
 
194
    return year + '-' + month + '-' + day;
195
  },
196
 
197
  /**
198
   * Return the ISO 8601 formatted datetime
199
   *
200
   * @method _parseDatetime
201
   * @param {object} optional A javascript date object. If undefined, the current date is used.
202
   * @return {string} Datetime
203
   * @private
204
   */
205
 
206
  _parseDatetime: function (date) {
207
    date = date ? date : new Date();
208
    var dateStr = this._parseDate();
209
    var timeStr = 'T#hours#:#minutes#:#seconds##formattedOffset#';
210
    var hours = date.getHours();
211
    var minutes = date.getMinutes();
212
    var seconds = date.getSeconds();
213
    var offsetHours = '' + Math.ceil(date.getTimezoneOffset() / 60);
214
    var offsetMinutes = '' + Math.abs(date.getTimezoneOffset() % 60);
215
    var formattedOffset;
216
 
217
    hours = ('0' + hours).slice(-2);
218
    minutes = ('0' + minutes).slice(-2);
219
    seconds = ('0' + seconds).slice(-2);
220
 
221
    if (offsetHours[0] === '-' && offsetHours.length < 3) {
222
      formattedOffset = offsetHours[0] + '0' + offsetHours[1];
223
    } else if (offsetHours.length < 2) {
224
      formattedOffset = '+0' + offsetHours;
225
    }
226
 
227
    if (offsetMinutes.length < 2) {
228
      formattedOffset += ':0' + offsetMinutes;
229
    } else {
230
      formattedOffset += ':' + offsetMinutes;
231
    }
232
 
233
    if (offsetHours === '0' && offsetMinutes === '0') {
234
      formattedOffset = 'Z';
235
    }
236
 
237
    timeStr = timeStr.replace('#hours#', hours);
238
    timeStr = timeStr.replace('#minutes#', minutes);
239
    timeStr = timeStr.replace('#seconds#', seconds);
240
    timeStr = timeStr.replace('#formattedOffset#', formattedOffset);
241
 
242
    return dateStr + timeStr;
243
  },
244
 
245
  /**
246
   * Return the formatted viewport
247
   *
248
   * @method _parseViewport
249
   * @return {string} Viewport
250
   * @private
251
   */
252
 
253
  _parseViewport: function () {
254
    var viewport = this.config.get('viewport');
255
    return 'w' + viewport.width + '_h' + viewport.height;
256
  }
257
 
258
};
259
 
260
/**
261
 * Mixes in screenshot methods
262
 *
263
 * @param {Dalek.DriverNative} DalekNative Native driver base class
264
 * @return {Dalek.DriverNative} DalekNative Native driver base class
265
 */
266
 
267
module.exports = function (DalekNative) {
268
  if ('undefined' === typeof DalekNative) {
269
    return Screenshot;
270
  }
271
  // mixin methods
272
  Object.keys(Screenshot).forEach(function (fn) {
273
    DalekNative.prototype[fn] = Screenshot[fn];
274
  });
275
 
276
  return DalekNative;
277
};