/tests/evernote/js/models/sap.js

https://gitlab.com/admin-github-cloud/jalangi2 · JavaScript · 460 lines · 302 code · 55 blank · 103 comment · 48 complexity · 40510625c288b79327bfa0a654241744 MD5 · raw file

  1. /*global define, $, console, tizen*/
  2. /*jslint regexp: true*/
  3. /**
  4. * SAP module
  5. */
  6. define({
  7. name: 'models/sap',
  8. requires: [
  9. 'core/event'
  10. ],
  11. def: function modelsSAP(e) {
  12. 'use strict';
  13. var sap = null,
  14. SAP_ID = '/system/evernoteforgear',
  15. SAP_NAME = 'evernoteforgear',
  16. SAP_ROLE = 'CONSUMER',
  17. SAP_CHANNEL_ID = 143,
  18. CONST_ERROR_TRIAL = 2,
  19. CONST_TIMEOUT = 15000,
  20. agent = null,
  21. sock = null,
  22. requestListener = null,
  23. sentData = '',
  24. trial = 2,
  25. acc = 0;
  26. function dispatchSuccess(data) {
  27. var param = {
  28. type:'success',
  29. data:data
  30. };
  31. e.fire(requestListener, param);
  32. requestListener = null;
  33. trial = CONST_ERROR_TRIAL;
  34. sentData = '';
  35. }
  36. function dispatchError(name, message) {
  37. e.fire(requestListener, {
  38. type:'error',
  39. name:name,
  40. message:message
  41. });
  42. requestListener = null;
  43. trial = CONST_ERROR_TRIAL;
  44. sentData = '';
  45. }
  46. // Errors
  47. // - OccuppiedError
  48. function dispatchImmediateError(listener, name, message) {
  49. e.fire(listener, {
  50. type:'error',
  51. name:name,
  52. message:message
  53. });
  54. }
  55. function sendData(listener, str) {
  56. try {
  57. sock.sendData(SAP_CHANNEL_ID, str);
  58. } catch(e) {
  59. console.error(e.name + ': ' + e.message);
  60. }
  61. sentData = str;
  62. trial--;
  63. requestListener = listener;
  64. acc++;
  65. }
  66. function mockRequestList(listener) {
  67. // the real code will send a request, receive a response
  68. // and finally trigger the event
  69. var dataObj = {
  70. id: 'notelistresp',
  71. count: 10,
  72. items: [
  73. {title: 'title', text: 'Simon'},
  74. {title: 'title', text: 'text'},
  75. {title: 'title', text: 'text'},
  76. {title: 'title', text: 'text'},
  77. {title: 'title', text: 'text'},
  78. {title: 'title', text: 'text'},
  79. {title: 'title', text: 'text'},
  80. {title: 'title', text: 'text'},
  81. {title: 'title', text: 'text'},
  82. {title: 'title', text: 'text'}
  83. ]
  84. };
  85. var param = {
  86. type:'success',
  87. data:dataObj
  88. };
  89. e.fire(listener, param);
  90. }
  91. function requestList(params) {
  92. var param = params.detail,
  93. listener = '',
  94. data = null,
  95. paramData = {
  96. id: 'notelistreq',
  97. request: 'list',
  98. count: 10
  99. };
  100. if(typeof param.listener !== 'string') {
  101. console.error('param is wrong');
  102. return;
  103. }
  104. listener = param.listener;
  105. if (typeof tizen === 'undefined' || typeof tizen.sa === 'undefined') {
  106. mockRequestList(listener);
  107. return;
  108. }
  109. if(requestListener != null) {
  110. console.error('waiting for result of the previous request');
  111. dispatchImmediateError(listener, 'OccupiedError', 'Still doing previous request.');
  112. return;
  113. }
  114. if(typeof sock !== 'object' || sock == null) {
  115. console.error('socket is not ready');
  116. dispatchImmediateError(listener, 'NotPreparedError', 'Initialization is not finished.');
  117. return;
  118. }
  119. if(!sock.isOpened()) {
  120. console.error('socket is closed');
  121. dispatchImmediateError(listener, 'NotPreparedError', 'Initialization is not finished.');
  122. return;
  123. }
  124. if(typeof param.data !== 'object') {
  125. console.error('param is wrong');
  126. dispatchImmediateError(listener, 'WrongParamError', 'Parameter is wrong.');
  127. return;
  128. }
  129. data = param.data;
  130. if(typeof data === 'object' &&
  131. data !== null &&
  132. data.count !== undefined &&
  133. typeof data.count === 'number') {
  134. paramData.count = data.count;
  135. }
  136. var jsonStr = JSON.stringify(paramData);
  137. sendData(listener, jsonStr);
  138. var currentAcc = acc;
  139. setTimeout(function() {
  140. if(requestListener != null &&
  141. currentAcc == acc) {
  142. console.error('Time out...');
  143. dispatchError('TimeoutError', 'Too long time after requested');
  144. }
  145. }, CONST_TIMEOUT);
  146. }
  147. function post(params) {
  148. var param = params.detail,
  149. listener = '',
  150. data = null,
  151. paramData = {
  152. id:'notepostreq'
  153. };
  154. if(typeof param.listener !== 'string') {
  155. console.error('param is wrong');
  156. return;
  157. }
  158. listener = param.listener;
  159. if(requestListener != null) {
  160. console.error('waiting for result of the previous request');
  161. dispatchImmediateError(listener, 'OccupiedError', 'Still doing previous request.');
  162. return;
  163. }
  164. if(typeof sock !== 'object' || sock == null) {
  165. console.error('socket is not ready');
  166. dispatchImmediateError(listener, 'NotPreparedError', 'Initialization is not finished.');
  167. return;
  168. }
  169. if(!sock.isOpened()) {
  170. console.error('socket is closed');
  171. dispatchImmediateError(listener, 'NotPreparedError', 'Initialization is not finished.');
  172. return;
  173. }
  174. if(typeof param.data !== 'object') {
  175. console.error('param is wrong');
  176. dispatchImmediateError(listener, 'WrongParamError', 'Parameter is wrong.');
  177. return;
  178. }
  179. data = param.data;
  180. if(typeof data === 'object' &&
  181. data !== null)
  182. {
  183. if(typeof data.title === 'string') {
  184. paramData.title = data.title;
  185. }
  186. if(typeof data.text === 'string') {
  187. paramData.text = data.text;
  188. }
  189. if(typeof data.image === 'object' &&
  190. data.image !== null) {
  191. paramData.image = data.image;
  192. }
  193. if(typeof data.audio === 'object' &&
  194. data.audio !== null) {
  195. paramData.audio = data.audio;
  196. }
  197. }
  198. var jsonStr = JSON.stringify(paramData);
  199. sendData(listener, jsonStr);
  200. var currentAcc = acc;
  201. setTimeout(function() {
  202. if(requestListener != null &&
  203. currentAcc == acc) {
  204. console.error('Time out...');
  205. dispatchError('TimeoutError', 'Too long time after requested');
  206. }
  207. }, CONST_TIMEOUT);
  208. }
  209. function onReceive(channelId, data) {
  210. var dataObj = null,
  211. newData = {
  212. channelId: channelId,
  213. data: null
  214. };
  215. if(requestListener == null) {
  216. console.error('Request already expired');
  217. return;
  218. }
  219. if(data === undefined ||
  220. typeof data !== 'string') {
  221. console.error('received data is not string');
  222. dispatchError('UnknownError', 'Wrong Data received.');
  223. return;
  224. }
  225. try {
  226. dataObj = JSON.parse(data);
  227. } catch(e) {
  228. console.error('JSON parse ' + e.name + ': ' + e.message);
  229. dispatchError('JSONError', 'Wrong Data.');
  230. return;
  231. }
  232. if(typeof dataObj !== 'object') {
  233. console.error('received data is not an object string');
  234. dispatchError('JSONError', 'Wrong Data.');
  235. return;
  236. }
  237. function reset() {
  238. requestListener = null;
  239. trial = CONST_ERROR_TRIAL;
  240. sentData = '';
  241. }
  242. if(typeof dataObj.id === 'string' &&
  243. dataObj.id === 'notelistresp') {
  244. dispatchSuccess(dataObj);
  245. } else if(typeof dataObj.result === 'string') {
  246. dispatchSuccess(dataObj);
  247. } else if(typeof dataObj.errormessage === 'string') {
  248. console.error('Error received : ' + dataObj.errormessage);
  249. if(trial == 0) {
  250. console.error('error done');
  251. dispatchError('RemoteError', dataObj.errormessage);
  252. } else {
  253. console.error('retry');
  254. sendData(requestListener, sentData);
  255. }
  256. } else {
  257. dispatchError('RemoteError', 'Received data is wrong');
  258. }
  259. }
  260. function init() {
  261. sap.requestSAAgent(
  262. {
  263. id : SAP_ID,
  264. name : SAP_NAME,
  265. role : SAP_ROLE,
  266. channelIds : [ SAP_CHANNEL_ID ]
  267. },
  268. function(agt) {
  269. try {
  270. console.log('requesteSAAgent succeed');
  271. agent = agt;
  272. agent.onserviceconnectionresponse = function(s) {
  273. console.log('socket created');
  274. sock = s;
  275. e.fire('models.sap.initdone', { status : 'ok' });
  276. };
  277. agent.initsocket = {
  278. onreceive : onReceive
  279. };
  280. agent.requestServiceConnection();
  281. } catch(err) {
  282. console.error(err.name + ': ' + err.message);
  283. }
  284. },
  285. function(err) {
  286. console.error(err.name + ': ' + err.message);
  287. }
  288. );
  289. // Don't do this if in mock mode
  290. // setTimeout(function() {
  291. // if(sock == null) {
  292. // console.error('initialize failed');
  293. // e.fire('models.sap.initdone',
  294. // {
  295. // status: 'error',
  296. // name: 'TimeoutError',
  297. // message: 'Failed to initialize SAP. Check connection with peer device.'
  298. // }
  299. // );
  300. // }
  301. // }, CONST_TIMEOUT);
  302. }
  303. e.listeners({
  304. 'models.sap.requestList': requestList,
  305. 'models.sap.post': post
  306. });
  307. if (typeof tizen !== 'undefined' && typeof tizen.sa !== 'undefined') {
  308. console.log('Track: sap: tizen not defined');
  309. sap = tizen.sa;
  310. } else {
  311. console.log('Track: sap: tizen defined');
  312. sap = {
  313. requestSAAgent: function requestSAAgentMock() {
  314. // requestSAAgent should trigger
  315. // 'models.sap.initdone' after some time'
  316. setTimeout(function triggerInitDone() {
  317. e.fire('models.sap.initdone', {status : 'ok'});
  318. }, 1500);
  319. }
  320. };
  321. }
  322. return {
  323. init: init,
  324. };
  325. }
  326. });
  327. /*
  328. * // Usage: request list
  329. *
  330. * var listener = 'models.sap.receiverequestedlist';
  331. *
  332. * e.listen(listener, function(params) {
  333. * var param = params.detail;
  334. * var type = param.type; // 'error' or 'success'
  335. * if( type == 'error') {
  336. * console.log('name: ' + param.name);
  337. * console.log('message: ' + param.message);
  338. * } else if(type == 'success') {
  339. * var data = param.data;
  340. * console.log('id: ' + data.id); // 'notelistresp'
  341. * console.log('count: ' + data.count);
  342. * for(var i=0; i<data.count; i++) {
  343. * console.log(' #' + i + '#');
  344. * console.log(' title : ' + data.items[i].title);
  345. * console.log(' text : ' + data.items[i].text);
  346. * console.log(' image mime : ' + data.items[i].image.mime);
  347. * console.log(' image name : ' + data.items[i].image.name);
  348. * //console.log(' image data : ' + data.items[i].image.data);
  349. * console.log(' audio mime : ' + data.items[i].audio.mime);
  350. * console.log(' audio name : ' + data.items[i].audio.name);
  351. * //console.log(' audio data : ' + data.items[i].audio.data);
  352. * }
  353. * }
  354. * });
  355. *
  356. * e.fire('model.sap.requestList',
  357. * {
  358. * listener: listener,
  359. * data: {
  360. * count: 10
  361. * }
  362. * }
  363. * );
  364. *
  365. */
  366. /*
  367. * // Usage: post
  368. *
  369. * var listener = 'models.sap.postdone';
  370. *
  371. * e.listen(listener, function(params) {
  372. * var param = params.detail;
  373. * var type = param.type; // 'error' or 'success'
  374. * if( type == 'error') {
  375. * console.log('name: ' + param.name);
  376. * console.log('message: ' + param.message);
  377. * } else if(type == 'success') {
  378. * var data = param.data;
  379. * console.log('result: ' + data.result); // 'success' or 'failed'
  380. * console.log('errormessage: ' + data.errormessage);
  381. * }
  382. * });
  383. *
  384. * e.fire('model.sap.post',
  385. * {
  386. * listener: listener,
  387. * data: {
  388. * title: 'Title',
  389. * text: 'Text',
  390. * image : {
  391. * name: 'Image name',
  392. * mime: 'image/jpeg',
  393. * data: ''
  394. * },
  395. * audio : {
  396. * name: 'Audio name',
  397. * mime: 'audio/mp3',
  398. * data: ''
  399. * }
  400. * }
  401. * }
  402. * );
  403. *
  404. *
  405. */