Source: components/admin/controllers/icones.controller.js

  1. /**
  2. * @ngdoc controllers
  3. * @name Icones
  4. * @module s4c.components.admin.controllers.Icones
  5. *
  6. * @description
  7. * `AdminIconesCtrl` Controller da tela de Upload de Ícones do módulo de administração
  8. *
  9. *
  10. */
  11. (function () {
  12. 'use strict';
  13. AdminIconesCtrl.$inject = [
  14. '$scope',
  15. '$http',
  16. '$mdDialog',
  17. 'API_ENDPOINT',
  18. 'ngFileReader',
  19. '$rootScope',
  20. 'Usuario',
  21. 'FileUploader'
  22. ];
  23. angular.module('s4c.controllers.AdminIconesCtrl', [
  24. 's4c.services.Categoria',
  25. 's4c.directives.ngFileReader'
  26. ]).controller('AdminIconesCtrl', AdminIconesCtrl);
  27. function AdminIconesCtrl($scope, $http, $mdDialog, API_ENDPOINT, ngFileReader, $rootScope, Usuario, FileUploader) {
  28. $scope.res = $rootScope.res;
  29. /**
  30. * @method carregarIcones
  31. */
  32. function carregarIcones() {
  33. $http.get(API_ENDPOINT + "filemanager/showicons")
  34. .then(function (result) {
  35. $scope.listIcons = [];
  36. $scope.listIconsName = [];
  37. $scope.listIcons = result.data;
  38. for (var index in $scope.listIcons) {
  39. var str = $scope.listIcons[index].filePath;
  40. var n = str.indexOf("uploads");
  41. var res = str.substring(n, str.length);
  42. $scope.listIcons[index].filePath = res;
  43. $scope.listIconsName.push($scope.listIcons[index].fileName);
  44. }
  45. }, function (err) {
  46. $mdDialog
  47. .show($mdDialog.alert()
  48. .title($scope.res('COMUM_ERRO'))
  49. .content(err.data.message)
  50. .ok($scope.res('COMUM_OK')));
  51. });
  52. }
  53. /**
  54. * @method salvarImagem
  55. */
  56. function salvarImagem() {
  57. var eviarAlerta = false;
  58. for (var element in uploader.queue) {
  59. if ($.inArray(uploader.queue[element].novoNome, $scope.listIconsName) >= 0) {
  60. eviarAlerta = true;
  61. }
  62. }
  63. if (eviarAlerta) {
  64. var confirm = $mdDialog.confirm()
  65. .title($scope.res('COMUM_AVISO'))
  66. .content($scope.res('COMUM_ICONE_DUPLICADO'))
  67. .ok($scope.res('COMUM_SIM'))
  68. .cancel($scope.res('COMUM_CANCELAR'));
  69. $mdDialog.show(confirm).then(function () {
  70. enviarArquivo(true);
  71. }, function () {
  72. enviarArquivo(false);
  73. });
  74. } else {
  75. _salvarArquivo();
  76. }
  77. }
  78. /**
  79. * @method cancelar
  80. */
  81. function cancelar() {
  82. uploader.clearQueue();
  83. $("#renderCropper").empty();
  84. $scope.listIconsToRemove = [];
  85. }
  86. /**
  87. * @method toBlob
  88. */
  89. function toBlob() {
  90. var canvas = document.createElement('canvas');
  91. var ctx = canvas.getContext('2d');
  92. canvas.height = 400;
  93. canvas.width = 400;
  94. ctx.drawImage(document.getElementById('image'), 10, 10);
  95. if (canvas.toBlob) {
  96. canvas.toBlob(function (blob) {
  97. var formData = new FormData();
  98. var token = window.sessionStorage.getItem('s4cToken');
  99. var tokenObj = JSON.parse(token);
  100. formData.append('arquivo', blob, "arquivo.png");
  101. $.ajax('/filemanager/addarquivo', {
  102. method: "POST",
  103. data: formData,
  104. processData: false,
  105. contentType: false,
  106. headers: {
  107. 'Authorization': 'Bearer ' + tokenObj.access_token
  108. },
  109. success: function (data) {
  110. $("#renderCropper").empty();
  111. carregarIcones();
  112. },
  113. error: function () {
  114. console.log('Upload error');
  115. }
  116. });
  117. });
  118. }
  119. }
  120. $scope.input = angular.element('input.uploadArquivo');
  121. function abrirUpload() {
  122. $("#renderCropper").empty();
  123. $scope.input.click();
  124. $scope.listIconsToRemove = [];
  125. }
  126. var uploader = $scope.uploader = new FileUploader(),
  127. uploadCallbackQueue = [];
  128. uploader.clearQueue();
  129. $scope.uploader.filters.push({
  130. 'name': 'enforceMaxFileSize',
  131. 'fn': function (item, evt) {
  132. if (item.size <= 51200) {
  133. return item.size <= 51200
  134. } else {
  135. uploader.clearQueue();
  136. $mdDialog
  137. .show($mdDialog.alert()
  138. .title($scope.res('COMUM_TAMANHOFILEULTRAPASSADO'))
  139. .content($scope.res('LIMITE_ICONE_ULTRAPASSADO') + " " + parseInt(item.size / 1024) + "KB" + " - " + $scope.res('LIMITE_ULTRAPASSADO'))
  140. .ok($scope.res('COMUM_OK')));
  141. return item.size <= 51200;
  142. }
  143. }
  144. });
  145. $scope.uploader.filters.push({
  146. 'name': 'enforceTypeFile',
  147. 'fn': function (item, evt) {
  148. if (isImage(ext(item.name))) {
  149. return true;
  150. } else {
  151. $mdDialog
  152. .show($mdDialog.alert()
  153. .title($scope.res('COMUM_TIPO_ARQUIVO_INVALIDO'))
  154. .content($scope.res('COMUM_TIPO_IMAGEM_VALIDA'))
  155. .ok($scope.res('COMUM_OK')));
  156. return false;
  157. }
  158. }
  159. });
  160. $scope.uploader.onCompleteItem = function (item, response) {
  161. $scope.mensagem = response;
  162. };
  163. $scope.uploader.onAfterAddingFile = function (item, evt, arquivo) {
  164. item.novoNome = item.file.name;
  165. if (item.file) {
  166. _preview(item);
  167. }
  168. }
  169. /**
  170. * @method _preview
  171. * @param {*} item
  172. */
  173. function _preview(item) {
  174. var reader = new FileReader();
  175. reader.onload = function (e) {
  176. var label = $('<label />', {
  177. id: 'arquivo_anexado' + item.file.name,
  178. for: 'myvalue',
  179. class: 'fake-label nopad',
  180. }).appendTo($('#renderCropper'));
  181. $("#arquivo_anexado" + item.file.name).text(item.file.name);
  182. var img = $('<img />',
  183. {
  184. id: 'image',
  185. src: e.target.result,
  186. style: 'max-width: 24px; max-height: 24px; margin-left: 10px;'
  187. }).appendTo($('#renderCropper'));
  188. };
  189. reader.readAsDataURL(item._file);
  190. }
  191. function ext(filename) {
  192. var index = _.lastIndexOf(filename, '.');
  193. return filename.substring(index, filename.length);
  194. }
  195. $scope.uploader.onBeforeUploadItem = function (item) {
  196. item.url = uploader.url;
  197. var token = window.sessionStorage.getItem('s4cToken');
  198. try {
  199. var tokenObj = JSON.parse(token);
  200. item.headers = {
  201. 'Authorization': 'Bearer ' + tokenObj.access_token
  202. };
  203. } catch (erro) {
  204. item.headers = {
  205. 'Authorization': 'Bearer ' + token
  206. };
  207. }
  208. item.file.name = item.novoNome;
  209. };
  210. $scope.uploader.onProgressItem = function (fileItem, progress) {
  211. console.info('onProgressItem', fileItem, progress);
  212. //listaEquals = [];
  213. };
  214. $scope.uploader.onCompleteAll = function (result) {
  215. _.each(uploadCallbackQueue, function (callback) {
  216. callback();
  217. });
  218. };
  219. /**
  220. * @method mostrarImagem
  221. */
  222. $scope.mostrarImagem = function () {
  223. $('#arquivo').each(function (index) {
  224. if ($('#arquivo').eq(index).val() != "") {
  225. $scope.readURL(this);
  226. }
  227. });
  228. }
  229. /**
  230. * @method readURL
  231. */
  232. $scope.readURL = function (input) {
  233. if (input.files && input.files[index]) {
  234. var reader = new FileReader();
  235. reader.onload = function (e) {
  236. $("#renderCropper").empty();
  237. var label = $('<label />', {
  238. id: 'arquivo_anexado',
  239. for: 'myvalue',
  240. class: 'fake-label nopad',
  241. }).appendTo($('#renderCropper'));
  242. $("#arquivo_anexado").text(input.files[0]);
  243. var img = $('<img />',
  244. {
  245. id: 'image' + index,
  246. src: e.target.result,
  247. style: 'max-width: 24px; max-height: 24px;'
  248. }).appendTo($('#renderCropper'));
  249. };
  250. reader.readAsDataURL(input.files[0]);
  251. }
  252. }
  253. /**
  254. * @method enviarArquivo
  255. * @param {*} substituir
  256. */
  257. function enviarArquivo(substituir) {
  258. var listIconsToAdd = [];
  259. for (var element in uploader.queue) {
  260. if ($.inArray(uploader.queue[element].novoNome, $scope.listIconsName) >= 0 && substituir) {
  261. var iconToRemove = _.find($scope.listIcons, function (icons) { return icons.filePath.contains(uploader.queue[element].novoNome) });
  262. if (iconToRemove) {
  263. $scope.listIconsToRemove.push(iconToRemove.fileId);
  264. listIconsToAdd.push(uploader.queue[element]);
  265. }
  266. }
  267. else if ($.inArray(uploader.queue[element].novoNome, $scope.listIconsName) < 0) {
  268. listIconsToAdd.push(uploader.queue[element]);
  269. }
  270. }
  271. uploader.clearQueue();
  272. for (var index in listIconsToAdd) {
  273. uploader.queue.push(listIconsToAdd[index]);
  274. }
  275. if ($scope.listIconsToRemove.length > 0) {
  276. for (var index in $scope.listIconsToRemove) {
  277. $http.delete(API_ENDPOINT + "filemanager/" + $scope.listIconsToRemove[index]).then(function () {
  278. if (index == $scope.listIconsToRemove.length - 1) {
  279. _salvarArquivo();
  280. }
  281. });
  282. }
  283. } else {
  284. _salvarArquivo();
  285. }
  286. }
  287. /**
  288. * @method _salvarArquivo
  289. */
  290. function _salvarArquivo() {
  291. $scope.isUploading = true;
  292. uploader.url = '/filemanager/addarquivo/ICONE';
  293. uploader.uploadAll();
  294. uploadCallbackQueue.push(function () {
  295. $scope.isUploading = false;
  296. $scope.arquivosPraSubir = false;
  297. carregarIcones();
  298. });
  299. $("#renderCropper").empty();
  300. }
  301. $scope.uploader.alias = 'arquivo';
  302. $scope.uploader.removeAfterUpload = true;
  303. /**
  304. * @method copyUrlIcons
  305. * @param {*} icons
  306. */
  307. function copyUrlIcons(icons) {
  308. var tempInput = document.createElement("input");
  309. tempInput.style = "position: absolute; left: -1000px; top: -1000px";
  310. tempInput.value = icons.filePath;
  311. document.body.appendChild(tempInput);
  312. tempInput.select();
  313. document.execCommand("copy");
  314. document.body.removeChild(tempInput);
  315. $mdDialog.show({
  316. controller: function ($scope) {
  317. $scope.res = $scope.$root.res;
  318. $scope.icons = icons;
  319. $scope.ok = function () {
  320. $mdDialog.hide();
  321. };
  322. $scope.cancelar = function () {
  323. $mdDialog.cancel();
  324. };
  325. $scope.deleteIcons = function (icons) {
  326. var confirm = $mdDialog.confirm()
  327. .title($scope.res('COMUM_MENSAGEM_ACAOIRREVERSIVEL'))
  328. .content($scope.res('CERTEZA_REMOVER_ICONE'))
  329. .ok($scope.res('COMUM_SIM'))
  330. .cancel($scope.res('COMUM_CANCELAR'));
  331. $mdDialog.show(confirm).then(function () {
  332. $http.delete(API_ENDPOINT + "filemanager/" + icons.fileId)
  333. .then(function (result) {
  334. carregarIcones();
  335. $mdDialog
  336. .show($mdDialog.alert()
  337. .title($scope.res('COMUM_SUCESSO'))
  338. .content($scope.res('REMOVER_ICONE_SUCESSO'))
  339. .ok($scope.res('COMUM_OK')));
  340. }, function (err) {
  341. $mdDialog
  342. .show($mdDialog.alert()
  343. .title($scope.res('COMUM_ERRO'))
  344. .content(err.data.message)
  345. .ok($scope.res('COMUM_OK')));
  346. });
  347. }, function (err) {
  348. $mdDialog
  349. .show($mdDialog.alert()
  350. .title($scope.res('COMUM_ERRO'))
  351. .content(err.data.message)
  352. .ok($scope.res('COMUM_OK')));
  353. });
  354. };
  355. },
  356. templateUrl: 'app/components/admin/modulos/manutencao/icones/dialogIcones.html'
  357. });
  358. }
  359. /**
  360. * @method isImage
  361. * @param {*} extension
  362. */
  363. function isImage(extension) {
  364. if (extension.contains(".jpg")) {
  365. return true;
  366. }
  367. if (extension.contains(".jpeg")) {
  368. return true;
  369. }
  370. if (extension.contains(".png")) {
  371. return true;
  372. }
  373. if (extension.contains(".bmp")) {
  374. return true;
  375. }
  376. if (extension.contains(".svg")) {
  377. return true;
  378. }
  379. if (extension.contains(".gif")) {
  380. return true;
  381. }
  382. if (extension.contains(".tiff")) {
  383. return true;
  384. }
  385. if (extension.contains(".tif")) {
  386. return true;
  387. }
  388. return false;
  389. }
  390. $(function () {
  391. carregarIcones();
  392. });
  393. angular.extend($scope, {
  394. carregarIcones: carregarIcones,
  395. salvarImagem: salvarImagem,
  396. abrirUpload: abrirUpload,
  397. copyUrlIcons: copyUrlIcons,
  398. cancelar: cancelar
  399. });
  400. }
  401. }());