cameraHelper.js 12 KB

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