You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

308 lines
12 KiB

  1. /*jshint node: true */
  2. /* global Q, resolveLocalFileSystemURL, Camera, cordova */
  3. /*
  4. *
  5. * Licensed to the Apache Software Foundation (ASF) under one
  6. * or more contributor license agreements. See the NOTICE file
  7. * distributed with this work for additional information
  8. * regarding copyright ownership. The ASF licenses this file
  9. * to you under the Apache License, Version 2.0 (the
  10. * "License"); you may not use this file except in compliance
  11. * with the License. You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing,
  16. * software distributed under the License is distributed on an
  17. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18. * KIND, either express or implied. See the License for the
  19. * specific language governing permissions and limitations
  20. * under the License.
  21. *
  22. */
  23. 'use strict';
  24. var cameraConstants = require('../../www/CameraConstants');
  25. function findKeyByValue(set, value) {
  26. for (var k in set) {
  27. if (set.hasOwnProperty(k)) {
  28. if (set[k] == value) {
  29. return k;
  30. }
  31. }
  32. }
  33. return undefined;
  34. }
  35. function getDescription(spec) {
  36. var desc = '';
  37. desc += 'sourceType: ' + findKeyByValue(cameraConstants.PictureSourceType, spec.options.sourceType);
  38. desc += ', destinationType: ' + findKeyByValue(cameraConstants.DestinationType, spec.options.destinationType);
  39. desc += ', encodingType: ' + findKeyByValue(cameraConstants.EncodingType, spec.options.encodingType);
  40. desc += ', allowEdit: ' + spec.options.allowEdit.toString();
  41. desc += ', correctOrientation: ' + spec.options.correctOrientation.toString();
  42. return desc;
  43. }
  44. module.exports.generateSpecs = function (sourceTypes, destinationTypes, encodingTypes, allowEditOptions, correctOrientationOptions) {
  45. var destinationType,
  46. sourceType,
  47. encodingType,
  48. allowEdit,
  49. correctOrientation,
  50. specs = [],
  51. id = 1;
  52. for (destinationType in destinationTypes) {
  53. if (destinationTypes.hasOwnProperty(destinationType)) {
  54. for (sourceType in sourceTypes) {
  55. if (sourceTypes.hasOwnProperty(sourceType)) {
  56. for (encodingType in encodingTypes) {
  57. if (encodingTypes.hasOwnProperty(encodingType)) {
  58. for (allowEdit in allowEditOptions) {
  59. if (allowEditOptions.hasOwnProperty(allowEdit)) {
  60. for (correctOrientation in correctOrientationOptions) {
  61. // if taking picture from photolibrary, don't vary 'correctOrientation' option
  62. if ((sourceTypes[sourceType] === cameraConstants.PictureSourceType.PHOTOLIBRARY ||
  63. sourceTypes[sourceType] === cameraConstants.PictureSourceType.SAVEDPHOTOALBUM) &&
  64. correctOrientation === true) { continue; }
  65. var spec = {
  66. 'id': id++,
  67. 'options': {
  68. 'destinationType': destinationTypes[destinationType],
  69. 'sourceType': sourceTypes[sourceType],
  70. 'encodingType': encodingTypes[encodingType],
  71. 'allowEdit': allowEditOptions[allowEdit],
  72. 'saveToPhotoAlbum': false,
  73. 'correctOrientation': correctOrientationOptions[correctOrientation]
  74. }
  75. };
  76. spec.description = getDescription(spec);
  77. specs.push(spec);
  78. }
  79. }
  80. }
  81. }
  82. }
  83. }
  84. }
  85. }
  86. }
  87. return specs;
  88. };
  89. // calls getPicture() and saves the result in promise
  90. // note that this function is executed in the context of tested app
  91. // and not in the context of tests
  92. module.exports.getPicture = function (opts, pid) {
  93. if (navigator._appiumPromises[pid - 1]) {
  94. navigator._appiumPromises[pid - 1] = null;
  95. }
  96. navigator._appiumPromises[pid] = Q.defer();
  97. navigator.camera.getPicture(function (result) {
  98. navigator._appiumPromises[pid].resolve(result);
  99. }, function (err) {
  100. navigator._appiumPromises[pid].reject(err);
  101. }, opts);
  102. };
  103. // verifies taken picture when the promise is resolved,
  104. // calls a callback with 'OK' if everything is good,
  105. // calls a callback with 'ERROR: <error message>' if something is wrong
  106. // note that this function is executed in the context of tested app
  107. // and not in the context of tests
  108. module.exports.checkPicture = function (pid, options, cb) {
  109. var isIos = cordova.platformId === "ios";
  110. var isAndroid = cordova.platformId === "android";
  111. // skip image type check if it's unmodified on Android:
  112. // https://github.com/apache/cordova-plugin-camera/#android-quirks-1
  113. var skipFileTypeCheckAndroid = isAndroid && options.quality === 100 &&
  114. !options.targetWidth && !options.targetHeight &&
  115. !options.correctOrientation;
  116. // Skip image type check if destination is NATIVE_URI and source - device's photoalbum
  117. // https://github.com/apache/cordova-plugin-camera/#ios-quirks-1
  118. var skipFileTypeCheckiOS = isIos && options.destinationType === Camera.DestinationType.NATIVE_URI &&
  119. (options.sourceType === Camera.PictureSourceType.PHOTOLIBRARY ||
  120. options.sourceType === Camera.PictureSourceType.SAVEDPHOTOALBUM);
  121. var skipFileTypeCheck = skipFileTypeCheckAndroid || skipFileTypeCheckiOS;
  122. var desiredType = 'JPEG';
  123. var mimeType = 'image/jpeg';
  124. if (options.encodingType === Camera.EncodingType.PNG) {
  125. desiredType = 'PNG';
  126. mimeType = 'image/png';
  127. }
  128. function errorCallback(msg) {
  129. if (msg.hasOwnProperty('message')) {
  130. msg = msg.message;
  131. }
  132. cb('ERROR: ' + msg);
  133. }
  134. // verifies the image we get from plugin
  135. function verifyResult(result) {
  136. if (result.length === 0) {
  137. errorCallback('The result is empty.');
  138. return;
  139. } else if (isIos && options.destinationType === Camera.DestinationType.NATIVE_URI && result.indexOf('assets-library:') !== 0) {
  140. errorCallback('Expected "' + result.substring(0, 150) + '"to start with "assets-library:"');
  141. return;
  142. } else if (isIos && options.destinationType === Camera.DestinationType.FILE_URI && result.indexOf('file:') !== 0) {
  143. errorCallback('Expected "' + result.substring(0, 150) + '"to start with "file:"');
  144. return;
  145. }
  146. try {
  147. window.atob(result);
  148. // if we got here it is a base64 string (DATA_URL)
  149. result = "data:" + mimeType + ";base64," + result;
  150. } catch (e) {
  151. // not DATA_URL
  152. if (options.destinationType === Camera.DestinationType.DATA_URL) {
  153. errorCallback('Expected ' + result.substring(0, 150) + 'not to be DATA_URL');
  154. return;
  155. }
  156. }
  157. try {
  158. if (result.indexOf('file:') === 0 ||
  159. result.indexOf('content:') === 0 ||
  160. result.indexOf('assets-library:') === 0) {
  161. if (!window.resolveLocalFileSystemURL) {
  162. errorCallback('Cannot read file. Please install cordova-plugin-file to fix this.');
  163. return;
  164. }
  165. resolveLocalFileSystemURL(result, function (entry) {
  166. if (skipFileTypeCheck) {
  167. displayFile(entry);
  168. } else {
  169. verifyFile(entry);
  170. }
  171. }, function (err) {
  172. errorCallback(err);
  173. });
  174. } else {
  175. displayImage(result);
  176. }
  177. } catch (e) {
  178. errorCallback(e);
  179. }
  180. }
  181. // verifies that the file type matches the requested type
  182. function verifyFile(entry) {
  183. try {
  184. var reader = new FileReader();
  185. reader.onloadend = function(e) {
  186. var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
  187. var header = '';
  188. for(var i = 0; i < arr.length; i++) {
  189. header += arr[i].toString(16);
  190. }
  191. var actualType = 'unknown';
  192. switch (header) {
  193. case "89504e47":
  194. actualType = 'PNG';
  195. break;
  196. case 'ffd8ffe0':
  197. case 'ffd8ffe1':
  198. case 'ffd8ffe2':
  199. actualType = 'JPEG';
  200. break;
  201. }
  202. if (actualType === desiredType) {
  203. displayFile(entry);
  204. } else {
  205. errorCallback('File type mismatch. Expected ' + desiredType + ', got ' + actualType);
  206. }
  207. };
  208. reader.onerror = function (e) {
  209. errorCallback(e);
  210. };
  211. entry.file(function (file) {
  212. reader.readAsArrayBuffer(file);
  213. }, function (e) {
  214. errorCallback(e);
  215. });
  216. } catch (e) {
  217. errorCallback(e);
  218. }
  219. }
  220. // reads the file, then displays the image
  221. function displayFile(entry) {
  222. function onFileReceived(file) {
  223. var reader = new FileReader();
  224. reader.onerror = function (e) {
  225. errorCallback(e);
  226. };
  227. reader.onloadend = function (evt) {
  228. displayImage(evt.target.result);
  229. };
  230. reader.readAsDataURL(file);
  231. }
  232. entry.file(onFileReceived, function (e) {
  233. errorCallback(e);
  234. });
  235. }
  236. function displayImage(image) {
  237. try {
  238. var imgEl = document.getElementById('camera_test_image');
  239. if (!imgEl) {
  240. imgEl = document.createElement('img');
  241. imgEl.id = 'camera_test_image';
  242. document.body.appendChild(imgEl);
  243. }
  244. var timedOut = false;
  245. var loadTimeout = setTimeout(function () {
  246. timedOut = true;
  247. imgEl.src = '';
  248. errorCallback('The image did not load: ' + image.substring(0, 150));
  249. }, 10000);
  250. var done = function (status) {
  251. if (!timedOut) {
  252. clearTimeout(loadTimeout);
  253. imgEl.src = '';
  254. cb(status);
  255. }
  256. };
  257. imgEl.onload = function () {
  258. try {
  259. // aspect ratio is preserved so only one dimension should match
  260. if ((typeof options.targetWidth === 'number' && imgEl.naturalWidth !== options.targetWidth) &&
  261. (typeof options.targetHeight === 'number' && imgEl.naturalHeight !== options.targetHeight))
  262. {
  263. done('ERROR: Wrong image size: ' + imgEl.naturalWidth + 'x' + imgEl.naturalHeight +
  264. '. Requested size: ' + options.targetWidth + 'x' + options.targetHeight);
  265. } else {
  266. done('OK');
  267. }
  268. } catch (e) {
  269. errorCallback(e);
  270. }
  271. };
  272. imgEl.src = image;
  273. } catch (e) {
  274. errorCallback(e);
  275. }
  276. }
  277. navigator._appiumPromises[pid].promise
  278. .then(function (result) {
  279. verifyResult(result);
  280. })
  281. .fail(function (e) {
  282. errorCallback(e);
  283. });
  284. };